Repository: fastly/js-compute-runtime Branch: main Commit: b6f41b0bcf42 Files: 9622 Total size: 15.6 MB Directory structure: gitextract_lduunf0x/ ├── .clang-format ├── .github/ │ ├── dependabot.yml │ └── workflows/ │ ├── cleanup.yml │ ├── dependencies.yml │ ├── main.yml │ └── release-please.yml ├── .gitignore ├── .gitmodules ├── .prettierrc.json ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── DEVELOPMENT.md ├── LICENSE ├── README.md ├── SECURITY.md ├── ci/ │ ├── build-tarballs.sh │ ├── clang-format.ignore │ ├── clang-format.sh │ ├── format-changelog.js │ ├── rustfmt.sh │ └── shellcheck.sh ├── compute-file-server-cli/ │ ├── .gitignore │ ├── Cargo.toml │ ├── LICENSE │ ├── README.md │ ├── rust-toolchain.toml │ └── src/ │ └── main.rs ├── documentation/ │ ├── .gitignore │ ├── LICENSE.md │ ├── README.md │ ├── app/ │ │ ├── .gitignore │ │ ├── c-at-e-file-server.js │ │ ├── fastly.toml │ │ ├── package.json │ │ ├── src/ │ │ │ └── index.js │ │ └── version-redirects.json │ ├── docs/ │ │ ├── acl/ │ │ │ └── Acl/ │ │ │ ├── open.mdx │ │ │ └── prototype/ │ │ │ └── lookup.mdx │ │ ├── backend/ │ │ │ ├── Backend/ │ │ │ │ ├── Backend.mdx │ │ │ │ ├── exists.mdx │ │ │ │ ├── fromName.mdx │ │ │ │ ├── health.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── betweenBytesTimeout.mdx │ │ │ │ ├── connectTimeout.mdx │ │ │ │ ├── firstByteTimeout.mdx │ │ │ │ ├── health.mdx │ │ │ │ ├── hostOverride.mdx │ │ │ │ ├── httpKeepaliveTime.mdx │ │ │ │ ├── isDynamic.mdx │ │ │ │ ├── isSSL.mdx │ │ │ │ ├── name.mdx │ │ │ │ ├── port.mdx │ │ │ │ ├── target.mdx │ │ │ │ ├── tcpKeepalive.mdx │ │ │ │ ├── tlsMaxVersion.mdx │ │ │ │ ├── tlsMinVersion.mdx │ │ │ │ ├── toName.mdx │ │ │ │ └── toString.mdx │ │ │ ├── allowDynamicBackends.mdx │ │ │ ├── enforceExplicitBackends.mdx │ │ │ └── setDefaultDynamicBackendConfig.mdx │ │ ├── cache/ │ │ │ ├── CacheEntry/ │ │ │ │ ├── age.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── hits.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── maxAge.mdx │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ ├── state.mdx │ │ │ │ └── userMetadata.mdx │ │ │ ├── CacheState/ │ │ │ │ ├── found.mdx │ │ │ │ ├── mustInsertOrUpdate.mdx │ │ │ │ ├── stale.mdx │ │ │ │ └── usable.mdx │ │ │ ├── CoreCache/ │ │ │ │ ├── insert.mdx │ │ │ │ ├── lookup.mdx │ │ │ │ └── transactionLookup.mdx │ │ │ ├── SimpleCache/ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── getOrSet.mdx │ │ │ │ └── purge.mdx │ │ │ ├── SimpleCacheEntry/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ └── text.mdx │ │ │ └── TransactionCacheEntry/ │ │ │ ├── age.mdx │ │ │ ├── body.mdx │ │ │ ├── cancel.mdx │ │ │ ├── close.mdx │ │ │ ├── hits.mdx │ │ │ ├── insert.mdx │ │ │ ├── insertAndStreamBack.mdx │ │ │ ├── length.mdx │ │ │ ├── maxAge.mdx │ │ │ ├── staleWhileRevalidate.mdx │ │ │ ├── state.mdx │ │ │ ├── update.mdx │ │ │ └── userMetadata.mdx │ │ ├── cache-override/ │ │ │ └── CacheOverride/ │ │ │ └── CacheOverride.mdx │ │ ├── compute/ │ │ │ ├── purgeSurrogateKey.mdx │ │ │ └── vCpuTime.mdx │ │ ├── config-store/ │ │ │ └── ConfigStore/ │ │ │ ├── ConfigStore.mdx │ │ │ └── prototype/ │ │ │ └── get.mdx │ │ ├── device/ │ │ │ └── Device/ │ │ │ ├── lookup.mdx │ │ │ └── prototype/ │ │ │ ├── brand.mdx │ │ │ ├── hardwareType.mdx │ │ │ ├── isBot.mdx │ │ │ ├── isDesktop.mdx │ │ │ ├── isGameConsole.mdx │ │ │ ├── isMediaPlayer.mdx │ │ │ ├── isMobile.mdx │ │ │ ├── isSmartTV.mdx │ │ │ ├── isTablet.mdx │ │ │ ├── isTouchscreen.mdx │ │ │ ├── model.mdx │ │ │ ├── name.mdx │ │ │ └── toJSON.mdx │ │ ├── dictionary/ │ │ │ └── Dictionary/ │ │ │ ├── Dictionary.mdx │ │ │ └── prototype/ │ │ │ └── get.mdx │ │ ├── edge-rate-limiter/ │ │ │ ├── EdgeRateLimiter/ │ │ │ │ ├── EdgeRateLimiter.mdx │ │ │ │ └── prototype/ │ │ │ │ └── checkRate.mdx │ │ │ ├── PenaltyBox/ │ │ │ │ ├── PenaltyBox.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── add.mdx │ │ │ │ └── has.mdx │ │ │ └── RateCounter/ │ │ │ ├── RateCounter.mdx │ │ │ └── prototype/ │ │ │ ├── increment.mdx │ │ │ ├── lookupCount.mdx │ │ │ └── lookupRate.mdx │ │ ├── env/ │ │ │ └── env.mdx │ │ ├── experimental/ │ │ │ ├── allowDynamicBackends.mdx │ │ │ ├── includeBytes.mdx │ │ │ ├── mapAndLogError.mdx │ │ │ ├── mapError.mdx │ │ │ ├── sdkVersion.mdx │ │ │ └── setReusableSandboxOptions.mdx │ │ ├── fanout/ │ │ │ └── createFanoutHandoff.mdx │ │ ├── geolocation/ │ │ │ └── getGeolocationForIpAddress.mdx │ │ ├── globals/ │ │ │ ├── AggregrateError/ │ │ │ │ └── AggregrateError.mdx │ │ │ ├── Array/ │ │ │ │ ├── @@species.mdx │ │ │ │ ├── Array.mdx │ │ │ │ ├── from.mdx │ │ │ │ ├── isArray.mdx │ │ │ │ ├── of.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── @@iterator.mdx │ │ │ │ ├── @@unscopables.mdx │ │ │ │ ├── at.mdx │ │ │ │ ├── concat.mdx │ │ │ │ ├── copyWithin.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── every.mdx │ │ │ │ ├── fill.mdx │ │ │ │ ├── filter.mdx │ │ │ │ ├── find.mdx │ │ │ │ ├── findIndex.mdx │ │ │ │ ├── flat.mdx │ │ │ │ ├── flatMap.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── includes.mdx │ │ │ │ ├── indexOf.mdx │ │ │ │ ├── join.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── map.mdx │ │ │ │ ├── pop.mdx │ │ │ │ ├── push.mdx │ │ │ │ ├── reduce.mdx │ │ │ │ ├── reduceRight.mdx │ │ │ │ ├── reverse.mdx │ │ │ │ ├── shift.mdx │ │ │ │ ├── slice.mdx │ │ │ │ ├── some.mdx │ │ │ │ ├── sort.mdx │ │ │ │ ├── splice.mdx │ │ │ │ ├── toLocaleString.mdx │ │ │ │ ├── toString.mdx │ │ │ │ ├── unshift.mdx │ │ │ │ └── values.mdx │ │ │ ├── ArrayBuffer/ │ │ │ │ ├── @@species.mdx │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ ├── isView.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── byteLength.mdx │ │ │ │ └── slice.mdx │ │ │ ├── BigInt/ │ │ │ │ ├── BigInt.mdx │ │ │ │ ├── asIntN.mdx │ │ │ │ ├── asUintN.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ ├── toString.mdx │ │ │ │ └── valueOf.mdx │ │ │ ├── BigInt64Array/ │ │ │ │ └── BigInt64Array.mdx │ │ │ ├── BigUint64Array/ │ │ │ │ └── BigUint64Array.mdx │ │ │ ├── Blob/ │ │ │ │ ├── Blob.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── size.mdx │ │ │ │ ├── slice.mdx │ │ │ │ ├── stream.mdx │ │ │ │ ├── text.mdx │ │ │ │ └── type.mdx │ │ │ ├── Boolean/ │ │ │ │ ├── Boolean.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── toString.mdx │ │ │ │ └── valueOf.mdx │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ └── prototype/ │ │ │ │ └── size.mdx │ │ │ ├── CompressionStream/ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── readable.mdx │ │ │ │ └── writable.mdx │ │ │ ├── CryptoKey/ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── algorithm.mdx │ │ │ │ ├── extractable.mdx │ │ │ │ ├── type.mdx │ │ │ │ └── usages.mdx │ │ │ ├── DOMException/ │ │ │ │ ├── DOMException.mdx │ │ │ │ ├── code.mdx │ │ │ │ ├── message.mdx │ │ │ │ └── name.mdx │ │ │ ├── DataView/ │ │ │ │ ├── DataView.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── buffer.mdx │ │ │ │ ├── byteLength.mdx │ │ │ │ ├── byteOffset.mdx │ │ │ │ ├── getBigInt64.mdx │ │ │ │ ├── getBigUint64.mdx │ │ │ │ ├── getFloat32.mdx │ │ │ │ ├── getFloat64.mdx │ │ │ │ ├── getInt16.mdx │ │ │ │ ├── getInt32.mdx │ │ │ │ ├── getInt8.mdx │ │ │ │ ├── getUint16.mdx │ │ │ │ ├── getUint32.mdx │ │ │ │ ├── getUint8.mdx │ │ │ │ ├── setBigInt64.mdx │ │ │ │ ├── setBigUint64.mdx │ │ │ │ ├── setFloat32.mdx │ │ │ │ ├── setFloat64.mdx │ │ │ │ ├── setInt16.mdx │ │ │ │ ├── setInt32.mdx │ │ │ │ ├── setInt8.mdx │ │ │ │ ├── setUint16.mdx │ │ │ │ ├── setUint32.mdx │ │ │ │ └── setUint8.mdx │ │ │ ├── Date/ │ │ │ │ ├── Date.mdx │ │ │ │ ├── UTC.mdx │ │ │ │ ├── now.mdx │ │ │ │ ├── parse.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ ├── getDate.mdx │ │ │ │ ├── getDay.mdx │ │ │ │ ├── getFullYear.mdx │ │ │ │ ├── getHours.mdx │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ ├── getMinutes.mdx │ │ │ │ ├── getMonth.mdx │ │ │ │ ├── getSeconds.mdx │ │ │ │ ├── getTime.mdx │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ ├── getUTCDate.mdx │ │ │ │ ├── getUTCDay.mdx │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ ├── getUTCHours.mdx │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ ├── getYear.mdx │ │ │ │ ├── setDate.mdx │ │ │ │ ├── setFullYear.mdx │ │ │ │ ├── setHours.mdx │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ ├── setMinutes.mdx │ │ │ │ ├── setMonth.mdx │ │ │ │ ├── setSeconds.mdx │ │ │ │ ├── setTime.mdx │ │ │ │ ├── setUTCDate.mdx │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ ├── setUTCHours.mdx │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ ├── setYear.mdx │ │ │ │ ├── toDateString.mdx │ │ │ │ ├── toISOString.mdx │ │ │ │ ├── toJSON.mdx │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ ├── toLocaleString.mdx │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ ├── toString.mdx │ │ │ │ ├── toTimeString.mdx │ │ │ │ ├── toUTCString.mdx │ │ │ │ └── valueOf.mdx │ │ │ ├── DecompressionStream/ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── readable.mdx │ │ │ │ └── writable.mdx │ │ │ ├── EcKeyImportParams/ │ │ │ │ └── EcKeyImportParams.mdx │ │ │ ├── EcdsaParams/ │ │ │ │ └── EcdsaParams.mdx │ │ │ ├── Error/ │ │ │ │ ├── Error.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── cause.mdx │ │ │ │ ├── message.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toString.mdx │ │ │ ├── EvalError/ │ │ │ │ └── EvalError.mdx │ │ │ ├── FetchEvent/ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── respondWith.mdx │ │ │ │ ├── sendEarlyHints.mdx │ │ │ │ └── waitUntil.mdx │ │ │ ├── FinalizationRegistry/ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── register.mdx │ │ │ │ └── unregister.mdx │ │ │ ├── Float32Array/ │ │ │ │ └── Float32Array.mdx │ │ │ ├── Float64Array/ │ │ │ │ └── Float64Array.mdx │ │ │ ├── FormData/ │ │ │ │ ├── FormData.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── append.mdx │ │ │ │ ├── delete.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── getAll.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── set.mdx │ │ │ │ └── values.mdx │ │ │ ├── Function/ │ │ │ │ ├── Function.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── apply.mdx │ │ │ │ ├── bind.mdx │ │ │ │ ├── call.mdx │ │ │ │ ├── index.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toString.mdx │ │ │ ├── Headers/ │ │ │ │ ├── Headers.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── append.mdx │ │ │ │ ├── delete.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── getSetCookie.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── set.mdx │ │ │ │ └── values.mdx │ │ │ ├── HmacImportParams/ │ │ │ │ └── HmacImportParams.mdx │ │ │ ├── Infinity.mdx │ │ │ ├── Int16Array/ │ │ │ │ └── Int16Array.mdx │ │ │ ├── Int32Array/ │ │ │ │ └── Int32Array.mdx │ │ │ ├── Int8Array/ │ │ │ │ └── Int8Array.mdx │ │ │ ├── JSON/ │ │ │ │ ├── parse.mdx │ │ │ │ └── stringify.mdx │ │ │ ├── Map/ │ │ │ │ ├── @@species.mdx │ │ │ │ ├── Map.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── @@iterator.mdx │ │ │ │ ├── clear.mdx │ │ │ │ ├── delete.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── set.mdx │ │ │ │ ├── size.mdx │ │ │ │ └── values.mdx │ │ │ ├── Math/ │ │ │ │ ├── E.mdx │ │ │ │ ├── LN10.mdx │ │ │ │ ├── LN2.mdx │ │ │ │ ├── LOG10e.mdx │ │ │ │ ├── LOG2e.mdx │ │ │ │ ├── PI.mdx │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ ├── SQRT2.mdx │ │ │ │ ├── abs.mdx │ │ │ │ ├── acos.mdx │ │ │ │ ├── acosh.mdx │ │ │ │ ├── asin.mdx │ │ │ │ ├── asinh.mdx │ │ │ │ ├── atan.mdx │ │ │ │ ├── atan2.mdx │ │ │ │ ├── atanh.mdx │ │ │ │ ├── cbrt.mdx │ │ │ │ ├── ceil.mdx │ │ │ │ ├── clz32.mdx │ │ │ │ ├── cos.mdx │ │ │ │ ├── cosh.mdx │ │ │ │ ├── exp.mdx │ │ │ │ ├── expm1.mdx │ │ │ │ ├── floor.mdx │ │ │ │ ├── fround.mdx │ │ │ │ ├── hypot.mdx │ │ │ │ ├── imul.mdx │ │ │ │ ├── log.mdx │ │ │ │ ├── log10.mdx │ │ │ │ ├── log1p.mdx │ │ │ │ ├── log2.mdx │ │ │ │ ├── max.mdx │ │ │ │ ├── min.mdx │ │ │ │ ├── pow.mdx │ │ │ │ ├── random.mdx │ │ │ │ ├── round.mdx │ │ │ │ ├── sign.mdx │ │ │ │ ├── sin.mdx │ │ │ │ ├── sinh.mdx │ │ │ │ ├── sqrt.mdx │ │ │ │ ├── tan.mdx │ │ │ │ ├── tanh.mdx │ │ │ │ └── trunc.mdx │ │ │ ├── NaN.mdx │ │ │ ├── Number/ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number.mdx │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ ├── epsilon.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isInteger.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── toExponential.mdx │ │ │ │ ├── toFixed.mdx │ │ │ │ ├── toLocaleString.mdx │ │ │ │ ├── toPrecision.mdx │ │ │ │ ├── toString.mdx │ │ │ │ └── valueOf.mdx │ │ │ ├── Object/ │ │ │ │ ├── Object.mdx │ │ │ │ ├── assign.mdx │ │ │ │ ├── create.mdx │ │ │ │ ├── defineProperties.mdx │ │ │ │ ├── defineProperty.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── freeze.mdx │ │ │ │ ├── fromEntries.mdx │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ ├── hasOwn.mdx │ │ │ │ ├── is.mdx │ │ │ │ ├── isExtensible.mdx │ │ │ │ ├── isFrozen.mdx │ │ │ │ ├── isSealed.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── preventExtensions.mdx │ │ │ │ ├── prototype/ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── seal.mdx │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ └── values.mdx │ │ │ ├── Promise/ │ │ │ │ ├── @@species.mdx │ │ │ │ ├── Promise.mdx │ │ │ │ ├── all.mdx │ │ │ │ ├── allSettled.mdx │ │ │ │ ├── any.mdx │ │ │ │ ├── prototype/ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ ├── finally.mdx │ │ │ │ │ └── then.mdx │ │ │ │ ├── race.mdx │ │ │ │ ├── reject.mdx │ │ │ │ └── resolve.mdx │ │ │ ├── Proxy/ │ │ │ │ ├── Proxy.mdx │ │ │ │ ├── proxy/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ └── revocable.mdx │ │ │ ├── RangeError/ │ │ │ │ └── RangeError.mdx │ │ │ ├── ReadableByteStreamController/ │ │ │ │ └── prototype/ │ │ │ │ ├── byobRequest.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── desiredSize.mdx │ │ │ │ ├── enqueue.mdx │ │ │ │ └── error.mdx │ │ │ ├── ReadableStream/ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── cancel.mdx │ │ │ │ ├── getReader.mdx │ │ │ │ ├── locked.mdx │ │ │ │ ├── pipeThrough.mdx │ │ │ │ ├── pipeTo.mdx │ │ │ │ └── tee.mdx │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── cancel.mdx │ │ │ │ ├── closed.mdx │ │ │ │ ├── read.mdx │ │ │ │ └── releaseLock.mdx │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ └── prototype/ │ │ │ │ ├── respond.mdx │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ └── view.mdx │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ └── prototype/ │ │ │ │ ├── close.mdx │ │ │ │ ├── desiredSize.mdx │ │ │ │ ├── enqueue.mdx │ │ │ │ └── error.mdx │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── cancel.mdx │ │ │ │ ├── closed.mdx │ │ │ │ ├── read.mdx │ │ │ │ └── releaseLock.mdx │ │ │ ├── ReferenceError/ │ │ │ │ └── ReferenceError.mdx │ │ │ ├── Reflect/ │ │ │ │ ├── apply.mdx │ │ │ │ ├── construct.mdx │ │ │ │ ├── defineProperty.mdx │ │ │ │ ├── deleteProperty.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── isExtensible.mdx │ │ │ │ ├── ownKeys.mdx │ │ │ │ ├── preventExtensions.mdx │ │ │ │ ├── set.mdx │ │ │ │ └── setPrototypeOf.mdx │ │ │ ├── Request/ │ │ │ │ ├── Request.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── blob.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── clone.mdx │ │ │ │ ├── formData.mdx │ │ │ │ ├── headers.mdx │ │ │ │ ├── json.mdx │ │ │ │ ├── method.mdx │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ ├── text.mdx │ │ │ │ └── url.mdx │ │ │ ├── Response/ │ │ │ │ ├── Response.mdx │ │ │ │ ├── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── blob.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── formData.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── ip.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── ok.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ ├── status.mdx │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ └── redirect.mdx │ │ │ ├── RsaHashedImportParams/ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ ├── Set/ │ │ │ │ ├── @@species.mdx │ │ │ │ ├── Set.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── @@iterator.mdx │ │ │ │ ├── add.mdx │ │ │ │ ├── clear.mdx │ │ │ │ ├── delete.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── size.mdx │ │ │ │ └── values.mdx │ │ │ ├── String/ │ │ │ │ ├── String.mdx │ │ │ │ ├── fromCharCode.mdx │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ ├── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ ├── substr.mdx │ │ │ │ │ ├── substring.mdx │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ ├── trim.mdx │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ └── raw.mdx │ │ │ ├── SubtleCrypto/ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── digest.mdx │ │ │ │ ├── importKey.mdx │ │ │ │ ├── sign.mdx │ │ │ │ └── verify.mdx │ │ │ ├── Symbol/ │ │ │ │ ├── Symbol.mdx │ │ │ │ ├── asyncIterator.mdx │ │ │ │ ├── for.mdx │ │ │ │ ├── hasInstance.mdx │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ ├── iterator.mdx │ │ │ │ ├── keyFor.mdx │ │ │ │ ├── match.mdx │ │ │ │ ├── matchAll.mdx │ │ │ │ ├── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── description.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── replace.mdx │ │ │ │ ├── search.mdx │ │ │ │ ├── species.mdx │ │ │ │ ├── split.mdx │ │ │ │ ├── toPrimitive.mdx │ │ │ │ ├── toStringTag.mdx │ │ │ │ └── unscopables.mdx │ │ │ ├── SyntaxError/ │ │ │ │ └── SyntaxError.mdx │ │ │ ├── TextDecoder/ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── decode.mdx │ │ │ │ ├── encoding.mdx │ │ │ │ ├── fatal.mdx │ │ │ │ └── ignoreBOM.mdx │ │ │ ├── TextEncoder/ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── encode.mdx │ │ │ │ └── encoding.mdx │ │ │ ├── TransformStream/ │ │ │ │ ├── TransformStream.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── readable.mdx │ │ │ │ └── writable.mdx │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ └── prototype/ │ │ │ │ ├── desiredSize.mdx │ │ │ │ ├── enqueue.mdx │ │ │ │ ├── error.mdx │ │ │ │ └── terminate.mdx │ │ │ ├── TypeError/ │ │ │ │ └── TypeError.mdx │ │ │ ├── URIError/ │ │ │ │ └── URIError.mdx │ │ │ ├── URL/ │ │ │ │ ├── URL.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── hash.mdx │ │ │ │ ├── host.mdx │ │ │ │ ├── hostname.mdx │ │ │ │ ├── href.mdx │ │ │ │ ├── origin.mdx │ │ │ │ ├── password.mdx │ │ │ │ ├── pathname.mdx │ │ │ │ ├── port.mdx │ │ │ │ ├── protocol.mdx │ │ │ │ ├── search.mdx │ │ │ │ ├── searchParams.mdx │ │ │ │ ├── toJSON.mdx │ │ │ │ ├── toString.mdx │ │ │ │ └── username.mdx │ │ │ ├── URLSearchParams/ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── append.mdx │ │ │ │ ├── delete.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── set.mdx │ │ │ │ ├── sort.mdx │ │ │ │ ├── toString.mdx │ │ │ │ └── values.mdx │ │ │ ├── Uint16Array/ │ │ │ │ └── Uint16Array.mdx │ │ │ ├── Uint32Array/ │ │ │ │ └── Uint32Array.mdx │ │ │ ├── Uint8Array/ │ │ │ │ └── Uint8Array.mdx │ │ │ ├── Uint8ClampedArray/ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ ├── WeakMap/ │ │ │ │ ├── WeakMap.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── delete.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── has.mdx │ │ │ │ └── set.mdx │ │ │ ├── WeakRef/ │ │ │ │ ├── WeakRef.mdx │ │ │ │ └── prototype/ │ │ │ │ └── deref.mdx │ │ │ ├── WeakSet/ │ │ │ │ ├── WeakSet.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── add.mdx │ │ │ │ ├── delete.mdx │ │ │ │ └── has.mdx │ │ │ ├── WorkerLocation/ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ ├── hash.mdx │ │ │ │ ├── host.mdx │ │ │ │ ├── hostname.mdx │ │ │ │ ├── href.mdx │ │ │ │ ├── origin.mdx │ │ │ │ ├── pathname.mdx │ │ │ │ ├── port.mdx │ │ │ │ ├── protocol.mdx │ │ │ │ ├── search.mdx │ │ │ │ └── toString.mdx │ │ │ ├── WritableStream/ │ │ │ │ ├── WritableStream.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── abort.mdx │ │ │ │ ├── getWriter.mdx │ │ │ │ └── locked.mdx │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ └── error.mdx │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── abort.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── closed.mdx │ │ │ │ ├── desiredSize.mdx │ │ │ │ ├── ready.mdx │ │ │ │ ├── releaseLock.mdx │ │ │ │ └── write.mdx │ │ │ ├── atob.mdx │ │ │ ├── btoa.mdx │ │ │ ├── clearInterval.mdx │ │ │ ├── clearTimeout.mdx │ │ │ ├── console/ │ │ │ │ ├── assert.mdx │ │ │ │ ├── clear.mdx │ │ │ │ ├── count.mdx │ │ │ │ ├── countReset.mdx │ │ │ │ ├── debug.mdx │ │ │ │ ├── dir.mdx │ │ │ │ ├── dirxml.mdx │ │ │ │ ├── error.mdx │ │ │ │ ├── group.mdx │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ ├── groupEnd.mdx │ │ │ │ ├── info.mdx │ │ │ │ ├── log.mdx │ │ │ │ ├── time.mdx │ │ │ │ ├── timeEnd.mdx │ │ │ │ ├── timeLog.mdx │ │ │ │ ├── trace.mdx │ │ │ │ └── warn.mdx │ │ │ ├── crypto/ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ ├── randomUUID.mdx │ │ │ │ └── subtle.mdx │ │ │ ├── decodeURI.mdx │ │ │ ├── decodeURIComponent.mdx │ │ │ ├── encodeURI.mdx │ │ │ ├── encodeURIComponent.mdx │ │ │ ├── escape.mdx │ │ │ ├── eval.mdx │ │ │ ├── fetch.mdx │ │ │ ├── globalThis.mdx │ │ │ ├── isFinite.mdx │ │ │ ├── isNaN.mdx │ │ │ ├── location.mdx │ │ │ ├── parseFloat.mdx │ │ │ ├── parseInt.mdx │ │ │ ├── performance/ │ │ │ │ ├── now.mdx │ │ │ │ └── timeOrigin.mdx │ │ │ ├── setInterval.mdx │ │ │ ├── setTimeout.mdx │ │ │ ├── structuredClone.mdx │ │ │ ├── undefined.mdx │ │ │ └── unescape.mdx │ │ ├── html-rewriter/ │ │ │ ├── Element/ │ │ │ │ └── prototype/ │ │ │ │ ├── after.mdx │ │ │ │ ├── append.mdx │ │ │ │ ├── before.mdx │ │ │ │ ├── hasAttribute.mdx │ │ │ │ ├── prepend.mdx │ │ │ │ ├── removeAttribute.mdx │ │ │ │ ├── replaceChildren.mdx │ │ │ │ ├── replaceWith.mdx │ │ │ │ ├── selector.mdx │ │ │ │ ├── setAttribute.mdx │ │ │ │ └── tag.mdx │ │ │ └── HTMLRewritingStream/ │ │ │ ├── HTMLRewritingStream.mdx │ │ │ └── prototype/ │ │ │ └── onElement.mdx │ │ ├── image-optimizer/ │ │ │ ├── Auto.mdx │ │ │ ├── BWAlgorithm.mdx │ │ │ ├── CropMode.mdx │ │ │ ├── Disable.mdx │ │ │ ├── Enable.mdx │ │ │ ├── Fit.mdx │ │ │ ├── Format.mdx │ │ │ ├── Metadata.mdx │ │ │ ├── Optimize.mdx │ │ │ ├── Orient.mdx │ │ │ ├── Profile.mdx │ │ │ ├── Region.mdx │ │ │ ├── ResizeFilter.mdx │ │ │ └── imageOptimizerOptions.mdx │ │ ├── index.mdx │ │ ├── kv-store/ │ │ │ ├── KVStore/ │ │ │ │ ├── KVStore.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── delete.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── list.mdx │ │ │ │ └── put.mdx │ │ │ └── KVStoreEntry/ │ │ │ └── prototype/ │ │ │ ├── arrayBuffer.mdx │ │ │ ├── body.mdx │ │ │ ├── bodyUsed.mdx │ │ │ ├── json.mdx │ │ │ ├── metadata.mdx │ │ │ ├── metadataText.mdx │ │ │ └── text.mdx │ │ ├── logger/ │ │ │ ├── Logger/ │ │ │ │ ├── Logger.mdx │ │ │ │ └── prototype/ │ │ │ │ └── log.mdx │ │ │ └── configureConsole.mdx │ │ ├── migration-guide/ │ │ │ └── index.mdx │ │ ├── secret-store/ │ │ │ ├── SecretStore/ │ │ │ │ ├── SecretStore.mdx │ │ │ │ ├── fromBytes.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ └── SecretStoreEntry/ │ │ │ └── prototype/ │ │ │ ├── plaintext.mdx │ │ │ └── rawBytes.mdx │ │ ├── security/ │ │ │ └── inspect.mdx │ │ ├── shielding/ │ │ │ └── Shield/ │ │ │ ├── Shield.mdx │ │ │ └── prototype/ │ │ │ ├── encryptedBackend.mdx │ │ │ ├── runningOn.mdx │ │ │ └── unencryptedBackend.mdx │ │ └── websocket/ │ │ └── createWebsocketHandoff.mdx │ ├── docusaurus.config.js │ ├── generate-version-redirects.mjs │ ├── package.json │ ├── rename-docs.mjs │ ├── sidebars.js │ ├── src/ │ │ ├── components/ │ │ │ ├── HomepageFeatures/ │ │ │ │ ├── index.js │ │ │ │ └── styles.module.css │ │ │ └── fiddle/ │ │ │ └── index.js │ │ ├── css/ │ │ │ └── custom.css │ │ ├── pages/ │ │ │ ├── index.js │ │ │ └── index.module.css │ │ └── theme/ │ │ └── MDXComponents.js │ ├── static/ │ │ └── fiddle.js │ ├── versioned_docs/ │ │ ├── version-1.13.0/ │ │ │ ├── backend/ │ │ │ │ └── Backend/ │ │ │ │ ├── Backend.mdx │ │ │ │ └── prototype/ │ │ │ │ └── toString.mdx │ │ │ ├── cache-override/ │ │ │ │ └── CacheOverride/ │ │ │ │ └── CacheOverride.mdx │ │ │ ├── config-store/ │ │ │ │ └── ConfigStore/ │ │ │ │ ├── ConfigStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── dictionary/ │ │ │ │ └── Dictionary/ │ │ │ │ ├── Dictionary.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── env/ │ │ │ │ └── env.mdx │ │ │ ├── experimental/ │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ └── includeBytes.mdx │ │ │ ├── fanout/ │ │ │ │ └── createFanoutHandoff.mdx │ │ │ ├── geolocation/ │ │ │ │ └── getGeolocationForIpAddress.mdx │ │ │ ├── globals/ │ │ │ │ ├── AggregrateError/ │ │ │ │ │ └── AggregrateError.mdx │ │ │ │ ├── Array/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Array.mdx │ │ │ │ │ ├── from.mdx │ │ │ │ │ ├── isArray.mdx │ │ │ │ │ ├── of.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── @@unscopables.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── copyWithin.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── every.mdx │ │ │ │ │ ├── fill.mdx │ │ │ │ │ ├── filter.mdx │ │ │ │ │ ├── find.mdx │ │ │ │ │ ├── findIndex.mdx │ │ │ │ │ ├── flat.mdx │ │ │ │ │ ├── flatMap.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── join.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── map.mdx │ │ │ │ │ ├── pop.mdx │ │ │ │ │ ├── push.mdx │ │ │ │ │ ├── reduce.mdx │ │ │ │ │ ├── reduceRight.mdx │ │ │ │ │ ├── reverse.mdx │ │ │ │ │ ├── shift.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── some.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── splice.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── unshift.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── ArrayBuffer/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ │ ├── isView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ └── slice.mdx │ │ │ │ ├── BigInt/ │ │ │ │ │ ├── BigInt.mdx │ │ │ │ │ ├── asIntN.mdx │ │ │ │ │ ├── asUintN.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── BigInt64Array/ │ │ │ │ │ └── BigInt64Array.mdx │ │ │ │ ├── BigUint64Array/ │ │ │ │ │ └── BigUint64Array.mdx │ │ │ │ ├── Boolean/ │ │ │ │ │ ├── Boolean.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── size.mdx │ │ │ │ ├── CompressionStream/ │ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── CryptoKey/ │ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── algorithm.mdx │ │ │ │ │ ├── extractable.mdx │ │ │ │ │ ├── type.mdx │ │ │ │ │ └── usages.mdx │ │ │ │ ├── DataView/ │ │ │ │ │ ├── DataView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── buffer.mdx │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ ├── byteOffset.mdx │ │ │ │ │ ├── getBigInt64.mdx │ │ │ │ │ ├── getBigUint64.mdx │ │ │ │ │ ├── getFloat32.mdx │ │ │ │ │ ├── getFloat64.mdx │ │ │ │ │ ├── getInt16.mdx │ │ │ │ │ ├── getInt32.mdx │ │ │ │ │ ├── getInt8.mdx │ │ │ │ │ ├── getUint16.mdx │ │ │ │ │ ├── getUint32.mdx │ │ │ │ │ ├── getUint8.mdx │ │ │ │ │ ├── setBigInt64.mdx │ │ │ │ │ ├── setBigUint64.mdx │ │ │ │ │ ├── setFloat32.mdx │ │ │ │ │ ├── setFloat64.mdx │ │ │ │ │ ├── setInt16.mdx │ │ │ │ │ ├── setInt32.mdx │ │ │ │ │ ├── setInt8.mdx │ │ │ │ │ ├── setUint16.mdx │ │ │ │ │ ├── setUint32.mdx │ │ │ │ │ └── setUint8.mdx │ │ │ │ ├── Date/ │ │ │ │ │ ├── Date.mdx │ │ │ │ │ ├── UTC.mdx │ │ │ │ │ ├── now.mdx │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── getDate.mdx │ │ │ │ │ ├── getDay.mdx │ │ │ │ │ ├── getFullYear.mdx │ │ │ │ │ ├── getHours.mdx │ │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ │ ├── getMinutes.mdx │ │ │ │ │ ├── getMonth.mdx │ │ │ │ │ ├── getSeconds.mdx │ │ │ │ │ ├── getTime.mdx │ │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ │ ├── getUTCDate.mdx │ │ │ │ │ ├── getUTCDay.mdx │ │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ │ ├── getUTCHours.mdx │ │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ │ ├── getYear.mdx │ │ │ │ │ ├── setDate.mdx │ │ │ │ │ ├── setFullYear.mdx │ │ │ │ │ ├── setHours.mdx │ │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ │ ├── setMinutes.mdx │ │ │ │ │ ├── setMonth.mdx │ │ │ │ │ ├── setSeconds.mdx │ │ │ │ │ ├── setTime.mdx │ │ │ │ │ ├── setUTCDate.mdx │ │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ │ ├── setUTCHours.mdx │ │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ │ ├── setYear.mdx │ │ │ │ │ ├── toDateString.mdx │ │ │ │ │ ├── toISOString.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toTimeString.mdx │ │ │ │ │ ├── toUTCString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── DecompressionStream/ │ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── Error/ │ │ │ │ │ ├── Error.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cause.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── EvalError/ │ │ │ │ │ └── EvalError.mdx │ │ │ │ ├── FetchEvent/ │ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respondWith.mdx │ │ │ │ │ └── waitUntil.mdx │ │ │ │ ├── FinalizationRegistry/ │ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── register.mdx │ │ │ │ │ └── unregister.mdx │ │ │ │ ├── Float32Array/ │ │ │ │ │ └── Float32Array.mdx │ │ │ │ ├── Float64Array/ │ │ │ │ │ └── Float64Array.mdx │ │ │ │ ├── Function/ │ │ │ │ │ ├── Function.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── bind.mdx │ │ │ │ │ ├── call.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── Headers/ │ │ │ │ │ ├── Headers.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Infinity.mdx │ │ │ │ ├── Int16Array/ │ │ │ │ │ └── Int16Array.mdx │ │ │ │ ├── Int32Array/ │ │ │ │ │ └── Int32Array.mdx │ │ │ │ ├── Int8Array/ │ │ │ │ │ └── Int8Array.mdx │ │ │ │ ├── JSON/ │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── stringify.mdx │ │ │ │ ├── Map/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Map.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Math/ │ │ │ │ │ ├── E.mdx │ │ │ │ │ ├── LN10.mdx │ │ │ │ │ ├── LN2.mdx │ │ │ │ │ ├── LOG10e.mdx │ │ │ │ │ ├── LOG2e.mdx │ │ │ │ │ ├── PI.mdx │ │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ │ ├── SQRT2.mdx │ │ │ │ │ ├── abs.mdx │ │ │ │ │ ├── acos.mdx │ │ │ │ │ ├── acosh.mdx │ │ │ │ │ ├── asin.mdx │ │ │ │ │ ├── asinh.mdx │ │ │ │ │ ├── atan.mdx │ │ │ │ │ ├── atan2.mdx │ │ │ │ │ ├── atanh.mdx │ │ │ │ │ ├── cbrt.mdx │ │ │ │ │ ├── ceil.mdx │ │ │ │ │ ├── clz32.mdx │ │ │ │ │ ├── cos.mdx │ │ │ │ │ ├── cosh.mdx │ │ │ │ │ ├── exp.mdx │ │ │ │ │ ├── expm1.mdx │ │ │ │ │ ├── floor.mdx │ │ │ │ │ ├── fround.mdx │ │ │ │ │ ├── hypot.mdx │ │ │ │ │ ├── imul.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── log10.mdx │ │ │ │ │ ├── log1p.mdx │ │ │ │ │ ├── log2.mdx │ │ │ │ │ ├── max.mdx │ │ │ │ │ ├── min.mdx │ │ │ │ │ ├── pow.mdx │ │ │ │ │ ├── random.mdx │ │ │ │ │ ├── round.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ ├── sin.mdx │ │ │ │ │ ├── sinh.mdx │ │ │ │ │ ├── sqrt.mdx │ │ │ │ │ ├── tan.mdx │ │ │ │ │ ├── tanh.mdx │ │ │ │ │ └── trunc.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number/ │ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ │ ├── NaN.mdx │ │ │ │ │ ├── Number.mdx │ │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ │ ├── epsilon.mdx │ │ │ │ │ ├── isFinite.mdx │ │ │ │ │ ├── isInteger.mdx │ │ │ │ │ ├── isNaN.mdx │ │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ │ ├── parseFloat.mdx │ │ │ │ │ ├── parseInt.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toExponential.mdx │ │ │ │ │ ├── toFixed.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toPrecision.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── Object/ │ │ │ │ │ ├── Object.mdx │ │ │ │ │ ├── assign.mdx │ │ │ │ │ ├── create.mdx │ │ │ │ │ ├── defineProperties.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── freeze.mdx │ │ │ │ │ ├── fromEntries.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── hasOwn.mdx │ │ │ │ │ ├── is.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── isFrozen.mdx │ │ │ │ │ ├── isSealed.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── seal.mdx │ │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Promise/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Promise.mdx │ │ │ │ │ ├── all.mdx │ │ │ │ │ ├── allSettled.mdx │ │ │ │ │ ├── any.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ │ ├── finally.mdx │ │ │ │ │ │ └── then.mdx │ │ │ │ │ ├── race.mdx │ │ │ │ │ ├── reject.mdx │ │ │ │ │ └── resolve.mdx │ │ │ │ ├── Proxy/ │ │ │ │ │ ├── Proxy.mdx │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ │ ├── construct.mdx │ │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ │ ├── get.mdx │ │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ │ ├── has.mdx │ │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ │ ├── set.mdx │ │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ │ └── revocable.mdx │ │ │ │ ├── RangeError/ │ │ │ │ │ └── RangeError.mdx │ │ │ │ ├── ReadableByteStreamController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byobRequest.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStream/ │ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── getReader.mdx │ │ │ │ │ ├── locked.mdx │ │ │ │ │ ├── pipeThrough.mdx │ │ │ │ │ ├── pipeTo.mdx │ │ │ │ │ └── tee.mdx │ │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respond.mdx │ │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ │ └── view.mdx │ │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReferenceError/ │ │ │ │ │ └── ReferenceError.mdx │ │ │ │ ├── Reflect/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ ├── Request/ │ │ │ │ │ ├── Request.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── method.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ ├── Response/ │ │ │ │ │ ├── Response.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ │ ├── body.mdx │ │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ │ ├── headers.mdx │ │ │ │ │ │ ├── json.mdx │ │ │ │ │ │ ├── ok.mdx │ │ │ │ │ │ ├── status.mdx │ │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ │ ├── text.mdx │ │ │ │ │ │ └── url.mdx │ │ │ │ │ └── redirect.mdx │ │ │ │ ├── RsaHashedImportParams/ │ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ │ ├── Set/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Set.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── String/ │ │ │ │ │ ├── String.mdx │ │ │ │ │ ├── fromCharCode.mdx │ │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ │ ├── at.mdx │ │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ │ ├── concat.mdx │ │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ │ ├── includes.mdx │ │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ │ ├── length.mdx │ │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ │ ├── match.mdx │ │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ │ ├── replace.mdx │ │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ │ ├── search.mdx │ │ │ │ │ │ ├── slice.mdx │ │ │ │ │ │ ├── split.mdx │ │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ │ ├── substr.mdx │ │ │ │ │ │ ├── substring.mdx │ │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ │ ├── trim.mdx │ │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ └── raw.mdx │ │ │ │ ├── SubtleCrypto/ │ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── digest.mdx │ │ │ │ │ ├── importKey.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ └── verify.mdx │ │ │ │ ├── Symbol/ │ │ │ │ │ ├── Symbol.mdx │ │ │ │ │ ├── asyncIterator.mdx │ │ │ │ │ ├── for.mdx │ │ │ │ │ ├── hasInstance.mdx │ │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ │ ├── iterator.mdx │ │ │ │ │ ├── keyFor.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ │ ├── description.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── species.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── toPrimitive.mdx │ │ │ │ │ ├── toStringTag.mdx │ │ │ │ │ └── unscopables.mdx │ │ │ │ ├── SyntaxError/ │ │ │ │ │ └── SyntaxError.mdx │ │ │ │ ├── TextDecoder/ │ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── decode.mdx │ │ │ │ │ ├── encoding.mdx │ │ │ │ │ ├── fatal.mdx │ │ │ │ │ └── ignoreBOM.mdx │ │ │ │ ├── TextEncoder/ │ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── encode.mdx │ │ │ │ │ └── encoding.mdx │ │ │ │ ├── TransformStream/ │ │ │ │ │ ├── TransformStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ └── terminate.mdx │ │ │ │ ├── TypeError/ │ │ │ │ │ └── TypeError.mdx │ │ │ │ ├── URIError/ │ │ │ │ │ └── URIError.mdx │ │ │ │ ├── URL/ │ │ │ │ │ ├── URL.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── password.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── searchParams.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── username.mdx │ │ │ │ ├── URLSearchParams/ │ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Uint16Array/ │ │ │ │ │ └── Uint16Array.mdx │ │ │ │ ├── Uint32Array/ │ │ │ │ │ └── Uint32Array.mdx │ │ │ │ ├── Uint8Array/ │ │ │ │ │ └── Uint8Array.mdx │ │ │ │ ├── Uint8ClampedArray/ │ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ │ ├── WeakMap/ │ │ │ │ │ ├── WeakMap.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ └── set.mdx │ │ │ │ ├── WeakRef/ │ │ │ │ │ ├── WeakRef.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── deref.mdx │ │ │ │ ├── WeakSet/ │ │ │ │ │ ├── WeakSet.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ └── has.mdx │ │ │ │ ├── WorkerLocation/ │ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── WritableStream/ │ │ │ │ │ ├── WritableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── getWriter.mdx │ │ │ │ │ └── locked.mdx │ │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ │ └── error.mdx │ │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── ready.mdx │ │ │ │ │ ├── releaseLock.mdx │ │ │ │ │ └── write.mdx │ │ │ │ ├── atob.mdx │ │ │ │ ├── btoa.mdx │ │ │ │ ├── clearInterval.mdx │ │ │ │ ├── clearTimeout.mdx │ │ │ │ ├── console/ │ │ │ │ │ ├── assert.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── count.mdx │ │ │ │ │ ├── countReset.mdx │ │ │ │ │ ├── debug.mdx │ │ │ │ │ ├── dir.mdx │ │ │ │ │ ├── dirxml.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ ├── group.mdx │ │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ │ ├── groupEnd.mdx │ │ │ │ │ ├── info.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── time.mdx │ │ │ │ │ ├── timeEnd.mdx │ │ │ │ │ ├── timeLog.mdx │ │ │ │ │ ├── trace.mdx │ │ │ │ │ └── warn.mdx │ │ │ │ ├── crypto/ │ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ │ ├── randomUUID.mdx │ │ │ │ │ └── subtle.mdx │ │ │ │ ├── decodeURI.mdx │ │ │ │ ├── decodeURIComponent.mdx │ │ │ │ ├── encodeURI.mdx │ │ │ │ ├── encodeURIComponent.mdx │ │ │ │ ├── escape.mdx │ │ │ │ ├── eval.mdx │ │ │ │ ├── fetch.mdx │ │ │ │ ├── globalThis.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── location.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ ├── setInterval.mdx │ │ │ │ ├── setTimeout.mdx │ │ │ │ ├── structuredClone.mdx │ │ │ │ ├── undefined.mdx │ │ │ │ └── unescape.mdx │ │ │ ├── index.mdx │ │ │ ├── logger/ │ │ │ │ └── Logger/ │ │ │ │ ├── Logger.mdx │ │ │ │ └── prototype/ │ │ │ │ └── log.mdx │ │ │ ├── object-store/ │ │ │ │ └── ObjectStore/ │ │ │ │ ├── ObjectStore.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── get.mdx │ │ │ │ └── put.mdx │ │ │ └── secret-store/ │ │ │ ├── SecretStore/ │ │ │ │ ├── SecretStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ └── SecretStoreEntry/ │ │ │ └── prototype/ │ │ │ └── plaintext.mdx │ │ ├── version-2.5.0/ │ │ │ ├── backend/ │ │ │ │ └── Backend/ │ │ │ │ ├── Backend.mdx │ │ │ │ └── prototype/ │ │ │ │ └── toString.mdx │ │ │ ├── cache/ │ │ │ │ ├── SimpleCache/ │ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOrSet.mdx │ │ │ │ │ └── set.mdx │ │ │ │ └── SimpleCacheEntry/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ └── text.mdx │ │ │ ├── cache-override/ │ │ │ │ └── CacheOverride/ │ │ │ │ └── CacheOverride.mdx │ │ │ ├── config-store/ │ │ │ │ └── ConfigStore/ │ │ │ │ ├── ConfigStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── dictionary/ │ │ │ │ └── Dictionary/ │ │ │ │ ├── Dictionary.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── env/ │ │ │ │ └── env.mdx │ │ │ ├── experimental/ │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ └── includeBytes.mdx │ │ │ ├── fanout/ │ │ │ │ └── createFanoutHandoff.mdx │ │ │ ├── geolocation/ │ │ │ │ └── getGeolocationForIpAddress.mdx │ │ │ ├── globals/ │ │ │ │ ├── AggregrateError/ │ │ │ │ │ └── AggregrateError.mdx │ │ │ │ ├── Array/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Array.mdx │ │ │ │ │ ├── from.mdx │ │ │ │ │ ├── isArray.mdx │ │ │ │ │ ├── of.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── @@unscopables.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── copyWithin.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── every.mdx │ │ │ │ │ ├── fill.mdx │ │ │ │ │ ├── filter.mdx │ │ │ │ │ ├── find.mdx │ │ │ │ │ ├── findIndex.mdx │ │ │ │ │ ├── flat.mdx │ │ │ │ │ ├── flatMap.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── join.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── map.mdx │ │ │ │ │ ├── pop.mdx │ │ │ │ │ ├── push.mdx │ │ │ │ │ ├── reduce.mdx │ │ │ │ │ ├── reduceRight.mdx │ │ │ │ │ ├── reverse.mdx │ │ │ │ │ ├── shift.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── some.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── splice.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── unshift.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── ArrayBuffer/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ │ ├── isView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ └── slice.mdx │ │ │ │ ├── BigInt/ │ │ │ │ │ ├── BigInt.mdx │ │ │ │ │ ├── asIntN.mdx │ │ │ │ │ ├── asUintN.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── BigInt64Array/ │ │ │ │ │ └── BigInt64Array.mdx │ │ │ │ ├── BigUint64Array/ │ │ │ │ │ └── BigUint64Array.mdx │ │ │ │ ├── Boolean/ │ │ │ │ │ ├── Boolean.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── size.mdx │ │ │ │ ├── CompressionStream/ │ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── CryptoKey/ │ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── algorithm.mdx │ │ │ │ │ ├── extractable.mdx │ │ │ │ │ ├── type.mdx │ │ │ │ │ └── usages.mdx │ │ │ │ ├── DOMException/ │ │ │ │ │ ├── DOMException.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ └── name.mdx │ │ │ │ ├── DataView/ │ │ │ │ │ ├── DataView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── buffer.mdx │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ ├── byteOffset.mdx │ │ │ │ │ ├── getBigInt64.mdx │ │ │ │ │ ├── getBigUint64.mdx │ │ │ │ │ ├── getFloat32.mdx │ │ │ │ │ ├── getFloat64.mdx │ │ │ │ │ ├── getInt16.mdx │ │ │ │ │ ├── getInt32.mdx │ │ │ │ │ ├── getInt8.mdx │ │ │ │ │ ├── getUint16.mdx │ │ │ │ │ ├── getUint32.mdx │ │ │ │ │ ├── getUint8.mdx │ │ │ │ │ ├── setBigInt64.mdx │ │ │ │ │ ├── setBigUint64.mdx │ │ │ │ │ ├── setFloat32.mdx │ │ │ │ │ ├── setFloat64.mdx │ │ │ │ │ ├── setInt16.mdx │ │ │ │ │ ├── setInt32.mdx │ │ │ │ │ ├── setInt8.mdx │ │ │ │ │ ├── setUint16.mdx │ │ │ │ │ ├── setUint32.mdx │ │ │ │ │ └── setUint8.mdx │ │ │ │ ├── Date/ │ │ │ │ │ ├── Date.mdx │ │ │ │ │ ├── UTC.mdx │ │ │ │ │ ├── now.mdx │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── getDate.mdx │ │ │ │ │ ├── getDay.mdx │ │ │ │ │ ├── getFullYear.mdx │ │ │ │ │ ├── getHours.mdx │ │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ │ ├── getMinutes.mdx │ │ │ │ │ ├── getMonth.mdx │ │ │ │ │ ├── getSeconds.mdx │ │ │ │ │ ├── getTime.mdx │ │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ │ ├── getUTCDate.mdx │ │ │ │ │ ├── getUTCDay.mdx │ │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ │ ├── getUTCHours.mdx │ │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ │ ├── getYear.mdx │ │ │ │ │ ├── setDate.mdx │ │ │ │ │ ├── setFullYear.mdx │ │ │ │ │ ├── setHours.mdx │ │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ │ ├── setMinutes.mdx │ │ │ │ │ ├── setMonth.mdx │ │ │ │ │ ├── setSeconds.mdx │ │ │ │ │ ├── setTime.mdx │ │ │ │ │ ├── setUTCDate.mdx │ │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ │ ├── setUTCHours.mdx │ │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ │ ├── setYear.mdx │ │ │ │ │ ├── toDateString.mdx │ │ │ │ │ ├── toISOString.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toTimeString.mdx │ │ │ │ │ ├── toUTCString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── DecompressionStream/ │ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── Error/ │ │ │ │ │ ├── Error.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cause.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── EvalError/ │ │ │ │ │ └── EvalError.mdx │ │ │ │ ├── FetchEvent/ │ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respondWith.mdx │ │ │ │ │ └── waitUntil.mdx │ │ │ │ ├── FinalizationRegistry/ │ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── register.mdx │ │ │ │ │ └── unregister.mdx │ │ │ │ ├── Float32Array/ │ │ │ │ │ └── Float32Array.mdx │ │ │ │ ├── Float64Array/ │ │ │ │ │ └── Float64Array.mdx │ │ │ │ ├── Function/ │ │ │ │ │ ├── Function.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── bind.mdx │ │ │ │ │ ├── call.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── Headers/ │ │ │ │ │ ├── Headers.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── HmacImportParams/ │ │ │ │ │ └── HmacImportParams.mdx │ │ │ │ ├── Infinity.mdx │ │ │ │ ├── Int16Array/ │ │ │ │ │ └── Int16Array.mdx │ │ │ │ ├── Int32Array/ │ │ │ │ │ └── Int32Array.mdx │ │ │ │ ├── Int8Array/ │ │ │ │ │ └── Int8Array.mdx │ │ │ │ ├── JSON/ │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── stringify.mdx │ │ │ │ ├── Map/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Map.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Math/ │ │ │ │ │ ├── E.mdx │ │ │ │ │ ├── LN10.mdx │ │ │ │ │ ├── LN2.mdx │ │ │ │ │ ├── LOG10e.mdx │ │ │ │ │ ├── LOG2e.mdx │ │ │ │ │ ├── PI.mdx │ │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ │ ├── SQRT2.mdx │ │ │ │ │ ├── abs.mdx │ │ │ │ │ ├── acos.mdx │ │ │ │ │ ├── acosh.mdx │ │ │ │ │ ├── asin.mdx │ │ │ │ │ ├── asinh.mdx │ │ │ │ │ ├── atan.mdx │ │ │ │ │ ├── atan2.mdx │ │ │ │ │ ├── atanh.mdx │ │ │ │ │ ├── cbrt.mdx │ │ │ │ │ ├── ceil.mdx │ │ │ │ │ ├── clz32.mdx │ │ │ │ │ ├── cos.mdx │ │ │ │ │ ├── cosh.mdx │ │ │ │ │ ├── exp.mdx │ │ │ │ │ ├── expm1.mdx │ │ │ │ │ ├── floor.mdx │ │ │ │ │ ├── fround.mdx │ │ │ │ │ ├── hypot.mdx │ │ │ │ │ ├── imul.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── log10.mdx │ │ │ │ │ ├── log1p.mdx │ │ │ │ │ ├── log2.mdx │ │ │ │ │ ├── max.mdx │ │ │ │ │ ├── min.mdx │ │ │ │ │ ├── pow.mdx │ │ │ │ │ ├── random.mdx │ │ │ │ │ ├── round.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ ├── sin.mdx │ │ │ │ │ ├── sinh.mdx │ │ │ │ │ ├── sqrt.mdx │ │ │ │ │ ├── tan.mdx │ │ │ │ │ ├── tanh.mdx │ │ │ │ │ └── trunc.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number/ │ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ │ ├── NaN.mdx │ │ │ │ │ ├── Number.mdx │ │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ │ ├── epsilon.mdx │ │ │ │ │ ├── isFinite.mdx │ │ │ │ │ ├── isInteger.mdx │ │ │ │ │ ├── isNaN.mdx │ │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ │ ├── parseFloat.mdx │ │ │ │ │ ├── parseInt.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toExponential.mdx │ │ │ │ │ ├── toFixed.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toPrecision.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── Object/ │ │ │ │ │ ├── Object.mdx │ │ │ │ │ ├── assign.mdx │ │ │ │ │ ├── create.mdx │ │ │ │ │ ├── defineProperties.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── freeze.mdx │ │ │ │ │ ├── fromEntries.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── hasOwn.mdx │ │ │ │ │ ├── is.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── isFrozen.mdx │ │ │ │ │ ├── isSealed.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── seal.mdx │ │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Promise/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Promise.mdx │ │ │ │ │ ├── all.mdx │ │ │ │ │ ├── allSettled.mdx │ │ │ │ │ ├── any.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ │ ├── finally.mdx │ │ │ │ │ │ └── then.mdx │ │ │ │ │ ├── race.mdx │ │ │ │ │ ├── reject.mdx │ │ │ │ │ └── resolve.mdx │ │ │ │ ├── Proxy/ │ │ │ │ │ ├── Proxy.mdx │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ │ ├── construct.mdx │ │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ │ ├── get.mdx │ │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ │ ├── has.mdx │ │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ │ ├── set.mdx │ │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ │ └── revocable.mdx │ │ │ │ ├── RangeError/ │ │ │ │ │ └── RangeError.mdx │ │ │ │ ├── ReadableByteStreamController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byobRequest.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStream/ │ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── getReader.mdx │ │ │ │ │ ├── locked.mdx │ │ │ │ │ ├── pipeThrough.mdx │ │ │ │ │ ├── pipeTo.mdx │ │ │ │ │ └── tee.mdx │ │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respond.mdx │ │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ │ └── view.mdx │ │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReferenceError/ │ │ │ │ │ └── ReferenceError.mdx │ │ │ │ ├── Reflect/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ ├── Request/ │ │ │ │ │ ├── Request.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── method.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ ├── Response/ │ │ │ │ │ ├── Response.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ │ ├── body.mdx │ │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ │ ├── headers.mdx │ │ │ │ │ │ ├── json.mdx │ │ │ │ │ │ ├── ok.mdx │ │ │ │ │ │ ├── status.mdx │ │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ │ ├── text.mdx │ │ │ │ │ │ └── url.mdx │ │ │ │ │ └── redirect.mdx │ │ │ │ ├── RsaHashedImportParams/ │ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ │ ├── Set/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Set.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── String/ │ │ │ │ │ ├── String.mdx │ │ │ │ │ ├── fromCharCode.mdx │ │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ │ ├── at.mdx │ │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ │ ├── concat.mdx │ │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ │ ├── includes.mdx │ │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ │ ├── length.mdx │ │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ │ ├── match.mdx │ │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ │ ├── replace.mdx │ │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ │ ├── search.mdx │ │ │ │ │ │ ├── slice.mdx │ │ │ │ │ │ ├── split.mdx │ │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ │ ├── substr.mdx │ │ │ │ │ │ ├── substring.mdx │ │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ │ ├── trim.mdx │ │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ └── raw.mdx │ │ │ │ ├── SubtleCrypto/ │ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── digest.mdx │ │ │ │ │ ├── importKey.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ └── verify.mdx │ │ │ │ ├── Symbol/ │ │ │ │ │ ├── Symbol.mdx │ │ │ │ │ ├── asyncIterator.mdx │ │ │ │ │ ├── for.mdx │ │ │ │ │ ├── hasInstance.mdx │ │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ │ ├── iterator.mdx │ │ │ │ │ ├── keyFor.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ │ ├── description.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── species.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── toPrimitive.mdx │ │ │ │ │ ├── toStringTag.mdx │ │ │ │ │ └── unscopables.mdx │ │ │ │ ├── SyntaxError/ │ │ │ │ │ └── SyntaxError.mdx │ │ │ │ ├── TextDecoder/ │ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── decode.mdx │ │ │ │ │ ├── encoding.mdx │ │ │ │ │ ├── fatal.mdx │ │ │ │ │ └── ignoreBOM.mdx │ │ │ │ ├── TextEncoder/ │ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── encode.mdx │ │ │ │ │ └── encoding.mdx │ │ │ │ ├── TransformStream/ │ │ │ │ │ ├── TransformStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ └── terminate.mdx │ │ │ │ ├── TypeError/ │ │ │ │ │ └── TypeError.mdx │ │ │ │ ├── URIError/ │ │ │ │ │ └── URIError.mdx │ │ │ │ ├── URL/ │ │ │ │ │ ├── URL.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── password.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── searchParams.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── username.mdx │ │ │ │ ├── URLSearchParams/ │ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Uint16Array/ │ │ │ │ │ └── Uint16Array.mdx │ │ │ │ ├── Uint32Array/ │ │ │ │ │ └── Uint32Array.mdx │ │ │ │ ├── Uint8Array/ │ │ │ │ │ └── Uint8Array.mdx │ │ │ │ ├── Uint8ClampedArray/ │ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ │ ├── WeakMap/ │ │ │ │ │ ├── WeakMap.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ └── set.mdx │ │ │ │ ├── WeakRef/ │ │ │ │ │ ├── WeakRef.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── deref.mdx │ │ │ │ ├── WeakSet/ │ │ │ │ │ ├── WeakSet.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ └── has.mdx │ │ │ │ ├── WorkerLocation/ │ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── WritableStream/ │ │ │ │ │ ├── WritableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── getWriter.mdx │ │ │ │ │ └── locked.mdx │ │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ │ └── error.mdx │ │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── ready.mdx │ │ │ │ │ ├── releaseLock.mdx │ │ │ │ │ └── write.mdx │ │ │ │ ├── atob.mdx │ │ │ │ ├── btoa.mdx │ │ │ │ ├── clearInterval.mdx │ │ │ │ ├── clearTimeout.mdx │ │ │ │ ├── console/ │ │ │ │ │ ├── assert.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── count.mdx │ │ │ │ │ ├── countReset.mdx │ │ │ │ │ ├── debug.mdx │ │ │ │ │ ├── dir.mdx │ │ │ │ │ ├── dirxml.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ ├── group.mdx │ │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ │ ├── groupEnd.mdx │ │ │ │ │ ├── info.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── time.mdx │ │ │ │ │ ├── timeEnd.mdx │ │ │ │ │ ├── timeLog.mdx │ │ │ │ │ ├── trace.mdx │ │ │ │ │ └── warn.mdx │ │ │ │ ├── crypto/ │ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ │ ├── randomUUID.mdx │ │ │ │ │ └── subtle.mdx │ │ │ │ ├── decodeURI.mdx │ │ │ │ ├── decodeURIComponent.mdx │ │ │ │ ├── encodeURI.mdx │ │ │ │ ├── encodeURIComponent.mdx │ │ │ │ ├── escape.mdx │ │ │ │ ├── eval.mdx │ │ │ │ ├── fetch.mdx │ │ │ │ ├── globalThis.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── location.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ ├── performance/ │ │ │ │ │ ├── now.mdx │ │ │ │ │ └── timeOrigin.mdx │ │ │ │ ├── setInterval.mdx │ │ │ │ ├── setTimeout.mdx │ │ │ │ ├── structuredClone.mdx │ │ │ │ ├── undefined.mdx │ │ │ │ └── unescape.mdx │ │ │ ├── index.mdx │ │ │ ├── kv-store/ │ │ │ │ ├── KVStore/ │ │ │ │ │ ├── KVStore.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── get.mdx │ │ │ │ │ └── put.mdx │ │ │ │ └── KVStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ └── text.mdx │ │ │ ├── logger/ │ │ │ │ └── Logger/ │ │ │ │ ├── Logger.mdx │ │ │ │ └── prototype/ │ │ │ │ └── log.mdx │ │ │ ├── migration-guide/ │ │ │ │ └── index.mdx │ │ │ └── secret-store/ │ │ │ ├── SecretStore/ │ │ │ │ ├── SecretStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ └── SecretStoreEntry/ │ │ │ └── prototype/ │ │ │ └── plaintext.mdx │ │ ├── version-3.38.4/ │ │ │ ├── acl/ │ │ │ │ └── Acl/ │ │ │ │ ├── open.mdx │ │ │ │ └── prototype/ │ │ │ │ └── lookup.mdx │ │ │ ├── backend/ │ │ │ │ ├── Backend/ │ │ │ │ │ ├── Backend.mdx │ │ │ │ │ ├── exists.mdx │ │ │ │ │ ├── fromName.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── betweenBytesTimeout.mdx │ │ │ │ │ ├── connectTimeout.mdx │ │ │ │ │ ├── firstByteTimeout.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ ├── hostOverride.mdx │ │ │ │ │ ├── httpKeepaliveTime.mdx │ │ │ │ │ ├── isDynamic.mdx │ │ │ │ │ ├── isSSL.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── target.mdx │ │ │ │ │ ├── tcpKeepalive.mdx │ │ │ │ │ ├── tlsMaxVersion.mdx │ │ │ │ │ ├── tlsMinVersion.mdx │ │ │ │ │ ├── toName.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── enforceExplicitBackends.mdx │ │ │ │ └── setDefaultDynamicBackendConfig.mdx │ │ │ ├── cache/ │ │ │ │ ├── CacheEntry/ │ │ │ │ │ ├── age.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── hits.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── maxAge.mdx │ │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ │ ├── state.mdx │ │ │ │ │ └── userMetadata.mdx │ │ │ │ ├── CacheState/ │ │ │ │ │ ├── found.mdx │ │ │ │ │ ├── mustInsertOrUpdate.mdx │ │ │ │ │ ├── stale.mdx │ │ │ │ │ └── usable.mdx │ │ │ │ ├── CoreCache/ │ │ │ │ │ ├── insert.mdx │ │ │ │ │ ├── lookup.mdx │ │ │ │ │ └── transactionLookup.mdx │ │ │ │ ├── SimpleCache/ │ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOrSet.mdx │ │ │ │ │ └── purge.mdx │ │ │ │ ├── SimpleCacheEntry/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ └── text.mdx │ │ │ │ └── TransactionCacheEntry/ │ │ │ │ ├── age.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── cancel.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── hits.mdx │ │ │ │ ├── insert.mdx │ │ │ │ ├── insertAndStreamBack.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── maxAge.mdx │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ ├── state.mdx │ │ │ │ ├── update.mdx │ │ │ │ └── userMetadata.mdx │ │ │ ├── cache-override/ │ │ │ │ └── CacheOverride/ │ │ │ │ └── CacheOverride.mdx │ │ │ ├── compute/ │ │ │ │ ├── purgeSurrogateKey.mdx │ │ │ │ └── vCpuTime.mdx │ │ │ ├── config-store/ │ │ │ │ └── ConfigStore/ │ │ │ │ ├── ConfigStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── device/ │ │ │ │ └── Device/ │ │ │ │ ├── lookup.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── brand.mdx │ │ │ │ ├── hardwareType.mdx │ │ │ │ ├── isDesktop.mdx │ │ │ │ ├── isGameConsole.mdx │ │ │ │ ├── isMediaPlayer.mdx │ │ │ │ ├── isMobile.mdx │ │ │ │ ├── isSmartTV.mdx │ │ │ │ ├── isTablet.mdx │ │ │ │ ├── isTouchscreen.mdx │ │ │ │ ├── model.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toJSON.mdx │ │ │ ├── dictionary/ │ │ │ │ └── Dictionary/ │ │ │ │ ├── Dictionary.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── edge-rate-limiter/ │ │ │ │ ├── EdgeRateLimiter/ │ │ │ │ │ ├── EdgeRateLimiter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── checkRate.mdx │ │ │ │ ├── PenaltyBox/ │ │ │ │ │ ├── PenaltyBox.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ └── has.mdx │ │ │ │ └── RateCounter/ │ │ │ │ ├── RateCounter.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── increment.mdx │ │ │ │ ├── lookupCount.mdx │ │ │ │ └── lookupRate.mdx │ │ │ ├── env/ │ │ │ │ └── env.mdx │ │ │ ├── experimental/ │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── includeBytes.mdx │ │ │ │ ├── mapAndLogError.mdx │ │ │ │ ├── mapError.mdx │ │ │ │ └── sdkVersion.mdx │ │ │ ├── fanout/ │ │ │ │ └── createFanoutHandoff.mdx │ │ │ ├── geolocation/ │ │ │ │ └── getGeolocationForIpAddress.mdx │ │ │ ├── globals/ │ │ │ │ ├── AggregrateError/ │ │ │ │ │ └── AggregrateError.mdx │ │ │ │ ├── Array/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Array.mdx │ │ │ │ │ ├── from.mdx │ │ │ │ │ ├── isArray.mdx │ │ │ │ │ ├── of.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── @@unscopables.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── copyWithin.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── every.mdx │ │ │ │ │ ├── fill.mdx │ │ │ │ │ ├── filter.mdx │ │ │ │ │ ├── find.mdx │ │ │ │ │ ├── findIndex.mdx │ │ │ │ │ ├── flat.mdx │ │ │ │ │ ├── flatMap.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── join.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── map.mdx │ │ │ │ │ ├── pop.mdx │ │ │ │ │ ├── push.mdx │ │ │ │ │ ├── reduce.mdx │ │ │ │ │ ├── reduceRight.mdx │ │ │ │ │ ├── reverse.mdx │ │ │ │ │ ├── shift.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── some.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── splice.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── unshift.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── ArrayBuffer/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ │ ├── isView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ └── slice.mdx │ │ │ │ ├── BigInt/ │ │ │ │ │ ├── BigInt.mdx │ │ │ │ │ ├── asIntN.mdx │ │ │ │ │ ├── asUintN.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── BigInt64Array/ │ │ │ │ │ └── BigInt64Array.mdx │ │ │ │ ├── BigUint64Array/ │ │ │ │ │ └── BigUint64Array.mdx │ │ │ │ ├── Blob/ │ │ │ │ │ ├── Blob.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── stream.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── type.mdx │ │ │ │ ├── Boolean/ │ │ │ │ │ ├── Boolean.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── size.mdx │ │ │ │ ├── CompressionStream/ │ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── CryptoKey/ │ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── algorithm.mdx │ │ │ │ │ ├── extractable.mdx │ │ │ │ │ ├── type.mdx │ │ │ │ │ └── usages.mdx │ │ │ │ ├── DOMException/ │ │ │ │ │ ├── DOMException.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ └── name.mdx │ │ │ │ ├── DataView/ │ │ │ │ │ ├── DataView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── buffer.mdx │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ ├── byteOffset.mdx │ │ │ │ │ ├── getBigInt64.mdx │ │ │ │ │ ├── getBigUint64.mdx │ │ │ │ │ ├── getFloat32.mdx │ │ │ │ │ ├── getFloat64.mdx │ │ │ │ │ ├── getInt16.mdx │ │ │ │ │ ├── getInt32.mdx │ │ │ │ │ ├── getInt8.mdx │ │ │ │ │ ├── getUint16.mdx │ │ │ │ │ ├── getUint32.mdx │ │ │ │ │ ├── getUint8.mdx │ │ │ │ │ ├── setBigInt64.mdx │ │ │ │ │ ├── setBigUint64.mdx │ │ │ │ │ ├── setFloat32.mdx │ │ │ │ │ ├── setFloat64.mdx │ │ │ │ │ ├── setInt16.mdx │ │ │ │ │ ├── setInt32.mdx │ │ │ │ │ ├── setInt8.mdx │ │ │ │ │ ├── setUint16.mdx │ │ │ │ │ ├── setUint32.mdx │ │ │ │ │ └── setUint8.mdx │ │ │ │ ├── Date/ │ │ │ │ │ ├── Date.mdx │ │ │ │ │ ├── UTC.mdx │ │ │ │ │ ├── now.mdx │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── getDate.mdx │ │ │ │ │ ├── getDay.mdx │ │ │ │ │ ├── getFullYear.mdx │ │ │ │ │ ├── getHours.mdx │ │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ │ ├── getMinutes.mdx │ │ │ │ │ ├── getMonth.mdx │ │ │ │ │ ├── getSeconds.mdx │ │ │ │ │ ├── getTime.mdx │ │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ │ ├── getUTCDate.mdx │ │ │ │ │ ├── getUTCDay.mdx │ │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ │ ├── getUTCHours.mdx │ │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ │ ├── getYear.mdx │ │ │ │ │ ├── setDate.mdx │ │ │ │ │ ├── setFullYear.mdx │ │ │ │ │ ├── setHours.mdx │ │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ │ ├── setMinutes.mdx │ │ │ │ │ ├── setMonth.mdx │ │ │ │ │ ├── setSeconds.mdx │ │ │ │ │ ├── setTime.mdx │ │ │ │ │ ├── setUTCDate.mdx │ │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ │ ├── setUTCHours.mdx │ │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ │ ├── setYear.mdx │ │ │ │ │ ├── toDateString.mdx │ │ │ │ │ ├── toISOString.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toTimeString.mdx │ │ │ │ │ ├── toUTCString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── DecompressionStream/ │ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── EcKeyImportParams/ │ │ │ │ │ └── EcKeyImportParams.mdx │ │ │ │ ├── EcdsaParams/ │ │ │ │ │ └── EcdsaParams.mdx │ │ │ │ ├── Error/ │ │ │ │ │ ├── Error.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cause.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── EvalError/ │ │ │ │ │ └── EvalError.mdx │ │ │ │ ├── FetchEvent/ │ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respondWith.mdx │ │ │ │ │ ├── sendEarlyHints.mdx │ │ │ │ │ └── waitUntil.mdx │ │ │ │ ├── FinalizationRegistry/ │ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── register.mdx │ │ │ │ │ └── unregister.mdx │ │ │ │ ├── Float32Array/ │ │ │ │ │ └── Float32Array.mdx │ │ │ │ ├── Float64Array/ │ │ │ │ │ └── Float64Array.mdx │ │ │ │ ├── FormData/ │ │ │ │ │ ├── FormData.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getAll.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Function/ │ │ │ │ │ ├── Function.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── bind.mdx │ │ │ │ │ ├── call.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── Headers/ │ │ │ │ │ ├── Headers.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getSetCookie.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── HmacImportParams/ │ │ │ │ │ └── HmacImportParams.mdx │ │ │ │ ├── Infinity.mdx │ │ │ │ ├── Int16Array/ │ │ │ │ │ └── Int16Array.mdx │ │ │ │ ├── Int32Array/ │ │ │ │ │ └── Int32Array.mdx │ │ │ │ ├── Int8Array/ │ │ │ │ │ └── Int8Array.mdx │ │ │ │ ├── JSON/ │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── stringify.mdx │ │ │ │ ├── Map/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Map.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Math/ │ │ │ │ │ ├── E.mdx │ │ │ │ │ ├── LN10.mdx │ │ │ │ │ ├── LN2.mdx │ │ │ │ │ ├── LOG10e.mdx │ │ │ │ │ ├── LOG2e.mdx │ │ │ │ │ ├── PI.mdx │ │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ │ ├── SQRT2.mdx │ │ │ │ │ ├── abs.mdx │ │ │ │ │ ├── acos.mdx │ │ │ │ │ ├── acosh.mdx │ │ │ │ │ ├── asin.mdx │ │ │ │ │ ├── asinh.mdx │ │ │ │ │ ├── atan.mdx │ │ │ │ │ ├── atan2.mdx │ │ │ │ │ ├── atanh.mdx │ │ │ │ │ ├── cbrt.mdx │ │ │ │ │ ├── ceil.mdx │ │ │ │ │ ├── clz32.mdx │ │ │ │ │ ├── cos.mdx │ │ │ │ │ ├── cosh.mdx │ │ │ │ │ ├── exp.mdx │ │ │ │ │ ├── expm1.mdx │ │ │ │ │ ├── floor.mdx │ │ │ │ │ ├── fround.mdx │ │ │ │ │ ├── hypot.mdx │ │ │ │ │ ├── imul.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── log10.mdx │ │ │ │ │ ├── log1p.mdx │ │ │ │ │ ├── log2.mdx │ │ │ │ │ ├── max.mdx │ │ │ │ │ ├── min.mdx │ │ │ │ │ ├── pow.mdx │ │ │ │ │ ├── random.mdx │ │ │ │ │ ├── round.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ ├── sin.mdx │ │ │ │ │ ├── sinh.mdx │ │ │ │ │ ├── sqrt.mdx │ │ │ │ │ ├── tan.mdx │ │ │ │ │ ├── tanh.mdx │ │ │ │ │ └── trunc.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number/ │ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ │ ├── NaN.mdx │ │ │ │ │ ├── Number.mdx │ │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ │ ├── epsilon.mdx │ │ │ │ │ ├── isFinite.mdx │ │ │ │ │ ├── isInteger.mdx │ │ │ │ │ ├── isNaN.mdx │ │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ │ ├── parseFloat.mdx │ │ │ │ │ ├── parseInt.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toExponential.mdx │ │ │ │ │ ├── toFixed.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toPrecision.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── Object/ │ │ │ │ │ ├── Object.mdx │ │ │ │ │ ├── assign.mdx │ │ │ │ │ ├── create.mdx │ │ │ │ │ ├── defineProperties.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── freeze.mdx │ │ │ │ │ ├── fromEntries.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── hasOwn.mdx │ │ │ │ │ ├── is.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── isFrozen.mdx │ │ │ │ │ ├── isSealed.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── seal.mdx │ │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Promise/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Promise.mdx │ │ │ │ │ ├── all.mdx │ │ │ │ │ ├── allSettled.mdx │ │ │ │ │ ├── any.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ │ ├── finally.mdx │ │ │ │ │ │ └── then.mdx │ │ │ │ │ ├── race.mdx │ │ │ │ │ ├── reject.mdx │ │ │ │ │ └── resolve.mdx │ │ │ │ ├── Proxy/ │ │ │ │ │ ├── Proxy.mdx │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ │ ├── construct.mdx │ │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ │ ├── get.mdx │ │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ │ ├── has.mdx │ │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ │ ├── set.mdx │ │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ │ └── revocable.mdx │ │ │ │ ├── RangeError/ │ │ │ │ │ └── RangeError.mdx │ │ │ │ ├── ReadableByteStreamController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byobRequest.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStream/ │ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── getReader.mdx │ │ │ │ │ ├── locked.mdx │ │ │ │ │ ├── pipeThrough.mdx │ │ │ │ │ ├── pipeTo.mdx │ │ │ │ │ └── tee.mdx │ │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respond.mdx │ │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ │ └── view.mdx │ │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReferenceError/ │ │ │ │ │ └── ReferenceError.mdx │ │ │ │ ├── Reflect/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ ├── Request/ │ │ │ │ │ ├── Request.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── blob.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── clone.mdx │ │ │ │ │ ├── formData.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── method.mdx │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ ├── Response/ │ │ │ │ │ ├── Response.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ │ ├── blob.mdx │ │ │ │ │ │ ├── body.mdx │ │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ │ ├── formData.mdx │ │ │ │ │ │ ├── headers.mdx │ │ │ │ │ │ ├── ip.mdx │ │ │ │ │ │ ├── json.mdx │ │ │ │ │ │ ├── ok.mdx │ │ │ │ │ │ ├── port.mdx │ │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ │ ├── status.mdx │ │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ │ ├── text.mdx │ │ │ │ │ │ └── url.mdx │ │ │ │ │ └── redirect.mdx │ │ │ │ ├── RsaHashedImportParams/ │ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ │ ├── Set/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Set.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── String/ │ │ │ │ │ ├── String.mdx │ │ │ │ │ ├── fromCharCode.mdx │ │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ │ ├── at.mdx │ │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ │ ├── concat.mdx │ │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ │ ├── includes.mdx │ │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ │ ├── length.mdx │ │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ │ ├── match.mdx │ │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ │ ├── replace.mdx │ │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ │ ├── search.mdx │ │ │ │ │ │ ├── slice.mdx │ │ │ │ │ │ ├── split.mdx │ │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ │ ├── substr.mdx │ │ │ │ │ │ ├── substring.mdx │ │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ │ ├── trim.mdx │ │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ └── raw.mdx │ │ │ │ ├── SubtleCrypto/ │ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── digest.mdx │ │ │ │ │ ├── importKey.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ └── verify.mdx │ │ │ │ ├── Symbol/ │ │ │ │ │ ├── Symbol.mdx │ │ │ │ │ ├── asyncIterator.mdx │ │ │ │ │ ├── for.mdx │ │ │ │ │ ├── hasInstance.mdx │ │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ │ ├── iterator.mdx │ │ │ │ │ ├── keyFor.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ │ ├── description.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── species.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── toPrimitive.mdx │ │ │ │ │ ├── toStringTag.mdx │ │ │ │ │ └── unscopables.mdx │ │ │ │ ├── SyntaxError/ │ │ │ │ │ └── SyntaxError.mdx │ │ │ │ ├── TextDecoder/ │ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── decode.mdx │ │ │ │ │ ├── encoding.mdx │ │ │ │ │ ├── fatal.mdx │ │ │ │ │ └── ignoreBOM.mdx │ │ │ │ ├── TextEncoder/ │ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── encode.mdx │ │ │ │ │ └── encoding.mdx │ │ │ │ ├── TransformStream/ │ │ │ │ │ ├── TransformStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ └── terminate.mdx │ │ │ │ ├── TypeError/ │ │ │ │ │ └── TypeError.mdx │ │ │ │ ├── URIError/ │ │ │ │ │ └── URIError.mdx │ │ │ │ ├── URL/ │ │ │ │ │ ├── URL.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── password.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── searchParams.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── username.mdx │ │ │ │ ├── URLSearchParams/ │ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Uint16Array/ │ │ │ │ │ └── Uint16Array.mdx │ │ │ │ ├── Uint32Array/ │ │ │ │ │ └── Uint32Array.mdx │ │ │ │ ├── Uint8Array/ │ │ │ │ │ └── Uint8Array.mdx │ │ │ │ ├── Uint8ClampedArray/ │ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ │ ├── WeakMap/ │ │ │ │ │ ├── WeakMap.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ └── set.mdx │ │ │ │ ├── WeakRef/ │ │ │ │ │ ├── WeakRef.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── deref.mdx │ │ │ │ ├── WeakSet/ │ │ │ │ │ ├── WeakSet.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ └── has.mdx │ │ │ │ ├── WorkerLocation/ │ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── WritableStream/ │ │ │ │ │ ├── WritableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── getWriter.mdx │ │ │ │ │ └── locked.mdx │ │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ │ └── error.mdx │ │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── ready.mdx │ │ │ │ │ ├── releaseLock.mdx │ │ │ │ │ └── write.mdx │ │ │ │ ├── atob.mdx │ │ │ │ ├── btoa.mdx │ │ │ │ ├── clearInterval.mdx │ │ │ │ ├── clearTimeout.mdx │ │ │ │ ├── console/ │ │ │ │ │ ├── assert.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── count.mdx │ │ │ │ │ ├── countReset.mdx │ │ │ │ │ ├── debug.mdx │ │ │ │ │ ├── dir.mdx │ │ │ │ │ ├── dirxml.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ ├── group.mdx │ │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ │ ├── groupEnd.mdx │ │ │ │ │ ├── info.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── time.mdx │ │ │ │ │ ├── timeEnd.mdx │ │ │ │ │ ├── timeLog.mdx │ │ │ │ │ ├── trace.mdx │ │ │ │ │ └── warn.mdx │ │ │ │ ├── crypto/ │ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ │ ├── randomUUID.mdx │ │ │ │ │ └── subtle.mdx │ │ │ │ ├── decodeURI.mdx │ │ │ │ ├── decodeURIComponent.mdx │ │ │ │ ├── encodeURI.mdx │ │ │ │ ├── encodeURIComponent.mdx │ │ │ │ ├── escape.mdx │ │ │ │ ├── eval.mdx │ │ │ │ ├── fetch.mdx │ │ │ │ ├── globalThis.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── location.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ ├── performance/ │ │ │ │ │ ├── now.mdx │ │ │ │ │ └── timeOrigin.mdx │ │ │ │ ├── setInterval.mdx │ │ │ │ ├── setTimeout.mdx │ │ │ │ ├── structuredClone.mdx │ │ │ │ ├── undefined.mdx │ │ │ │ └── unescape.mdx │ │ │ ├── html-rewriter/ │ │ │ │ ├── Element/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── after.mdx │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── before.mdx │ │ │ │ │ ├── hasAttribute.mdx │ │ │ │ │ ├── prepend.mdx │ │ │ │ │ ├── removeAttribute.mdx │ │ │ │ │ ├── replaceChildren.mdx │ │ │ │ │ ├── replaceWith.mdx │ │ │ │ │ ├── selector.mdx │ │ │ │ │ ├── setAttribute.mdx │ │ │ │ │ └── tag.mdx │ │ │ │ └── HTMLRewritingStream/ │ │ │ │ ├── HTMLRewritingStream.mdx │ │ │ │ └── prototype/ │ │ │ │ └── onElement.mdx │ │ │ ├── image-optimizer/ │ │ │ │ ├── Auto.mdx │ │ │ │ ├── BWAlgorithm.mdx │ │ │ │ ├── CropMode.mdx │ │ │ │ ├── Disable.mdx │ │ │ │ ├── Enable.mdx │ │ │ │ ├── Fit.mdx │ │ │ │ ├── Format.mdx │ │ │ │ ├── Metadata.mdx │ │ │ │ ├── Optimize.mdx │ │ │ │ ├── Orient.mdx │ │ │ │ ├── Profile.mdx │ │ │ │ ├── Region.mdx │ │ │ │ ├── ResizeFilter.mdx │ │ │ │ └── imageOptimizerOptions.mdx │ │ │ ├── index.mdx │ │ │ ├── kv-store/ │ │ │ │ ├── KVStore/ │ │ │ │ │ ├── KVStore.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── list.mdx │ │ │ │ │ └── put.mdx │ │ │ │ └── KVStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ ├── metadata.mdx │ │ │ │ ├── metadataText.mdx │ │ │ │ └── text.mdx │ │ │ ├── logger/ │ │ │ │ ├── Logger/ │ │ │ │ │ ├── Logger.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── log.mdx │ │ │ │ └── configureConsole.mdx │ │ │ ├── migration-guide/ │ │ │ │ └── index.mdx │ │ │ ├── secret-store/ │ │ │ │ ├── SecretStore/ │ │ │ │ │ ├── SecretStore.mdx │ │ │ │ │ ├── fromBytes.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── get.mdx │ │ │ │ └── SecretStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── plaintext.mdx │ │ │ │ └── rawBytes.mdx │ │ │ ├── security/ │ │ │ │ └── inspect.mdx │ │ │ ├── shielding/ │ │ │ │ └── Shield/ │ │ │ │ ├── Shield.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── encryptedBackend.mdx │ │ │ │ ├── runningOn.mdx │ │ │ │ └── unencryptedBackend.mdx │ │ │ └── websocket/ │ │ │ └── createWebsocketHandoff.mdx │ │ ├── version-3.39.0/ │ │ │ ├── acl/ │ │ │ │ └── Acl/ │ │ │ │ ├── open.mdx │ │ │ │ └── prototype/ │ │ │ │ └── lookup.mdx │ │ │ ├── backend/ │ │ │ │ ├── Backend/ │ │ │ │ │ ├── Backend.mdx │ │ │ │ │ ├── exists.mdx │ │ │ │ │ ├── fromName.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── betweenBytesTimeout.mdx │ │ │ │ │ ├── connectTimeout.mdx │ │ │ │ │ ├── firstByteTimeout.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ ├── hostOverride.mdx │ │ │ │ │ ├── httpKeepaliveTime.mdx │ │ │ │ │ ├── isDynamic.mdx │ │ │ │ │ ├── isSSL.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── target.mdx │ │ │ │ │ ├── tcpKeepalive.mdx │ │ │ │ │ ├── tlsMaxVersion.mdx │ │ │ │ │ ├── tlsMinVersion.mdx │ │ │ │ │ ├── toName.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── enforceExplicitBackends.mdx │ │ │ │ └── setDefaultDynamicBackendConfig.mdx │ │ │ ├── cache/ │ │ │ │ ├── CacheEntry/ │ │ │ │ │ ├── age.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── hits.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── maxAge.mdx │ │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ │ ├── state.mdx │ │ │ │ │ └── userMetadata.mdx │ │ │ │ ├── CacheState/ │ │ │ │ │ ├── found.mdx │ │ │ │ │ ├── mustInsertOrUpdate.mdx │ │ │ │ │ ├── stale.mdx │ │ │ │ │ └── usable.mdx │ │ │ │ ├── CoreCache/ │ │ │ │ │ ├── insert.mdx │ │ │ │ │ ├── lookup.mdx │ │ │ │ │ └── transactionLookup.mdx │ │ │ │ ├── SimpleCache/ │ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOrSet.mdx │ │ │ │ │ └── purge.mdx │ │ │ │ ├── SimpleCacheEntry/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ └── text.mdx │ │ │ │ └── TransactionCacheEntry/ │ │ │ │ ├── age.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── cancel.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── hits.mdx │ │ │ │ ├── insert.mdx │ │ │ │ ├── insertAndStreamBack.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── maxAge.mdx │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ ├── state.mdx │ │ │ │ ├── update.mdx │ │ │ │ └── userMetadata.mdx │ │ │ ├── cache-override/ │ │ │ │ └── CacheOverride/ │ │ │ │ └── CacheOverride.mdx │ │ │ ├── compute/ │ │ │ │ ├── purgeSurrogateKey.mdx │ │ │ │ └── vCpuTime.mdx │ │ │ ├── config-store/ │ │ │ │ └── ConfigStore/ │ │ │ │ ├── ConfigStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── device/ │ │ │ │ └── Device/ │ │ │ │ ├── lookup.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── brand.mdx │ │ │ │ ├── hardwareType.mdx │ │ │ │ ├── isBot.mdx │ │ │ │ ├── isDesktop.mdx │ │ │ │ ├── isGameConsole.mdx │ │ │ │ ├── isMediaPlayer.mdx │ │ │ │ ├── isMobile.mdx │ │ │ │ ├── isSmartTV.mdx │ │ │ │ ├── isTablet.mdx │ │ │ │ ├── isTouchscreen.mdx │ │ │ │ ├── model.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toJSON.mdx │ │ │ ├── dictionary/ │ │ │ │ └── Dictionary/ │ │ │ │ ├── Dictionary.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── edge-rate-limiter/ │ │ │ │ ├── EdgeRateLimiter/ │ │ │ │ │ ├── EdgeRateLimiter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── checkRate.mdx │ │ │ │ ├── PenaltyBox/ │ │ │ │ │ ├── PenaltyBox.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ └── has.mdx │ │ │ │ └── RateCounter/ │ │ │ │ ├── RateCounter.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── increment.mdx │ │ │ │ ├── lookupCount.mdx │ │ │ │ └── lookupRate.mdx │ │ │ ├── env/ │ │ │ │ └── env.mdx │ │ │ ├── experimental/ │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── includeBytes.mdx │ │ │ │ ├── mapAndLogError.mdx │ │ │ │ ├── mapError.mdx │ │ │ │ └── sdkVersion.mdx │ │ │ ├── fanout/ │ │ │ │ └── createFanoutHandoff.mdx │ │ │ ├── geolocation/ │ │ │ │ └── getGeolocationForIpAddress.mdx │ │ │ ├── globals/ │ │ │ │ ├── AggregrateError/ │ │ │ │ │ └── AggregrateError.mdx │ │ │ │ ├── Array/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Array.mdx │ │ │ │ │ ├── from.mdx │ │ │ │ │ ├── isArray.mdx │ │ │ │ │ ├── of.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── @@unscopables.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── copyWithin.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── every.mdx │ │ │ │ │ ├── fill.mdx │ │ │ │ │ ├── filter.mdx │ │ │ │ │ ├── find.mdx │ │ │ │ │ ├── findIndex.mdx │ │ │ │ │ ├── flat.mdx │ │ │ │ │ ├── flatMap.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── join.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── map.mdx │ │ │ │ │ ├── pop.mdx │ │ │ │ │ ├── push.mdx │ │ │ │ │ ├── reduce.mdx │ │ │ │ │ ├── reduceRight.mdx │ │ │ │ │ ├── reverse.mdx │ │ │ │ │ ├── shift.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── some.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── splice.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── unshift.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── ArrayBuffer/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ │ ├── isView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ └── slice.mdx │ │ │ │ ├── BigInt/ │ │ │ │ │ ├── BigInt.mdx │ │ │ │ │ ├── asIntN.mdx │ │ │ │ │ ├── asUintN.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── BigInt64Array/ │ │ │ │ │ └── BigInt64Array.mdx │ │ │ │ ├── BigUint64Array/ │ │ │ │ │ └── BigUint64Array.mdx │ │ │ │ ├── Blob/ │ │ │ │ │ ├── Blob.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── stream.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── type.mdx │ │ │ │ ├── Boolean/ │ │ │ │ │ ├── Boolean.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── size.mdx │ │ │ │ ├── CompressionStream/ │ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── CryptoKey/ │ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── algorithm.mdx │ │ │ │ │ ├── extractable.mdx │ │ │ │ │ ├── type.mdx │ │ │ │ │ └── usages.mdx │ │ │ │ ├── DOMException/ │ │ │ │ │ ├── DOMException.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ └── name.mdx │ │ │ │ ├── DataView/ │ │ │ │ │ ├── DataView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── buffer.mdx │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ ├── byteOffset.mdx │ │ │ │ │ ├── getBigInt64.mdx │ │ │ │ │ ├── getBigUint64.mdx │ │ │ │ │ ├── getFloat32.mdx │ │ │ │ │ ├── getFloat64.mdx │ │ │ │ │ ├── getInt16.mdx │ │ │ │ │ ├── getInt32.mdx │ │ │ │ │ ├── getInt8.mdx │ │ │ │ │ ├── getUint16.mdx │ │ │ │ │ ├── getUint32.mdx │ │ │ │ │ ├── getUint8.mdx │ │ │ │ │ ├── setBigInt64.mdx │ │ │ │ │ ├── setBigUint64.mdx │ │ │ │ │ ├── setFloat32.mdx │ │ │ │ │ ├── setFloat64.mdx │ │ │ │ │ ├── setInt16.mdx │ │ │ │ │ ├── setInt32.mdx │ │ │ │ │ ├── setInt8.mdx │ │ │ │ │ ├── setUint16.mdx │ │ │ │ │ ├── setUint32.mdx │ │ │ │ │ └── setUint8.mdx │ │ │ │ ├── Date/ │ │ │ │ │ ├── Date.mdx │ │ │ │ │ ├── UTC.mdx │ │ │ │ │ ├── now.mdx │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── getDate.mdx │ │ │ │ │ ├── getDay.mdx │ │ │ │ │ ├── getFullYear.mdx │ │ │ │ │ ├── getHours.mdx │ │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ │ ├── getMinutes.mdx │ │ │ │ │ ├── getMonth.mdx │ │ │ │ │ ├── getSeconds.mdx │ │ │ │ │ ├── getTime.mdx │ │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ │ ├── getUTCDate.mdx │ │ │ │ │ ├── getUTCDay.mdx │ │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ │ ├── getUTCHours.mdx │ │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ │ ├── getYear.mdx │ │ │ │ │ ├── setDate.mdx │ │ │ │ │ ├── setFullYear.mdx │ │ │ │ │ ├── setHours.mdx │ │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ │ ├── setMinutes.mdx │ │ │ │ │ ├── setMonth.mdx │ │ │ │ │ ├── setSeconds.mdx │ │ │ │ │ ├── setTime.mdx │ │ │ │ │ ├── setUTCDate.mdx │ │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ │ ├── setUTCHours.mdx │ │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ │ ├── setYear.mdx │ │ │ │ │ ├── toDateString.mdx │ │ │ │ │ ├── toISOString.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toTimeString.mdx │ │ │ │ │ ├── toUTCString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── DecompressionStream/ │ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── EcKeyImportParams/ │ │ │ │ │ └── EcKeyImportParams.mdx │ │ │ │ ├── EcdsaParams/ │ │ │ │ │ └── EcdsaParams.mdx │ │ │ │ ├── Error/ │ │ │ │ │ ├── Error.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cause.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── EvalError/ │ │ │ │ │ └── EvalError.mdx │ │ │ │ ├── FetchEvent/ │ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respondWith.mdx │ │ │ │ │ ├── sendEarlyHints.mdx │ │ │ │ │ └── waitUntil.mdx │ │ │ │ ├── FinalizationRegistry/ │ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── register.mdx │ │ │ │ │ └── unregister.mdx │ │ │ │ ├── Float32Array/ │ │ │ │ │ └── Float32Array.mdx │ │ │ │ ├── Float64Array/ │ │ │ │ │ └── Float64Array.mdx │ │ │ │ ├── FormData/ │ │ │ │ │ ├── FormData.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getAll.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Function/ │ │ │ │ │ ├── Function.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── bind.mdx │ │ │ │ │ ├── call.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── Headers/ │ │ │ │ │ ├── Headers.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getSetCookie.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── HmacImportParams/ │ │ │ │ │ └── HmacImportParams.mdx │ │ │ │ ├── Infinity.mdx │ │ │ │ ├── Int16Array/ │ │ │ │ │ └── Int16Array.mdx │ │ │ │ ├── Int32Array/ │ │ │ │ │ └── Int32Array.mdx │ │ │ │ ├── Int8Array/ │ │ │ │ │ └── Int8Array.mdx │ │ │ │ ├── JSON/ │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── stringify.mdx │ │ │ │ ├── Map/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Map.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Math/ │ │ │ │ │ ├── E.mdx │ │ │ │ │ ├── LN10.mdx │ │ │ │ │ ├── LN2.mdx │ │ │ │ │ ├── LOG10e.mdx │ │ │ │ │ ├── LOG2e.mdx │ │ │ │ │ ├── PI.mdx │ │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ │ ├── SQRT2.mdx │ │ │ │ │ ├── abs.mdx │ │ │ │ │ ├── acos.mdx │ │ │ │ │ ├── acosh.mdx │ │ │ │ │ ├── asin.mdx │ │ │ │ │ ├── asinh.mdx │ │ │ │ │ ├── atan.mdx │ │ │ │ │ ├── atan2.mdx │ │ │ │ │ ├── atanh.mdx │ │ │ │ │ ├── cbrt.mdx │ │ │ │ │ ├── ceil.mdx │ │ │ │ │ ├── clz32.mdx │ │ │ │ │ ├── cos.mdx │ │ │ │ │ ├── cosh.mdx │ │ │ │ │ ├── exp.mdx │ │ │ │ │ ├── expm1.mdx │ │ │ │ │ ├── floor.mdx │ │ │ │ │ ├── fround.mdx │ │ │ │ │ ├── hypot.mdx │ │ │ │ │ ├── imul.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── log10.mdx │ │ │ │ │ ├── log1p.mdx │ │ │ │ │ ├── log2.mdx │ │ │ │ │ ├── max.mdx │ │ │ │ │ ├── min.mdx │ │ │ │ │ ├── pow.mdx │ │ │ │ │ ├── random.mdx │ │ │ │ │ ├── round.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ ├── sin.mdx │ │ │ │ │ ├── sinh.mdx │ │ │ │ │ ├── sqrt.mdx │ │ │ │ │ ├── tan.mdx │ │ │ │ │ ├── tanh.mdx │ │ │ │ │ └── trunc.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number/ │ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ │ ├── NaN.mdx │ │ │ │ │ ├── Number.mdx │ │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ │ ├── epsilon.mdx │ │ │ │ │ ├── isFinite.mdx │ │ │ │ │ ├── isInteger.mdx │ │ │ │ │ ├── isNaN.mdx │ │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ │ ├── parseFloat.mdx │ │ │ │ │ ├── parseInt.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toExponential.mdx │ │ │ │ │ ├── toFixed.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toPrecision.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── Object/ │ │ │ │ │ ├── Object.mdx │ │ │ │ │ ├── assign.mdx │ │ │ │ │ ├── create.mdx │ │ │ │ │ ├── defineProperties.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── freeze.mdx │ │ │ │ │ ├── fromEntries.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── hasOwn.mdx │ │ │ │ │ ├── is.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── isFrozen.mdx │ │ │ │ │ ├── isSealed.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── seal.mdx │ │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Promise/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Promise.mdx │ │ │ │ │ ├── all.mdx │ │ │ │ │ ├── allSettled.mdx │ │ │ │ │ ├── any.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ │ ├── finally.mdx │ │ │ │ │ │ └── then.mdx │ │ │ │ │ ├── race.mdx │ │ │ │ │ ├── reject.mdx │ │ │ │ │ └── resolve.mdx │ │ │ │ ├── Proxy/ │ │ │ │ │ ├── Proxy.mdx │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ │ ├── construct.mdx │ │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ │ ├── get.mdx │ │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ │ ├── has.mdx │ │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ │ ├── set.mdx │ │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ │ └── revocable.mdx │ │ │ │ ├── RangeError/ │ │ │ │ │ └── RangeError.mdx │ │ │ │ ├── ReadableByteStreamController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byobRequest.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStream/ │ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── getReader.mdx │ │ │ │ │ ├── locked.mdx │ │ │ │ │ ├── pipeThrough.mdx │ │ │ │ │ ├── pipeTo.mdx │ │ │ │ │ └── tee.mdx │ │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respond.mdx │ │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ │ └── view.mdx │ │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReferenceError/ │ │ │ │ │ └── ReferenceError.mdx │ │ │ │ ├── Reflect/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ ├── Request/ │ │ │ │ │ ├── Request.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── blob.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── clone.mdx │ │ │ │ │ ├── formData.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── method.mdx │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ ├── Response/ │ │ │ │ │ ├── Response.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ │ ├── blob.mdx │ │ │ │ │ │ ├── body.mdx │ │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ │ ├── formData.mdx │ │ │ │ │ │ ├── headers.mdx │ │ │ │ │ │ ├── ip.mdx │ │ │ │ │ │ ├── json.mdx │ │ │ │ │ │ ├── ok.mdx │ │ │ │ │ │ ├── port.mdx │ │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ │ ├── status.mdx │ │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ │ ├── text.mdx │ │ │ │ │ │ └── url.mdx │ │ │ │ │ └── redirect.mdx │ │ │ │ ├── RsaHashedImportParams/ │ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ │ ├── Set/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Set.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── String/ │ │ │ │ │ ├── String.mdx │ │ │ │ │ ├── fromCharCode.mdx │ │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ │ ├── at.mdx │ │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ │ ├── concat.mdx │ │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ │ ├── includes.mdx │ │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ │ ├── length.mdx │ │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ │ ├── match.mdx │ │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ │ ├── replace.mdx │ │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ │ ├── search.mdx │ │ │ │ │ │ ├── slice.mdx │ │ │ │ │ │ ├── split.mdx │ │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ │ ├── substr.mdx │ │ │ │ │ │ ├── substring.mdx │ │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ │ ├── trim.mdx │ │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ └── raw.mdx │ │ │ │ ├── SubtleCrypto/ │ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── digest.mdx │ │ │ │ │ ├── importKey.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ └── verify.mdx │ │ │ │ ├── Symbol/ │ │ │ │ │ ├── Symbol.mdx │ │ │ │ │ ├── asyncIterator.mdx │ │ │ │ │ ├── for.mdx │ │ │ │ │ ├── hasInstance.mdx │ │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ │ ├── iterator.mdx │ │ │ │ │ ├── keyFor.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ │ ├── description.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── species.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── toPrimitive.mdx │ │ │ │ │ ├── toStringTag.mdx │ │ │ │ │ └── unscopables.mdx │ │ │ │ ├── SyntaxError/ │ │ │ │ │ └── SyntaxError.mdx │ │ │ │ ├── TextDecoder/ │ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── decode.mdx │ │ │ │ │ ├── encoding.mdx │ │ │ │ │ ├── fatal.mdx │ │ │ │ │ └── ignoreBOM.mdx │ │ │ │ ├── TextEncoder/ │ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── encode.mdx │ │ │ │ │ └── encoding.mdx │ │ │ │ ├── TransformStream/ │ │ │ │ │ ├── TransformStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ └── terminate.mdx │ │ │ │ ├── TypeError/ │ │ │ │ │ └── TypeError.mdx │ │ │ │ ├── URIError/ │ │ │ │ │ └── URIError.mdx │ │ │ │ ├── URL/ │ │ │ │ │ ├── URL.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── password.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── searchParams.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── username.mdx │ │ │ │ ├── URLSearchParams/ │ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Uint16Array/ │ │ │ │ │ └── Uint16Array.mdx │ │ │ │ ├── Uint32Array/ │ │ │ │ │ └── Uint32Array.mdx │ │ │ │ ├── Uint8Array/ │ │ │ │ │ └── Uint8Array.mdx │ │ │ │ ├── Uint8ClampedArray/ │ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ │ ├── WeakMap/ │ │ │ │ │ ├── WeakMap.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ └── set.mdx │ │ │ │ ├── WeakRef/ │ │ │ │ │ ├── WeakRef.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── deref.mdx │ │ │ │ ├── WeakSet/ │ │ │ │ │ ├── WeakSet.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ └── has.mdx │ │ │ │ ├── WorkerLocation/ │ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── WritableStream/ │ │ │ │ │ ├── WritableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── getWriter.mdx │ │ │ │ │ └── locked.mdx │ │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ │ └── error.mdx │ │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── ready.mdx │ │ │ │ │ ├── releaseLock.mdx │ │ │ │ │ └── write.mdx │ │ │ │ ├── atob.mdx │ │ │ │ ├── btoa.mdx │ │ │ │ ├── clearInterval.mdx │ │ │ │ ├── clearTimeout.mdx │ │ │ │ ├── console/ │ │ │ │ │ ├── assert.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── count.mdx │ │ │ │ │ ├── countReset.mdx │ │ │ │ │ ├── debug.mdx │ │ │ │ │ ├── dir.mdx │ │ │ │ │ ├── dirxml.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ ├── group.mdx │ │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ │ ├── groupEnd.mdx │ │ │ │ │ ├── info.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── time.mdx │ │ │ │ │ ├── timeEnd.mdx │ │ │ │ │ ├── timeLog.mdx │ │ │ │ │ ├── trace.mdx │ │ │ │ │ └── warn.mdx │ │ │ │ ├── crypto/ │ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ │ ├── randomUUID.mdx │ │ │ │ │ └── subtle.mdx │ │ │ │ ├── decodeURI.mdx │ │ │ │ ├── decodeURIComponent.mdx │ │ │ │ ├── encodeURI.mdx │ │ │ │ ├── encodeURIComponent.mdx │ │ │ │ ├── escape.mdx │ │ │ │ ├── eval.mdx │ │ │ │ ├── fetch.mdx │ │ │ │ ├── globalThis.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── location.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ ├── performance/ │ │ │ │ │ ├── now.mdx │ │ │ │ │ └── timeOrigin.mdx │ │ │ │ ├── setInterval.mdx │ │ │ │ ├── setTimeout.mdx │ │ │ │ ├── structuredClone.mdx │ │ │ │ ├── undefined.mdx │ │ │ │ └── unescape.mdx │ │ │ ├── html-rewriter/ │ │ │ │ ├── Element/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── after.mdx │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── before.mdx │ │ │ │ │ ├── hasAttribute.mdx │ │ │ │ │ ├── prepend.mdx │ │ │ │ │ ├── removeAttribute.mdx │ │ │ │ │ ├── replaceChildren.mdx │ │ │ │ │ ├── replaceWith.mdx │ │ │ │ │ ├── selector.mdx │ │ │ │ │ ├── setAttribute.mdx │ │ │ │ │ └── tag.mdx │ │ │ │ └── HTMLRewritingStream/ │ │ │ │ ├── HTMLRewritingStream.mdx │ │ │ │ └── prototype/ │ │ │ │ └── onElement.mdx │ │ │ ├── image-optimizer/ │ │ │ │ ├── Auto.mdx │ │ │ │ ├── BWAlgorithm.mdx │ │ │ │ ├── CropMode.mdx │ │ │ │ ├── Disable.mdx │ │ │ │ ├── Enable.mdx │ │ │ │ ├── Fit.mdx │ │ │ │ ├── Format.mdx │ │ │ │ ├── Metadata.mdx │ │ │ │ ├── Optimize.mdx │ │ │ │ ├── Orient.mdx │ │ │ │ ├── Profile.mdx │ │ │ │ ├── Region.mdx │ │ │ │ ├── ResizeFilter.mdx │ │ │ │ └── imageOptimizerOptions.mdx │ │ │ ├── index.mdx │ │ │ ├── kv-store/ │ │ │ │ ├── KVStore/ │ │ │ │ │ ├── KVStore.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── list.mdx │ │ │ │ │ └── put.mdx │ │ │ │ └── KVStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ ├── metadata.mdx │ │ │ │ ├── metadataText.mdx │ │ │ │ └── text.mdx │ │ │ ├── logger/ │ │ │ │ ├── Logger/ │ │ │ │ │ ├── Logger.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── log.mdx │ │ │ │ └── configureConsole.mdx │ │ │ ├── migration-guide/ │ │ │ │ └── index.mdx │ │ │ ├── secret-store/ │ │ │ │ ├── SecretStore/ │ │ │ │ │ ├── SecretStore.mdx │ │ │ │ │ ├── fromBytes.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── get.mdx │ │ │ │ └── SecretStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── plaintext.mdx │ │ │ │ └── rawBytes.mdx │ │ │ ├── security/ │ │ │ │ └── inspect.mdx │ │ │ ├── shielding/ │ │ │ │ └── Shield/ │ │ │ │ ├── Shield.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── encryptedBackend.mdx │ │ │ │ ├── runningOn.mdx │ │ │ │ └── unencryptedBackend.mdx │ │ │ └── websocket/ │ │ │ └── createWebsocketHandoff.mdx │ │ ├── version-3.39.1/ │ │ │ ├── acl/ │ │ │ │ └── Acl/ │ │ │ │ ├── open.mdx │ │ │ │ └── prototype/ │ │ │ │ └── lookup.mdx │ │ │ ├── backend/ │ │ │ │ ├── Backend/ │ │ │ │ │ ├── Backend.mdx │ │ │ │ │ ├── exists.mdx │ │ │ │ │ ├── fromName.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── betweenBytesTimeout.mdx │ │ │ │ │ ├── connectTimeout.mdx │ │ │ │ │ ├── firstByteTimeout.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ ├── hostOverride.mdx │ │ │ │ │ ├── httpKeepaliveTime.mdx │ │ │ │ │ ├── isDynamic.mdx │ │ │ │ │ ├── isSSL.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── target.mdx │ │ │ │ │ ├── tcpKeepalive.mdx │ │ │ │ │ ├── tlsMaxVersion.mdx │ │ │ │ │ ├── tlsMinVersion.mdx │ │ │ │ │ ├── toName.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── enforceExplicitBackends.mdx │ │ │ │ └── setDefaultDynamicBackendConfig.mdx │ │ │ ├── cache/ │ │ │ │ ├── CacheEntry/ │ │ │ │ │ ├── age.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── hits.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── maxAge.mdx │ │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ │ ├── state.mdx │ │ │ │ │ └── userMetadata.mdx │ │ │ │ ├── CacheState/ │ │ │ │ │ ├── found.mdx │ │ │ │ │ ├── mustInsertOrUpdate.mdx │ │ │ │ │ ├── stale.mdx │ │ │ │ │ └── usable.mdx │ │ │ │ ├── CoreCache/ │ │ │ │ │ ├── insert.mdx │ │ │ │ │ ├── lookup.mdx │ │ │ │ │ └── transactionLookup.mdx │ │ │ │ ├── SimpleCache/ │ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOrSet.mdx │ │ │ │ │ └── purge.mdx │ │ │ │ ├── SimpleCacheEntry/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ └── text.mdx │ │ │ │ └── TransactionCacheEntry/ │ │ │ │ ├── age.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── cancel.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── hits.mdx │ │ │ │ ├── insert.mdx │ │ │ │ ├── insertAndStreamBack.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── maxAge.mdx │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ ├── state.mdx │ │ │ │ ├── update.mdx │ │ │ │ └── userMetadata.mdx │ │ │ ├── cache-override/ │ │ │ │ └── CacheOverride/ │ │ │ │ └── CacheOverride.mdx │ │ │ ├── compute/ │ │ │ │ ├── purgeSurrogateKey.mdx │ │ │ │ └── vCpuTime.mdx │ │ │ ├── config-store/ │ │ │ │ └── ConfigStore/ │ │ │ │ ├── ConfigStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── device/ │ │ │ │ └── Device/ │ │ │ │ ├── lookup.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── brand.mdx │ │ │ │ ├── hardwareType.mdx │ │ │ │ ├── isBot.mdx │ │ │ │ ├── isDesktop.mdx │ │ │ │ ├── isGameConsole.mdx │ │ │ │ ├── isMediaPlayer.mdx │ │ │ │ ├── isMobile.mdx │ │ │ │ ├── isSmartTV.mdx │ │ │ │ ├── isTablet.mdx │ │ │ │ ├── isTouchscreen.mdx │ │ │ │ ├── model.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toJSON.mdx │ │ │ ├── dictionary/ │ │ │ │ └── Dictionary/ │ │ │ │ ├── Dictionary.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── edge-rate-limiter/ │ │ │ │ ├── EdgeRateLimiter/ │ │ │ │ │ ├── EdgeRateLimiter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── checkRate.mdx │ │ │ │ ├── PenaltyBox/ │ │ │ │ │ ├── PenaltyBox.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ └── has.mdx │ │ │ │ └── RateCounter/ │ │ │ │ ├── RateCounter.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── increment.mdx │ │ │ │ ├── lookupCount.mdx │ │ │ │ └── lookupRate.mdx │ │ │ ├── env/ │ │ │ │ └── env.mdx │ │ │ ├── experimental/ │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── includeBytes.mdx │ │ │ │ ├── mapAndLogError.mdx │ │ │ │ ├── mapError.mdx │ │ │ │ └── sdkVersion.mdx │ │ │ ├── fanout/ │ │ │ │ └── createFanoutHandoff.mdx │ │ │ ├── geolocation/ │ │ │ │ └── getGeolocationForIpAddress.mdx │ │ │ ├── globals/ │ │ │ │ ├── AggregrateError/ │ │ │ │ │ └── AggregrateError.mdx │ │ │ │ ├── Array/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Array.mdx │ │ │ │ │ ├── from.mdx │ │ │ │ │ ├── isArray.mdx │ │ │ │ │ ├── of.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── @@unscopables.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── copyWithin.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── every.mdx │ │ │ │ │ ├── fill.mdx │ │ │ │ │ ├── filter.mdx │ │ │ │ │ ├── find.mdx │ │ │ │ │ ├── findIndex.mdx │ │ │ │ │ ├── flat.mdx │ │ │ │ │ ├── flatMap.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── join.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── map.mdx │ │ │ │ │ ├── pop.mdx │ │ │ │ │ ├── push.mdx │ │ │ │ │ ├── reduce.mdx │ │ │ │ │ ├── reduceRight.mdx │ │ │ │ │ ├── reverse.mdx │ │ │ │ │ ├── shift.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── some.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── splice.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── unshift.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── ArrayBuffer/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ │ ├── isView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ └── slice.mdx │ │ │ │ ├── BigInt/ │ │ │ │ │ ├── BigInt.mdx │ │ │ │ │ ├── asIntN.mdx │ │ │ │ │ ├── asUintN.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── BigInt64Array/ │ │ │ │ │ └── BigInt64Array.mdx │ │ │ │ ├── BigUint64Array/ │ │ │ │ │ └── BigUint64Array.mdx │ │ │ │ ├── Blob/ │ │ │ │ │ ├── Blob.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── stream.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── type.mdx │ │ │ │ ├── Boolean/ │ │ │ │ │ ├── Boolean.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── size.mdx │ │ │ │ ├── CompressionStream/ │ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── CryptoKey/ │ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── algorithm.mdx │ │ │ │ │ ├── extractable.mdx │ │ │ │ │ ├── type.mdx │ │ │ │ │ └── usages.mdx │ │ │ │ ├── DOMException/ │ │ │ │ │ ├── DOMException.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ └── name.mdx │ │ │ │ ├── DataView/ │ │ │ │ │ ├── DataView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── buffer.mdx │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ ├── byteOffset.mdx │ │ │ │ │ ├── getBigInt64.mdx │ │ │ │ │ ├── getBigUint64.mdx │ │ │ │ │ ├── getFloat32.mdx │ │ │ │ │ ├── getFloat64.mdx │ │ │ │ │ ├── getInt16.mdx │ │ │ │ │ ├── getInt32.mdx │ │ │ │ │ ├── getInt8.mdx │ │ │ │ │ ├── getUint16.mdx │ │ │ │ │ ├── getUint32.mdx │ │ │ │ │ ├── getUint8.mdx │ │ │ │ │ ├── setBigInt64.mdx │ │ │ │ │ ├── setBigUint64.mdx │ │ │ │ │ ├── setFloat32.mdx │ │ │ │ │ ├── setFloat64.mdx │ │ │ │ │ ├── setInt16.mdx │ │ │ │ │ ├── setInt32.mdx │ │ │ │ │ ├── setInt8.mdx │ │ │ │ │ ├── setUint16.mdx │ │ │ │ │ ├── setUint32.mdx │ │ │ │ │ └── setUint8.mdx │ │ │ │ ├── Date/ │ │ │ │ │ ├── Date.mdx │ │ │ │ │ ├── UTC.mdx │ │ │ │ │ ├── now.mdx │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── getDate.mdx │ │ │ │ │ ├── getDay.mdx │ │ │ │ │ ├── getFullYear.mdx │ │ │ │ │ ├── getHours.mdx │ │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ │ ├── getMinutes.mdx │ │ │ │ │ ├── getMonth.mdx │ │ │ │ │ ├── getSeconds.mdx │ │ │ │ │ ├── getTime.mdx │ │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ │ ├── getUTCDate.mdx │ │ │ │ │ ├── getUTCDay.mdx │ │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ │ ├── getUTCHours.mdx │ │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ │ ├── getYear.mdx │ │ │ │ │ ├── setDate.mdx │ │ │ │ │ ├── setFullYear.mdx │ │ │ │ │ ├── setHours.mdx │ │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ │ ├── setMinutes.mdx │ │ │ │ │ ├── setMonth.mdx │ │ │ │ │ ├── setSeconds.mdx │ │ │ │ │ ├── setTime.mdx │ │ │ │ │ ├── setUTCDate.mdx │ │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ │ ├── setUTCHours.mdx │ │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ │ ├── setYear.mdx │ │ │ │ │ ├── toDateString.mdx │ │ │ │ │ ├── toISOString.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toTimeString.mdx │ │ │ │ │ ├── toUTCString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── DecompressionStream/ │ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── EcKeyImportParams/ │ │ │ │ │ └── EcKeyImportParams.mdx │ │ │ │ ├── EcdsaParams/ │ │ │ │ │ └── EcdsaParams.mdx │ │ │ │ ├── Error/ │ │ │ │ │ ├── Error.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cause.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── EvalError/ │ │ │ │ │ └── EvalError.mdx │ │ │ │ ├── FetchEvent/ │ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respondWith.mdx │ │ │ │ │ ├── sendEarlyHints.mdx │ │ │ │ │ └── waitUntil.mdx │ │ │ │ ├── FinalizationRegistry/ │ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── register.mdx │ │ │ │ │ └── unregister.mdx │ │ │ │ ├── Float32Array/ │ │ │ │ │ └── Float32Array.mdx │ │ │ │ ├── Float64Array/ │ │ │ │ │ └── Float64Array.mdx │ │ │ │ ├── FormData/ │ │ │ │ │ ├── FormData.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getAll.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Function/ │ │ │ │ │ ├── Function.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── bind.mdx │ │ │ │ │ ├── call.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── Headers/ │ │ │ │ │ ├── Headers.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getSetCookie.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── HmacImportParams/ │ │ │ │ │ └── HmacImportParams.mdx │ │ │ │ ├── Infinity.mdx │ │ │ │ ├── Int16Array/ │ │ │ │ │ └── Int16Array.mdx │ │ │ │ ├── Int32Array/ │ │ │ │ │ └── Int32Array.mdx │ │ │ │ ├── Int8Array/ │ │ │ │ │ └── Int8Array.mdx │ │ │ │ ├── JSON/ │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── stringify.mdx │ │ │ │ ├── Map/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Map.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Math/ │ │ │ │ │ ├── E.mdx │ │ │ │ │ ├── LN10.mdx │ │ │ │ │ ├── LN2.mdx │ │ │ │ │ ├── LOG10e.mdx │ │ │ │ │ ├── LOG2e.mdx │ │ │ │ │ ├── PI.mdx │ │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ │ ├── SQRT2.mdx │ │ │ │ │ ├── abs.mdx │ │ │ │ │ ├── acos.mdx │ │ │ │ │ ├── acosh.mdx │ │ │ │ │ ├── asin.mdx │ │ │ │ │ ├── asinh.mdx │ │ │ │ │ ├── atan.mdx │ │ │ │ │ ├── atan2.mdx │ │ │ │ │ ├── atanh.mdx │ │ │ │ │ ├── cbrt.mdx │ │ │ │ │ ├── ceil.mdx │ │ │ │ │ ├── clz32.mdx │ │ │ │ │ ├── cos.mdx │ │ │ │ │ ├── cosh.mdx │ │ │ │ │ ├── exp.mdx │ │ │ │ │ ├── expm1.mdx │ │ │ │ │ ├── floor.mdx │ │ │ │ │ ├── fround.mdx │ │ │ │ │ ├── hypot.mdx │ │ │ │ │ ├── imul.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── log10.mdx │ │ │ │ │ ├── log1p.mdx │ │ │ │ │ ├── log2.mdx │ │ │ │ │ ├── max.mdx │ │ │ │ │ ├── min.mdx │ │ │ │ │ ├── pow.mdx │ │ │ │ │ ├── random.mdx │ │ │ │ │ ├── round.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ ├── sin.mdx │ │ │ │ │ ├── sinh.mdx │ │ │ │ │ ├── sqrt.mdx │ │ │ │ │ ├── tan.mdx │ │ │ │ │ ├── tanh.mdx │ │ │ │ │ └── trunc.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number/ │ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ │ ├── NaN.mdx │ │ │ │ │ ├── Number.mdx │ │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ │ ├── epsilon.mdx │ │ │ │ │ ├── isFinite.mdx │ │ │ │ │ ├── isInteger.mdx │ │ │ │ │ ├── isNaN.mdx │ │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ │ ├── parseFloat.mdx │ │ │ │ │ ├── parseInt.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toExponential.mdx │ │ │ │ │ ├── toFixed.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toPrecision.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── Object/ │ │ │ │ │ ├── Object.mdx │ │ │ │ │ ├── assign.mdx │ │ │ │ │ ├── create.mdx │ │ │ │ │ ├── defineProperties.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── freeze.mdx │ │ │ │ │ ├── fromEntries.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── hasOwn.mdx │ │ │ │ │ ├── is.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── isFrozen.mdx │ │ │ │ │ ├── isSealed.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── seal.mdx │ │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Promise/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Promise.mdx │ │ │ │ │ ├── all.mdx │ │ │ │ │ ├── allSettled.mdx │ │ │ │ │ ├── any.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ │ ├── finally.mdx │ │ │ │ │ │ └── then.mdx │ │ │ │ │ ├── race.mdx │ │ │ │ │ ├── reject.mdx │ │ │ │ │ └── resolve.mdx │ │ │ │ ├── Proxy/ │ │ │ │ │ ├── Proxy.mdx │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ │ ├── construct.mdx │ │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ │ ├── get.mdx │ │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ │ ├── has.mdx │ │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ │ ├── set.mdx │ │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ │ └── revocable.mdx │ │ │ │ ├── RangeError/ │ │ │ │ │ └── RangeError.mdx │ │ │ │ ├── ReadableByteStreamController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byobRequest.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStream/ │ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── getReader.mdx │ │ │ │ │ ├── locked.mdx │ │ │ │ │ ├── pipeThrough.mdx │ │ │ │ │ ├── pipeTo.mdx │ │ │ │ │ └── tee.mdx │ │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respond.mdx │ │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ │ └── view.mdx │ │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReferenceError/ │ │ │ │ │ └── ReferenceError.mdx │ │ │ │ ├── Reflect/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ ├── Request/ │ │ │ │ │ ├── Request.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── blob.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── clone.mdx │ │ │ │ │ ├── formData.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── method.mdx │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ ├── Response/ │ │ │ │ │ ├── Response.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ │ ├── blob.mdx │ │ │ │ │ │ ├── body.mdx │ │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ │ ├── formData.mdx │ │ │ │ │ │ ├── headers.mdx │ │ │ │ │ │ ├── ip.mdx │ │ │ │ │ │ ├── json.mdx │ │ │ │ │ │ ├── ok.mdx │ │ │ │ │ │ ├── port.mdx │ │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ │ ├── status.mdx │ │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ │ ├── text.mdx │ │ │ │ │ │ └── url.mdx │ │ │ │ │ └── redirect.mdx │ │ │ │ ├── RsaHashedImportParams/ │ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ │ ├── Set/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Set.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── String/ │ │ │ │ │ ├── String.mdx │ │ │ │ │ ├── fromCharCode.mdx │ │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ │ ├── at.mdx │ │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ │ ├── concat.mdx │ │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ │ ├── includes.mdx │ │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ │ ├── length.mdx │ │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ │ ├── match.mdx │ │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ │ ├── replace.mdx │ │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ │ ├── search.mdx │ │ │ │ │ │ ├── slice.mdx │ │ │ │ │ │ ├── split.mdx │ │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ │ ├── substr.mdx │ │ │ │ │ │ ├── substring.mdx │ │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ │ ├── trim.mdx │ │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ └── raw.mdx │ │ │ │ ├── SubtleCrypto/ │ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── digest.mdx │ │ │ │ │ ├── importKey.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ └── verify.mdx │ │ │ │ ├── Symbol/ │ │ │ │ │ ├── Symbol.mdx │ │ │ │ │ ├── asyncIterator.mdx │ │ │ │ │ ├── for.mdx │ │ │ │ │ ├── hasInstance.mdx │ │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ │ ├── iterator.mdx │ │ │ │ │ ├── keyFor.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ │ ├── description.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── species.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── toPrimitive.mdx │ │ │ │ │ ├── toStringTag.mdx │ │ │ │ │ └── unscopables.mdx │ │ │ │ ├── SyntaxError/ │ │ │ │ │ └── SyntaxError.mdx │ │ │ │ ├── TextDecoder/ │ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── decode.mdx │ │ │ │ │ ├── encoding.mdx │ │ │ │ │ ├── fatal.mdx │ │ │ │ │ └── ignoreBOM.mdx │ │ │ │ ├── TextEncoder/ │ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── encode.mdx │ │ │ │ │ └── encoding.mdx │ │ │ │ ├── TransformStream/ │ │ │ │ │ ├── TransformStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ └── terminate.mdx │ │ │ │ ├── TypeError/ │ │ │ │ │ └── TypeError.mdx │ │ │ │ ├── URIError/ │ │ │ │ │ └── URIError.mdx │ │ │ │ ├── URL/ │ │ │ │ │ ├── URL.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── password.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── searchParams.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── username.mdx │ │ │ │ ├── URLSearchParams/ │ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Uint16Array/ │ │ │ │ │ └── Uint16Array.mdx │ │ │ │ ├── Uint32Array/ │ │ │ │ │ └── Uint32Array.mdx │ │ │ │ ├── Uint8Array/ │ │ │ │ │ └── Uint8Array.mdx │ │ │ │ ├── Uint8ClampedArray/ │ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ │ ├── WeakMap/ │ │ │ │ │ ├── WeakMap.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ └── set.mdx │ │ │ │ ├── WeakRef/ │ │ │ │ │ ├── WeakRef.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── deref.mdx │ │ │ │ ├── WeakSet/ │ │ │ │ │ ├── WeakSet.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ └── has.mdx │ │ │ │ ├── WorkerLocation/ │ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── WritableStream/ │ │ │ │ │ ├── WritableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── getWriter.mdx │ │ │ │ │ └── locked.mdx │ │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ │ └── error.mdx │ │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── ready.mdx │ │ │ │ │ ├── releaseLock.mdx │ │ │ │ │ └── write.mdx │ │ │ │ ├── atob.mdx │ │ │ │ ├── btoa.mdx │ │ │ │ ├── clearInterval.mdx │ │ │ │ ├── clearTimeout.mdx │ │ │ │ ├── console/ │ │ │ │ │ ├── assert.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── count.mdx │ │ │ │ │ ├── countReset.mdx │ │ │ │ │ ├── debug.mdx │ │ │ │ │ ├── dir.mdx │ │ │ │ │ ├── dirxml.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ ├── group.mdx │ │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ │ ├── groupEnd.mdx │ │ │ │ │ ├── info.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── time.mdx │ │ │ │ │ ├── timeEnd.mdx │ │ │ │ │ ├── timeLog.mdx │ │ │ │ │ ├── trace.mdx │ │ │ │ │ └── warn.mdx │ │ │ │ ├── crypto/ │ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ │ ├── randomUUID.mdx │ │ │ │ │ └── subtle.mdx │ │ │ │ ├── decodeURI.mdx │ │ │ │ ├── decodeURIComponent.mdx │ │ │ │ ├── encodeURI.mdx │ │ │ │ ├── encodeURIComponent.mdx │ │ │ │ ├── escape.mdx │ │ │ │ ├── eval.mdx │ │ │ │ ├── fetch.mdx │ │ │ │ ├── globalThis.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── location.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ ├── performance/ │ │ │ │ │ ├── now.mdx │ │ │ │ │ └── timeOrigin.mdx │ │ │ │ ├── setInterval.mdx │ │ │ │ ├── setTimeout.mdx │ │ │ │ ├── structuredClone.mdx │ │ │ │ ├── undefined.mdx │ │ │ │ └── unescape.mdx │ │ │ ├── html-rewriter/ │ │ │ │ ├── Element/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── after.mdx │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── before.mdx │ │ │ │ │ ├── hasAttribute.mdx │ │ │ │ │ ├── prepend.mdx │ │ │ │ │ ├── removeAttribute.mdx │ │ │ │ │ ├── replaceChildren.mdx │ │ │ │ │ ├── replaceWith.mdx │ │ │ │ │ ├── selector.mdx │ │ │ │ │ ├── setAttribute.mdx │ │ │ │ │ └── tag.mdx │ │ │ │ └── HTMLRewritingStream/ │ │ │ │ ├── HTMLRewritingStream.mdx │ │ │ │ └── prototype/ │ │ │ │ └── onElement.mdx │ │ │ ├── image-optimizer/ │ │ │ │ ├── Auto.mdx │ │ │ │ ├── BWAlgorithm.mdx │ │ │ │ ├── CropMode.mdx │ │ │ │ ├── Disable.mdx │ │ │ │ ├── Enable.mdx │ │ │ │ ├── Fit.mdx │ │ │ │ ├── Format.mdx │ │ │ │ ├── Metadata.mdx │ │ │ │ ├── Optimize.mdx │ │ │ │ ├── Orient.mdx │ │ │ │ ├── Profile.mdx │ │ │ │ ├── Region.mdx │ │ │ │ ├── ResizeFilter.mdx │ │ │ │ └── imageOptimizerOptions.mdx │ │ │ ├── index.mdx │ │ │ ├── kv-store/ │ │ │ │ ├── KVStore/ │ │ │ │ │ ├── KVStore.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── list.mdx │ │ │ │ │ └── put.mdx │ │ │ │ └── KVStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ ├── metadata.mdx │ │ │ │ ├── metadataText.mdx │ │ │ │ └── text.mdx │ │ │ ├── logger/ │ │ │ │ ├── Logger/ │ │ │ │ │ ├── Logger.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── log.mdx │ │ │ │ └── configureConsole.mdx │ │ │ ├── migration-guide/ │ │ │ │ └── index.mdx │ │ │ ├── secret-store/ │ │ │ │ ├── SecretStore/ │ │ │ │ │ ├── SecretStore.mdx │ │ │ │ │ ├── fromBytes.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── get.mdx │ │ │ │ └── SecretStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── plaintext.mdx │ │ │ │ └── rawBytes.mdx │ │ │ ├── security/ │ │ │ │ └── inspect.mdx │ │ │ ├── shielding/ │ │ │ │ └── Shield/ │ │ │ │ ├── Shield.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── encryptedBackend.mdx │ │ │ │ ├── runningOn.mdx │ │ │ │ └── unencryptedBackend.mdx │ │ │ └── websocket/ │ │ │ └── createWebsocketHandoff.mdx │ │ ├── version-3.39.2/ │ │ │ ├── acl/ │ │ │ │ └── Acl/ │ │ │ │ ├── open.mdx │ │ │ │ └── prototype/ │ │ │ │ └── lookup.mdx │ │ │ ├── backend/ │ │ │ │ ├── Backend/ │ │ │ │ │ ├── Backend.mdx │ │ │ │ │ ├── exists.mdx │ │ │ │ │ ├── fromName.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── betweenBytesTimeout.mdx │ │ │ │ │ ├── connectTimeout.mdx │ │ │ │ │ ├── firstByteTimeout.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ ├── hostOverride.mdx │ │ │ │ │ ├── httpKeepaliveTime.mdx │ │ │ │ │ ├── isDynamic.mdx │ │ │ │ │ ├── isSSL.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── target.mdx │ │ │ │ │ ├── tcpKeepalive.mdx │ │ │ │ │ ├── tlsMaxVersion.mdx │ │ │ │ │ ├── tlsMinVersion.mdx │ │ │ │ │ ├── toName.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── enforceExplicitBackends.mdx │ │ │ │ └── setDefaultDynamicBackendConfig.mdx │ │ │ ├── cache/ │ │ │ │ ├── CacheEntry/ │ │ │ │ │ ├── age.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── hits.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── maxAge.mdx │ │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ │ ├── state.mdx │ │ │ │ │ └── userMetadata.mdx │ │ │ │ ├── CacheState/ │ │ │ │ │ ├── found.mdx │ │ │ │ │ ├── mustInsertOrUpdate.mdx │ │ │ │ │ ├── stale.mdx │ │ │ │ │ └── usable.mdx │ │ │ │ ├── CoreCache/ │ │ │ │ │ ├── insert.mdx │ │ │ │ │ ├── lookup.mdx │ │ │ │ │ └── transactionLookup.mdx │ │ │ │ ├── SimpleCache/ │ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOrSet.mdx │ │ │ │ │ └── purge.mdx │ │ │ │ ├── SimpleCacheEntry/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ └── text.mdx │ │ │ │ └── TransactionCacheEntry/ │ │ │ │ ├── age.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── cancel.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── hits.mdx │ │ │ │ ├── insert.mdx │ │ │ │ ├── insertAndStreamBack.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── maxAge.mdx │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ ├── state.mdx │ │ │ │ ├── update.mdx │ │ │ │ └── userMetadata.mdx │ │ │ ├── cache-override/ │ │ │ │ └── CacheOverride/ │ │ │ │ └── CacheOverride.mdx │ │ │ ├── compute/ │ │ │ │ ├── purgeSurrogateKey.mdx │ │ │ │ └── vCpuTime.mdx │ │ │ ├── config-store/ │ │ │ │ └── ConfigStore/ │ │ │ │ ├── ConfigStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── device/ │ │ │ │ └── Device/ │ │ │ │ ├── lookup.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── brand.mdx │ │ │ │ ├── hardwareType.mdx │ │ │ │ ├── isBot.mdx │ │ │ │ ├── isDesktop.mdx │ │ │ │ ├── isGameConsole.mdx │ │ │ │ ├── isMediaPlayer.mdx │ │ │ │ ├── isMobile.mdx │ │ │ │ ├── isSmartTV.mdx │ │ │ │ ├── isTablet.mdx │ │ │ │ ├── isTouchscreen.mdx │ │ │ │ ├── model.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toJSON.mdx │ │ │ ├── dictionary/ │ │ │ │ └── Dictionary/ │ │ │ │ ├── Dictionary.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── edge-rate-limiter/ │ │ │ │ ├── EdgeRateLimiter/ │ │ │ │ │ ├── EdgeRateLimiter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── checkRate.mdx │ │ │ │ ├── PenaltyBox/ │ │ │ │ │ ├── PenaltyBox.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ └── has.mdx │ │ │ │ └── RateCounter/ │ │ │ │ ├── RateCounter.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── increment.mdx │ │ │ │ ├── lookupCount.mdx │ │ │ │ └── lookupRate.mdx │ │ │ ├── env/ │ │ │ │ └── env.mdx │ │ │ ├── experimental/ │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── includeBytes.mdx │ │ │ │ ├── mapAndLogError.mdx │ │ │ │ ├── mapError.mdx │ │ │ │ └── sdkVersion.mdx │ │ │ ├── fanout/ │ │ │ │ └── createFanoutHandoff.mdx │ │ │ ├── geolocation/ │ │ │ │ └── getGeolocationForIpAddress.mdx │ │ │ ├── globals/ │ │ │ │ ├── AggregrateError/ │ │ │ │ │ └── AggregrateError.mdx │ │ │ │ ├── Array/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Array.mdx │ │ │ │ │ ├── from.mdx │ │ │ │ │ ├── isArray.mdx │ │ │ │ │ ├── of.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── @@unscopables.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── copyWithin.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── every.mdx │ │ │ │ │ ├── fill.mdx │ │ │ │ │ ├── filter.mdx │ │ │ │ │ ├── find.mdx │ │ │ │ │ ├── findIndex.mdx │ │ │ │ │ ├── flat.mdx │ │ │ │ │ ├── flatMap.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── join.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── map.mdx │ │ │ │ │ ├── pop.mdx │ │ │ │ │ ├── push.mdx │ │ │ │ │ ├── reduce.mdx │ │ │ │ │ ├── reduceRight.mdx │ │ │ │ │ ├── reverse.mdx │ │ │ │ │ ├── shift.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── some.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── splice.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── unshift.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── ArrayBuffer/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ │ ├── isView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ └── slice.mdx │ │ │ │ ├── BigInt/ │ │ │ │ │ ├── BigInt.mdx │ │ │ │ │ ├── asIntN.mdx │ │ │ │ │ ├── asUintN.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── BigInt64Array/ │ │ │ │ │ └── BigInt64Array.mdx │ │ │ │ ├── BigUint64Array/ │ │ │ │ │ └── BigUint64Array.mdx │ │ │ │ ├── Blob/ │ │ │ │ │ ├── Blob.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── stream.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── type.mdx │ │ │ │ ├── Boolean/ │ │ │ │ │ ├── Boolean.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── size.mdx │ │ │ │ ├── CompressionStream/ │ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── CryptoKey/ │ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── algorithm.mdx │ │ │ │ │ ├── extractable.mdx │ │ │ │ │ ├── type.mdx │ │ │ │ │ └── usages.mdx │ │ │ │ ├── DOMException/ │ │ │ │ │ ├── DOMException.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ └── name.mdx │ │ │ │ ├── DataView/ │ │ │ │ │ ├── DataView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── buffer.mdx │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ ├── byteOffset.mdx │ │ │ │ │ ├── getBigInt64.mdx │ │ │ │ │ ├── getBigUint64.mdx │ │ │ │ │ ├── getFloat32.mdx │ │ │ │ │ ├── getFloat64.mdx │ │ │ │ │ ├── getInt16.mdx │ │ │ │ │ ├── getInt32.mdx │ │ │ │ │ ├── getInt8.mdx │ │ │ │ │ ├── getUint16.mdx │ │ │ │ │ ├── getUint32.mdx │ │ │ │ │ ├── getUint8.mdx │ │ │ │ │ ├── setBigInt64.mdx │ │ │ │ │ ├── setBigUint64.mdx │ │ │ │ │ ├── setFloat32.mdx │ │ │ │ │ ├── setFloat64.mdx │ │ │ │ │ ├── setInt16.mdx │ │ │ │ │ ├── setInt32.mdx │ │ │ │ │ ├── setInt8.mdx │ │ │ │ │ ├── setUint16.mdx │ │ │ │ │ ├── setUint32.mdx │ │ │ │ │ └── setUint8.mdx │ │ │ │ ├── Date/ │ │ │ │ │ ├── Date.mdx │ │ │ │ │ ├── UTC.mdx │ │ │ │ │ ├── now.mdx │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── getDate.mdx │ │ │ │ │ ├── getDay.mdx │ │ │ │ │ ├── getFullYear.mdx │ │ │ │ │ ├── getHours.mdx │ │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ │ ├── getMinutes.mdx │ │ │ │ │ ├── getMonth.mdx │ │ │ │ │ ├── getSeconds.mdx │ │ │ │ │ ├── getTime.mdx │ │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ │ ├── getUTCDate.mdx │ │ │ │ │ ├── getUTCDay.mdx │ │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ │ ├── getUTCHours.mdx │ │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ │ ├── getYear.mdx │ │ │ │ │ ├── setDate.mdx │ │ │ │ │ ├── setFullYear.mdx │ │ │ │ │ ├── setHours.mdx │ │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ │ ├── setMinutes.mdx │ │ │ │ │ ├── setMonth.mdx │ │ │ │ │ ├── setSeconds.mdx │ │ │ │ │ ├── setTime.mdx │ │ │ │ │ ├── setUTCDate.mdx │ │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ │ ├── setUTCHours.mdx │ │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ │ ├── setYear.mdx │ │ │ │ │ ├── toDateString.mdx │ │ │ │ │ ├── toISOString.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toTimeString.mdx │ │ │ │ │ ├── toUTCString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── DecompressionStream/ │ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── EcKeyImportParams/ │ │ │ │ │ └── EcKeyImportParams.mdx │ │ │ │ ├── EcdsaParams/ │ │ │ │ │ └── EcdsaParams.mdx │ │ │ │ ├── Error/ │ │ │ │ │ ├── Error.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cause.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── EvalError/ │ │ │ │ │ └── EvalError.mdx │ │ │ │ ├── FetchEvent/ │ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respondWith.mdx │ │ │ │ │ ├── sendEarlyHints.mdx │ │ │ │ │ └── waitUntil.mdx │ │ │ │ ├── FinalizationRegistry/ │ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── register.mdx │ │ │ │ │ └── unregister.mdx │ │ │ │ ├── Float32Array/ │ │ │ │ │ └── Float32Array.mdx │ │ │ │ ├── Float64Array/ │ │ │ │ │ └── Float64Array.mdx │ │ │ │ ├── FormData/ │ │ │ │ │ ├── FormData.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getAll.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Function/ │ │ │ │ │ ├── Function.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── bind.mdx │ │ │ │ │ ├── call.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── Headers/ │ │ │ │ │ ├── Headers.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getSetCookie.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── HmacImportParams/ │ │ │ │ │ └── HmacImportParams.mdx │ │ │ │ ├── Infinity.mdx │ │ │ │ ├── Int16Array/ │ │ │ │ │ └── Int16Array.mdx │ │ │ │ ├── Int32Array/ │ │ │ │ │ └── Int32Array.mdx │ │ │ │ ├── Int8Array/ │ │ │ │ │ └── Int8Array.mdx │ │ │ │ ├── JSON/ │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── stringify.mdx │ │ │ │ ├── Map/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Map.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Math/ │ │ │ │ │ ├── E.mdx │ │ │ │ │ ├── LN10.mdx │ │ │ │ │ ├── LN2.mdx │ │ │ │ │ ├── LOG10e.mdx │ │ │ │ │ ├── LOG2e.mdx │ │ │ │ │ ├── PI.mdx │ │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ │ ├── SQRT2.mdx │ │ │ │ │ ├── abs.mdx │ │ │ │ │ ├── acos.mdx │ │ │ │ │ ├── acosh.mdx │ │ │ │ │ ├── asin.mdx │ │ │ │ │ ├── asinh.mdx │ │ │ │ │ ├── atan.mdx │ │ │ │ │ ├── atan2.mdx │ │ │ │ │ ├── atanh.mdx │ │ │ │ │ ├── cbrt.mdx │ │ │ │ │ ├── ceil.mdx │ │ │ │ │ ├── clz32.mdx │ │ │ │ │ ├── cos.mdx │ │ │ │ │ ├── cosh.mdx │ │ │ │ │ ├── exp.mdx │ │ │ │ │ ├── expm1.mdx │ │ │ │ │ ├── floor.mdx │ │ │ │ │ ├── fround.mdx │ │ │ │ │ ├── hypot.mdx │ │ │ │ │ ├── imul.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── log10.mdx │ │ │ │ │ ├── log1p.mdx │ │ │ │ │ ├── log2.mdx │ │ │ │ │ ├── max.mdx │ │ │ │ │ ├── min.mdx │ │ │ │ │ ├── pow.mdx │ │ │ │ │ ├── random.mdx │ │ │ │ │ ├── round.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ ├── sin.mdx │ │ │ │ │ ├── sinh.mdx │ │ │ │ │ ├── sqrt.mdx │ │ │ │ │ ├── tan.mdx │ │ │ │ │ ├── tanh.mdx │ │ │ │ │ └── trunc.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number/ │ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ │ ├── NaN.mdx │ │ │ │ │ ├── Number.mdx │ │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ │ ├── epsilon.mdx │ │ │ │ │ ├── isFinite.mdx │ │ │ │ │ ├── isInteger.mdx │ │ │ │ │ ├── isNaN.mdx │ │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ │ ├── parseFloat.mdx │ │ │ │ │ ├── parseInt.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toExponential.mdx │ │ │ │ │ ├── toFixed.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toPrecision.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── Object/ │ │ │ │ │ ├── Object.mdx │ │ │ │ │ ├── assign.mdx │ │ │ │ │ ├── create.mdx │ │ │ │ │ ├── defineProperties.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── freeze.mdx │ │ │ │ │ ├── fromEntries.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── hasOwn.mdx │ │ │ │ │ ├── is.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── isFrozen.mdx │ │ │ │ │ ├── isSealed.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── seal.mdx │ │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Promise/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Promise.mdx │ │ │ │ │ ├── all.mdx │ │ │ │ │ ├── allSettled.mdx │ │ │ │ │ ├── any.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ │ ├── finally.mdx │ │ │ │ │ │ └── then.mdx │ │ │ │ │ ├── race.mdx │ │ │ │ │ ├── reject.mdx │ │ │ │ │ └── resolve.mdx │ │ │ │ ├── Proxy/ │ │ │ │ │ ├── Proxy.mdx │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ │ ├── construct.mdx │ │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ │ ├── get.mdx │ │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ │ ├── has.mdx │ │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ │ ├── set.mdx │ │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ │ └── revocable.mdx │ │ │ │ ├── RangeError/ │ │ │ │ │ └── RangeError.mdx │ │ │ │ ├── ReadableByteStreamController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byobRequest.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStream/ │ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── getReader.mdx │ │ │ │ │ ├── locked.mdx │ │ │ │ │ ├── pipeThrough.mdx │ │ │ │ │ ├── pipeTo.mdx │ │ │ │ │ └── tee.mdx │ │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respond.mdx │ │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ │ └── view.mdx │ │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReferenceError/ │ │ │ │ │ └── ReferenceError.mdx │ │ │ │ ├── Reflect/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ ├── Request/ │ │ │ │ │ ├── Request.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── blob.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── clone.mdx │ │ │ │ │ ├── formData.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── method.mdx │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ ├── Response/ │ │ │ │ │ ├── Response.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ │ ├── blob.mdx │ │ │ │ │ │ ├── body.mdx │ │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ │ ├── formData.mdx │ │ │ │ │ │ ├── headers.mdx │ │ │ │ │ │ ├── ip.mdx │ │ │ │ │ │ ├── json.mdx │ │ │ │ │ │ ├── ok.mdx │ │ │ │ │ │ ├── port.mdx │ │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ │ ├── status.mdx │ │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ │ ├── text.mdx │ │ │ │ │ │ └── url.mdx │ │ │ │ │ └── redirect.mdx │ │ │ │ ├── RsaHashedImportParams/ │ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ │ ├── Set/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Set.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── String/ │ │ │ │ │ ├── String.mdx │ │ │ │ │ ├── fromCharCode.mdx │ │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ │ ├── at.mdx │ │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ │ ├── concat.mdx │ │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ │ ├── includes.mdx │ │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ │ ├── length.mdx │ │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ │ ├── match.mdx │ │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ │ ├── replace.mdx │ │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ │ ├── search.mdx │ │ │ │ │ │ ├── slice.mdx │ │ │ │ │ │ ├── split.mdx │ │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ │ ├── substr.mdx │ │ │ │ │ │ ├── substring.mdx │ │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ │ ├── trim.mdx │ │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ └── raw.mdx │ │ │ │ ├── SubtleCrypto/ │ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── digest.mdx │ │ │ │ │ ├── importKey.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ └── verify.mdx │ │ │ │ ├── Symbol/ │ │ │ │ │ ├── Symbol.mdx │ │ │ │ │ ├── asyncIterator.mdx │ │ │ │ │ ├── for.mdx │ │ │ │ │ ├── hasInstance.mdx │ │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ │ ├── iterator.mdx │ │ │ │ │ ├── keyFor.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ │ ├── description.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── species.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── toPrimitive.mdx │ │ │ │ │ ├── toStringTag.mdx │ │ │ │ │ └── unscopables.mdx │ │ │ │ ├── SyntaxError/ │ │ │ │ │ └── SyntaxError.mdx │ │ │ │ ├── TextDecoder/ │ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── decode.mdx │ │ │ │ │ ├── encoding.mdx │ │ │ │ │ ├── fatal.mdx │ │ │ │ │ └── ignoreBOM.mdx │ │ │ │ ├── TextEncoder/ │ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── encode.mdx │ │ │ │ │ └── encoding.mdx │ │ │ │ ├── TransformStream/ │ │ │ │ │ ├── TransformStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ └── terminate.mdx │ │ │ │ ├── TypeError/ │ │ │ │ │ └── TypeError.mdx │ │ │ │ ├── URIError/ │ │ │ │ │ └── URIError.mdx │ │ │ │ ├── URL/ │ │ │ │ │ ├── URL.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── password.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── searchParams.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── username.mdx │ │ │ │ ├── URLSearchParams/ │ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Uint16Array/ │ │ │ │ │ └── Uint16Array.mdx │ │ │ │ ├── Uint32Array/ │ │ │ │ │ └── Uint32Array.mdx │ │ │ │ ├── Uint8Array/ │ │ │ │ │ └── Uint8Array.mdx │ │ │ │ ├── Uint8ClampedArray/ │ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ │ ├── WeakMap/ │ │ │ │ │ ├── WeakMap.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ └── set.mdx │ │ │ │ ├── WeakRef/ │ │ │ │ │ ├── WeakRef.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── deref.mdx │ │ │ │ ├── WeakSet/ │ │ │ │ │ ├── WeakSet.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ └── has.mdx │ │ │ │ ├── WorkerLocation/ │ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── WritableStream/ │ │ │ │ │ ├── WritableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── getWriter.mdx │ │ │ │ │ └── locked.mdx │ │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ │ └── error.mdx │ │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── ready.mdx │ │ │ │ │ ├── releaseLock.mdx │ │ │ │ │ └── write.mdx │ │ │ │ ├── atob.mdx │ │ │ │ ├── btoa.mdx │ │ │ │ ├── clearInterval.mdx │ │ │ │ ├── clearTimeout.mdx │ │ │ │ ├── console/ │ │ │ │ │ ├── assert.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── count.mdx │ │ │ │ │ ├── countReset.mdx │ │ │ │ │ ├── debug.mdx │ │ │ │ │ ├── dir.mdx │ │ │ │ │ ├── dirxml.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ ├── group.mdx │ │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ │ ├── groupEnd.mdx │ │ │ │ │ ├── info.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── time.mdx │ │ │ │ │ ├── timeEnd.mdx │ │ │ │ │ ├── timeLog.mdx │ │ │ │ │ ├── trace.mdx │ │ │ │ │ └── warn.mdx │ │ │ │ ├── crypto/ │ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ │ ├── randomUUID.mdx │ │ │ │ │ └── subtle.mdx │ │ │ │ ├── decodeURI.mdx │ │ │ │ ├── decodeURIComponent.mdx │ │ │ │ ├── encodeURI.mdx │ │ │ │ ├── encodeURIComponent.mdx │ │ │ │ ├── escape.mdx │ │ │ │ ├── eval.mdx │ │ │ │ ├── fetch.mdx │ │ │ │ ├── globalThis.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── location.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ ├── performance/ │ │ │ │ │ ├── now.mdx │ │ │ │ │ └── timeOrigin.mdx │ │ │ │ ├── setInterval.mdx │ │ │ │ ├── setTimeout.mdx │ │ │ │ ├── structuredClone.mdx │ │ │ │ ├── undefined.mdx │ │ │ │ └── unescape.mdx │ │ │ ├── html-rewriter/ │ │ │ │ ├── Element/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── after.mdx │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── before.mdx │ │ │ │ │ ├── hasAttribute.mdx │ │ │ │ │ ├── prepend.mdx │ │ │ │ │ ├── removeAttribute.mdx │ │ │ │ │ ├── replaceChildren.mdx │ │ │ │ │ ├── replaceWith.mdx │ │ │ │ │ ├── selector.mdx │ │ │ │ │ ├── setAttribute.mdx │ │ │ │ │ └── tag.mdx │ │ │ │ └── HTMLRewritingStream/ │ │ │ │ ├── HTMLRewritingStream.mdx │ │ │ │ └── prototype/ │ │ │ │ └── onElement.mdx │ │ │ ├── image-optimizer/ │ │ │ │ ├── Auto.mdx │ │ │ │ ├── BWAlgorithm.mdx │ │ │ │ ├── CropMode.mdx │ │ │ │ ├── Disable.mdx │ │ │ │ ├── Enable.mdx │ │ │ │ ├── Fit.mdx │ │ │ │ ├── Format.mdx │ │ │ │ ├── Metadata.mdx │ │ │ │ ├── Optimize.mdx │ │ │ │ ├── Orient.mdx │ │ │ │ ├── Profile.mdx │ │ │ │ ├── Region.mdx │ │ │ │ ├── ResizeFilter.mdx │ │ │ │ └── imageOptimizerOptions.mdx │ │ │ ├── index.mdx │ │ │ ├── kv-store/ │ │ │ │ ├── KVStore/ │ │ │ │ │ ├── KVStore.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── list.mdx │ │ │ │ │ └── put.mdx │ │ │ │ └── KVStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ ├── metadata.mdx │ │ │ │ ├── metadataText.mdx │ │ │ │ └── text.mdx │ │ │ ├── logger/ │ │ │ │ ├── Logger/ │ │ │ │ │ ├── Logger.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── log.mdx │ │ │ │ └── configureConsole.mdx │ │ │ ├── migration-guide/ │ │ │ │ └── index.mdx │ │ │ ├── secret-store/ │ │ │ │ ├── SecretStore/ │ │ │ │ │ ├── SecretStore.mdx │ │ │ │ │ ├── fromBytes.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── get.mdx │ │ │ │ └── SecretStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── plaintext.mdx │ │ │ │ └── rawBytes.mdx │ │ │ ├── security/ │ │ │ │ └── inspect.mdx │ │ │ ├── shielding/ │ │ │ │ └── Shield/ │ │ │ │ ├── Shield.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── encryptedBackend.mdx │ │ │ │ ├── runningOn.mdx │ │ │ │ └── unencryptedBackend.mdx │ │ │ └── websocket/ │ │ │ └── createWebsocketHandoff.mdx │ │ ├── version-3.39.3/ │ │ │ ├── acl/ │ │ │ │ └── Acl/ │ │ │ │ ├── open.mdx │ │ │ │ └── prototype/ │ │ │ │ └── lookup.mdx │ │ │ ├── backend/ │ │ │ │ ├── Backend/ │ │ │ │ │ ├── Backend.mdx │ │ │ │ │ ├── exists.mdx │ │ │ │ │ ├── fromName.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── betweenBytesTimeout.mdx │ │ │ │ │ ├── connectTimeout.mdx │ │ │ │ │ ├── firstByteTimeout.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ ├── hostOverride.mdx │ │ │ │ │ ├── httpKeepaliveTime.mdx │ │ │ │ │ ├── isDynamic.mdx │ │ │ │ │ ├── isSSL.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── target.mdx │ │ │ │ │ ├── tcpKeepalive.mdx │ │ │ │ │ ├── tlsMaxVersion.mdx │ │ │ │ │ ├── tlsMinVersion.mdx │ │ │ │ │ ├── toName.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── enforceExplicitBackends.mdx │ │ │ │ └── setDefaultDynamicBackendConfig.mdx │ │ │ ├── cache/ │ │ │ │ ├── CacheEntry/ │ │ │ │ │ ├── age.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── hits.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── maxAge.mdx │ │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ │ ├── state.mdx │ │ │ │ │ └── userMetadata.mdx │ │ │ │ ├── CacheState/ │ │ │ │ │ ├── found.mdx │ │ │ │ │ ├── mustInsertOrUpdate.mdx │ │ │ │ │ ├── stale.mdx │ │ │ │ │ └── usable.mdx │ │ │ │ ├── CoreCache/ │ │ │ │ │ ├── insert.mdx │ │ │ │ │ ├── lookup.mdx │ │ │ │ │ └── transactionLookup.mdx │ │ │ │ ├── SimpleCache/ │ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOrSet.mdx │ │ │ │ │ └── purge.mdx │ │ │ │ ├── SimpleCacheEntry/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ └── text.mdx │ │ │ │ └── TransactionCacheEntry/ │ │ │ │ ├── age.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── cancel.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── hits.mdx │ │ │ │ ├── insert.mdx │ │ │ │ ├── insertAndStreamBack.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── maxAge.mdx │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ ├── state.mdx │ │ │ │ ├── update.mdx │ │ │ │ └── userMetadata.mdx │ │ │ ├── cache-override/ │ │ │ │ └── CacheOverride/ │ │ │ │ └── CacheOverride.mdx │ │ │ ├── compute/ │ │ │ │ ├── purgeSurrogateKey.mdx │ │ │ │ └── vCpuTime.mdx │ │ │ ├── config-store/ │ │ │ │ └── ConfigStore/ │ │ │ │ ├── ConfigStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── device/ │ │ │ │ └── Device/ │ │ │ │ ├── lookup.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── brand.mdx │ │ │ │ ├── hardwareType.mdx │ │ │ │ ├── isBot.mdx │ │ │ │ ├── isDesktop.mdx │ │ │ │ ├── isGameConsole.mdx │ │ │ │ ├── isMediaPlayer.mdx │ │ │ │ ├── isMobile.mdx │ │ │ │ ├── isSmartTV.mdx │ │ │ │ ├── isTablet.mdx │ │ │ │ ├── isTouchscreen.mdx │ │ │ │ ├── model.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toJSON.mdx │ │ │ ├── dictionary/ │ │ │ │ └── Dictionary/ │ │ │ │ ├── Dictionary.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── edge-rate-limiter/ │ │ │ │ ├── EdgeRateLimiter/ │ │ │ │ │ ├── EdgeRateLimiter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── checkRate.mdx │ │ │ │ ├── PenaltyBox/ │ │ │ │ │ ├── PenaltyBox.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ └── has.mdx │ │ │ │ └── RateCounter/ │ │ │ │ ├── RateCounter.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── increment.mdx │ │ │ │ ├── lookupCount.mdx │ │ │ │ └── lookupRate.mdx │ │ │ ├── env/ │ │ │ │ └── env.mdx │ │ │ ├── experimental/ │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── includeBytes.mdx │ │ │ │ ├── mapAndLogError.mdx │ │ │ │ ├── mapError.mdx │ │ │ │ └── sdkVersion.mdx │ │ │ ├── fanout/ │ │ │ │ └── createFanoutHandoff.mdx │ │ │ ├── geolocation/ │ │ │ │ └── getGeolocationForIpAddress.mdx │ │ │ ├── globals/ │ │ │ │ ├── AggregrateError/ │ │ │ │ │ └── AggregrateError.mdx │ │ │ │ ├── Array/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Array.mdx │ │ │ │ │ ├── from.mdx │ │ │ │ │ ├── isArray.mdx │ │ │ │ │ ├── of.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── @@unscopables.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── copyWithin.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── every.mdx │ │ │ │ │ ├── fill.mdx │ │ │ │ │ ├── filter.mdx │ │ │ │ │ ├── find.mdx │ │ │ │ │ ├── findIndex.mdx │ │ │ │ │ ├── flat.mdx │ │ │ │ │ ├── flatMap.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── join.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── map.mdx │ │ │ │ │ ├── pop.mdx │ │ │ │ │ ├── push.mdx │ │ │ │ │ ├── reduce.mdx │ │ │ │ │ ├── reduceRight.mdx │ │ │ │ │ ├── reverse.mdx │ │ │ │ │ ├── shift.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── some.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── splice.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── unshift.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── ArrayBuffer/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ │ ├── isView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ └── slice.mdx │ │ │ │ ├── BigInt/ │ │ │ │ │ ├── BigInt.mdx │ │ │ │ │ ├── asIntN.mdx │ │ │ │ │ ├── asUintN.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── BigInt64Array/ │ │ │ │ │ └── BigInt64Array.mdx │ │ │ │ ├── BigUint64Array/ │ │ │ │ │ └── BigUint64Array.mdx │ │ │ │ ├── Blob/ │ │ │ │ │ ├── Blob.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── stream.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── type.mdx │ │ │ │ ├── Boolean/ │ │ │ │ │ ├── Boolean.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── size.mdx │ │ │ │ ├── CompressionStream/ │ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── CryptoKey/ │ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── algorithm.mdx │ │ │ │ │ ├── extractable.mdx │ │ │ │ │ ├── type.mdx │ │ │ │ │ └── usages.mdx │ │ │ │ ├── DOMException/ │ │ │ │ │ ├── DOMException.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ └── name.mdx │ │ │ │ ├── DataView/ │ │ │ │ │ ├── DataView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── buffer.mdx │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ ├── byteOffset.mdx │ │ │ │ │ ├── getBigInt64.mdx │ │ │ │ │ ├── getBigUint64.mdx │ │ │ │ │ ├── getFloat32.mdx │ │ │ │ │ ├── getFloat64.mdx │ │ │ │ │ ├── getInt16.mdx │ │ │ │ │ ├── getInt32.mdx │ │ │ │ │ ├── getInt8.mdx │ │ │ │ │ ├── getUint16.mdx │ │ │ │ │ ├── getUint32.mdx │ │ │ │ │ ├── getUint8.mdx │ │ │ │ │ ├── setBigInt64.mdx │ │ │ │ │ ├── setBigUint64.mdx │ │ │ │ │ ├── setFloat32.mdx │ │ │ │ │ ├── setFloat64.mdx │ │ │ │ │ ├── setInt16.mdx │ │ │ │ │ ├── setInt32.mdx │ │ │ │ │ ├── setInt8.mdx │ │ │ │ │ ├── setUint16.mdx │ │ │ │ │ ├── setUint32.mdx │ │ │ │ │ └── setUint8.mdx │ │ │ │ ├── Date/ │ │ │ │ │ ├── Date.mdx │ │ │ │ │ ├── UTC.mdx │ │ │ │ │ ├── now.mdx │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── getDate.mdx │ │ │ │ │ ├── getDay.mdx │ │ │ │ │ ├── getFullYear.mdx │ │ │ │ │ ├── getHours.mdx │ │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ │ ├── getMinutes.mdx │ │ │ │ │ ├── getMonth.mdx │ │ │ │ │ ├── getSeconds.mdx │ │ │ │ │ ├── getTime.mdx │ │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ │ ├── getUTCDate.mdx │ │ │ │ │ ├── getUTCDay.mdx │ │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ │ ├── getUTCHours.mdx │ │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ │ ├── getYear.mdx │ │ │ │ │ ├── setDate.mdx │ │ │ │ │ ├── setFullYear.mdx │ │ │ │ │ ├── setHours.mdx │ │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ │ ├── setMinutes.mdx │ │ │ │ │ ├── setMonth.mdx │ │ │ │ │ ├── setSeconds.mdx │ │ │ │ │ ├── setTime.mdx │ │ │ │ │ ├── setUTCDate.mdx │ │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ │ ├── setUTCHours.mdx │ │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ │ ├── setYear.mdx │ │ │ │ │ ├── toDateString.mdx │ │ │ │ │ ├── toISOString.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toTimeString.mdx │ │ │ │ │ ├── toUTCString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── DecompressionStream/ │ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── EcKeyImportParams/ │ │ │ │ │ └── EcKeyImportParams.mdx │ │ │ │ ├── EcdsaParams/ │ │ │ │ │ └── EcdsaParams.mdx │ │ │ │ ├── Error/ │ │ │ │ │ ├── Error.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cause.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── EvalError/ │ │ │ │ │ └── EvalError.mdx │ │ │ │ ├── FetchEvent/ │ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respondWith.mdx │ │ │ │ │ ├── sendEarlyHints.mdx │ │ │ │ │ └── waitUntil.mdx │ │ │ │ ├── FinalizationRegistry/ │ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── register.mdx │ │ │ │ │ └── unregister.mdx │ │ │ │ ├── Float32Array/ │ │ │ │ │ └── Float32Array.mdx │ │ │ │ ├── Float64Array/ │ │ │ │ │ └── Float64Array.mdx │ │ │ │ ├── FormData/ │ │ │ │ │ ├── FormData.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getAll.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Function/ │ │ │ │ │ ├── Function.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── bind.mdx │ │ │ │ │ ├── call.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── Headers/ │ │ │ │ │ ├── Headers.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getSetCookie.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── HmacImportParams/ │ │ │ │ │ └── HmacImportParams.mdx │ │ │ │ ├── Infinity.mdx │ │ │ │ ├── Int16Array/ │ │ │ │ │ └── Int16Array.mdx │ │ │ │ ├── Int32Array/ │ │ │ │ │ └── Int32Array.mdx │ │ │ │ ├── Int8Array/ │ │ │ │ │ └── Int8Array.mdx │ │ │ │ ├── JSON/ │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── stringify.mdx │ │ │ │ ├── Map/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Map.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Math/ │ │ │ │ │ ├── E.mdx │ │ │ │ │ ├── LN10.mdx │ │ │ │ │ ├── LN2.mdx │ │ │ │ │ ├── LOG10e.mdx │ │ │ │ │ ├── LOG2e.mdx │ │ │ │ │ ├── PI.mdx │ │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ │ ├── SQRT2.mdx │ │ │ │ │ ├── abs.mdx │ │ │ │ │ ├── acos.mdx │ │ │ │ │ ├── acosh.mdx │ │ │ │ │ ├── asin.mdx │ │ │ │ │ ├── asinh.mdx │ │ │ │ │ ├── atan.mdx │ │ │ │ │ ├── atan2.mdx │ │ │ │ │ ├── atanh.mdx │ │ │ │ │ ├── cbrt.mdx │ │ │ │ │ ├── ceil.mdx │ │ │ │ │ ├── clz32.mdx │ │ │ │ │ ├── cos.mdx │ │ │ │ │ ├── cosh.mdx │ │ │ │ │ ├── exp.mdx │ │ │ │ │ ├── expm1.mdx │ │ │ │ │ ├── floor.mdx │ │ │ │ │ ├── fround.mdx │ │ │ │ │ ├── hypot.mdx │ │ │ │ │ ├── imul.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── log10.mdx │ │ │ │ │ ├── log1p.mdx │ │ │ │ │ ├── log2.mdx │ │ │ │ │ ├── max.mdx │ │ │ │ │ ├── min.mdx │ │ │ │ │ ├── pow.mdx │ │ │ │ │ ├── random.mdx │ │ │ │ │ ├── round.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ ├── sin.mdx │ │ │ │ │ ├── sinh.mdx │ │ │ │ │ ├── sqrt.mdx │ │ │ │ │ ├── tan.mdx │ │ │ │ │ ├── tanh.mdx │ │ │ │ │ └── trunc.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number/ │ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ │ ├── NaN.mdx │ │ │ │ │ ├── Number.mdx │ │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ │ ├── epsilon.mdx │ │ │ │ │ ├── isFinite.mdx │ │ │ │ │ ├── isInteger.mdx │ │ │ │ │ ├── isNaN.mdx │ │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ │ ├── parseFloat.mdx │ │ │ │ │ ├── parseInt.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toExponential.mdx │ │ │ │ │ ├── toFixed.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toPrecision.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── Object/ │ │ │ │ │ ├── Object.mdx │ │ │ │ │ ├── assign.mdx │ │ │ │ │ ├── create.mdx │ │ │ │ │ ├── defineProperties.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── freeze.mdx │ │ │ │ │ ├── fromEntries.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── hasOwn.mdx │ │ │ │ │ ├── is.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── isFrozen.mdx │ │ │ │ │ ├── isSealed.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── seal.mdx │ │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Promise/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Promise.mdx │ │ │ │ │ ├── all.mdx │ │ │ │ │ ├── allSettled.mdx │ │ │ │ │ ├── any.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ │ ├── finally.mdx │ │ │ │ │ │ └── then.mdx │ │ │ │ │ ├── race.mdx │ │ │ │ │ ├── reject.mdx │ │ │ │ │ └── resolve.mdx │ │ │ │ ├── Proxy/ │ │ │ │ │ ├── Proxy.mdx │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ │ ├── construct.mdx │ │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ │ ├── get.mdx │ │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ │ ├── has.mdx │ │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ │ ├── set.mdx │ │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ │ └── revocable.mdx │ │ │ │ ├── RangeError/ │ │ │ │ │ └── RangeError.mdx │ │ │ │ ├── ReadableByteStreamController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byobRequest.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStream/ │ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── getReader.mdx │ │ │ │ │ ├── locked.mdx │ │ │ │ │ ├── pipeThrough.mdx │ │ │ │ │ ├── pipeTo.mdx │ │ │ │ │ └── tee.mdx │ │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respond.mdx │ │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ │ └── view.mdx │ │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReferenceError/ │ │ │ │ │ └── ReferenceError.mdx │ │ │ │ ├── Reflect/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ ├── Request/ │ │ │ │ │ ├── Request.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── blob.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── clone.mdx │ │ │ │ │ ├── formData.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── method.mdx │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ ├── Response/ │ │ │ │ │ ├── Response.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ │ ├── blob.mdx │ │ │ │ │ │ ├── body.mdx │ │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ │ ├── formData.mdx │ │ │ │ │ │ ├── headers.mdx │ │ │ │ │ │ ├── ip.mdx │ │ │ │ │ │ ├── json.mdx │ │ │ │ │ │ ├── ok.mdx │ │ │ │ │ │ ├── port.mdx │ │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ │ ├── status.mdx │ │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ │ ├── text.mdx │ │ │ │ │ │ └── url.mdx │ │ │ │ │ └── redirect.mdx │ │ │ │ ├── RsaHashedImportParams/ │ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ │ ├── Set/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Set.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── String/ │ │ │ │ │ ├── String.mdx │ │ │ │ │ ├── fromCharCode.mdx │ │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ │ ├── at.mdx │ │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ │ ├── concat.mdx │ │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ │ ├── includes.mdx │ │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ │ ├── length.mdx │ │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ │ ├── match.mdx │ │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ │ ├── replace.mdx │ │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ │ ├── search.mdx │ │ │ │ │ │ ├── slice.mdx │ │ │ │ │ │ ├── split.mdx │ │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ │ ├── substr.mdx │ │ │ │ │ │ ├── substring.mdx │ │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ │ ├── trim.mdx │ │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ └── raw.mdx │ │ │ │ ├── SubtleCrypto/ │ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── digest.mdx │ │ │ │ │ ├── importKey.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ └── verify.mdx │ │ │ │ ├── Symbol/ │ │ │ │ │ ├── Symbol.mdx │ │ │ │ │ ├── asyncIterator.mdx │ │ │ │ │ ├── for.mdx │ │ │ │ │ ├── hasInstance.mdx │ │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ │ ├── iterator.mdx │ │ │ │ │ ├── keyFor.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ │ ├── description.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── species.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── toPrimitive.mdx │ │ │ │ │ ├── toStringTag.mdx │ │ │ │ │ └── unscopables.mdx │ │ │ │ ├── SyntaxError/ │ │ │ │ │ └── SyntaxError.mdx │ │ │ │ ├── TextDecoder/ │ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── decode.mdx │ │ │ │ │ ├── encoding.mdx │ │ │ │ │ ├── fatal.mdx │ │ │ │ │ └── ignoreBOM.mdx │ │ │ │ ├── TextEncoder/ │ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── encode.mdx │ │ │ │ │ └── encoding.mdx │ │ │ │ ├── TransformStream/ │ │ │ │ │ ├── TransformStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ └── terminate.mdx │ │ │ │ ├── TypeError/ │ │ │ │ │ └── TypeError.mdx │ │ │ │ ├── URIError/ │ │ │ │ │ └── URIError.mdx │ │ │ │ ├── URL/ │ │ │ │ │ ├── URL.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── password.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── searchParams.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── username.mdx │ │ │ │ ├── URLSearchParams/ │ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Uint16Array/ │ │ │ │ │ └── Uint16Array.mdx │ │ │ │ ├── Uint32Array/ │ │ │ │ │ └── Uint32Array.mdx │ │ │ │ ├── Uint8Array/ │ │ │ │ │ └── Uint8Array.mdx │ │ │ │ ├── Uint8ClampedArray/ │ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ │ ├── WeakMap/ │ │ │ │ │ ├── WeakMap.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ └── set.mdx │ │ │ │ ├── WeakRef/ │ │ │ │ │ ├── WeakRef.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── deref.mdx │ │ │ │ ├── WeakSet/ │ │ │ │ │ ├── WeakSet.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ └── has.mdx │ │ │ │ ├── WorkerLocation/ │ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── WritableStream/ │ │ │ │ │ ├── WritableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── getWriter.mdx │ │ │ │ │ └── locked.mdx │ │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ │ └── error.mdx │ │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── ready.mdx │ │ │ │ │ ├── releaseLock.mdx │ │ │ │ │ └── write.mdx │ │ │ │ ├── atob.mdx │ │ │ │ ├── btoa.mdx │ │ │ │ ├── clearInterval.mdx │ │ │ │ ├── clearTimeout.mdx │ │ │ │ ├── console/ │ │ │ │ │ ├── assert.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── count.mdx │ │ │ │ │ ├── countReset.mdx │ │ │ │ │ ├── debug.mdx │ │ │ │ │ ├── dir.mdx │ │ │ │ │ ├── dirxml.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ ├── group.mdx │ │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ │ ├── groupEnd.mdx │ │ │ │ │ ├── info.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── time.mdx │ │ │ │ │ ├── timeEnd.mdx │ │ │ │ │ ├── timeLog.mdx │ │ │ │ │ ├── trace.mdx │ │ │ │ │ └── warn.mdx │ │ │ │ ├── crypto/ │ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ │ ├── randomUUID.mdx │ │ │ │ │ └── subtle.mdx │ │ │ │ ├── decodeURI.mdx │ │ │ │ ├── decodeURIComponent.mdx │ │ │ │ ├── encodeURI.mdx │ │ │ │ ├── encodeURIComponent.mdx │ │ │ │ ├── escape.mdx │ │ │ │ ├── eval.mdx │ │ │ │ ├── fetch.mdx │ │ │ │ ├── globalThis.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── location.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ ├── performance/ │ │ │ │ │ ├── now.mdx │ │ │ │ │ └── timeOrigin.mdx │ │ │ │ ├── setInterval.mdx │ │ │ │ ├── setTimeout.mdx │ │ │ │ ├── structuredClone.mdx │ │ │ │ ├── undefined.mdx │ │ │ │ └── unescape.mdx │ │ │ ├── html-rewriter/ │ │ │ │ ├── Element/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── after.mdx │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── before.mdx │ │ │ │ │ ├── hasAttribute.mdx │ │ │ │ │ ├── prepend.mdx │ │ │ │ │ ├── removeAttribute.mdx │ │ │ │ │ ├── replaceChildren.mdx │ │ │ │ │ ├── replaceWith.mdx │ │ │ │ │ ├── selector.mdx │ │ │ │ │ ├── setAttribute.mdx │ │ │ │ │ └── tag.mdx │ │ │ │ └── HTMLRewritingStream/ │ │ │ │ ├── HTMLRewritingStream.mdx │ │ │ │ └── prototype/ │ │ │ │ └── onElement.mdx │ │ │ ├── image-optimizer/ │ │ │ │ ├── Auto.mdx │ │ │ │ ├── BWAlgorithm.mdx │ │ │ │ ├── CropMode.mdx │ │ │ │ ├── Disable.mdx │ │ │ │ ├── Enable.mdx │ │ │ │ ├── Fit.mdx │ │ │ │ ├── Format.mdx │ │ │ │ ├── Metadata.mdx │ │ │ │ ├── Optimize.mdx │ │ │ │ ├── Orient.mdx │ │ │ │ ├── Profile.mdx │ │ │ │ ├── Region.mdx │ │ │ │ ├── ResizeFilter.mdx │ │ │ │ └── imageOptimizerOptions.mdx │ │ │ ├── index.mdx │ │ │ ├── kv-store/ │ │ │ │ ├── KVStore/ │ │ │ │ │ ├── KVStore.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── list.mdx │ │ │ │ │ └── put.mdx │ │ │ │ └── KVStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ ├── metadata.mdx │ │ │ │ ├── metadataText.mdx │ │ │ │ └── text.mdx │ │ │ ├── logger/ │ │ │ │ ├── Logger/ │ │ │ │ │ ├── Logger.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── log.mdx │ │ │ │ └── configureConsole.mdx │ │ │ ├── migration-guide/ │ │ │ │ └── index.mdx │ │ │ ├── secret-store/ │ │ │ │ ├── SecretStore/ │ │ │ │ │ ├── SecretStore.mdx │ │ │ │ │ ├── fromBytes.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── get.mdx │ │ │ │ └── SecretStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── plaintext.mdx │ │ │ │ └── rawBytes.mdx │ │ │ ├── security/ │ │ │ │ └── inspect.mdx │ │ │ ├── shielding/ │ │ │ │ └── Shield/ │ │ │ │ ├── Shield.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── encryptedBackend.mdx │ │ │ │ ├── runningOn.mdx │ │ │ │ └── unencryptedBackend.mdx │ │ │ └── websocket/ │ │ │ └── createWebsocketHandoff.mdx │ │ ├── version-3.40.0/ │ │ │ ├── acl/ │ │ │ │ └── Acl/ │ │ │ │ ├── open.mdx │ │ │ │ └── prototype/ │ │ │ │ └── lookup.mdx │ │ │ ├── backend/ │ │ │ │ ├── Backend/ │ │ │ │ │ ├── Backend.mdx │ │ │ │ │ ├── exists.mdx │ │ │ │ │ ├── fromName.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── betweenBytesTimeout.mdx │ │ │ │ │ ├── connectTimeout.mdx │ │ │ │ │ ├── firstByteTimeout.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ ├── hostOverride.mdx │ │ │ │ │ ├── httpKeepaliveTime.mdx │ │ │ │ │ ├── isDynamic.mdx │ │ │ │ │ ├── isSSL.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── target.mdx │ │ │ │ │ ├── tcpKeepalive.mdx │ │ │ │ │ ├── tlsMaxVersion.mdx │ │ │ │ │ ├── tlsMinVersion.mdx │ │ │ │ │ ├── toName.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── enforceExplicitBackends.mdx │ │ │ │ └── setDefaultDynamicBackendConfig.mdx │ │ │ ├── cache/ │ │ │ │ ├── CacheEntry/ │ │ │ │ │ ├── age.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── hits.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── maxAge.mdx │ │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ │ ├── state.mdx │ │ │ │ │ └── userMetadata.mdx │ │ │ │ ├── CacheState/ │ │ │ │ │ ├── found.mdx │ │ │ │ │ ├── mustInsertOrUpdate.mdx │ │ │ │ │ ├── stale.mdx │ │ │ │ │ └── usable.mdx │ │ │ │ ├── CoreCache/ │ │ │ │ │ ├── insert.mdx │ │ │ │ │ ├── lookup.mdx │ │ │ │ │ └── transactionLookup.mdx │ │ │ │ ├── SimpleCache/ │ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOrSet.mdx │ │ │ │ │ └── purge.mdx │ │ │ │ ├── SimpleCacheEntry/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ └── text.mdx │ │ │ │ └── TransactionCacheEntry/ │ │ │ │ ├── age.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── cancel.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── hits.mdx │ │ │ │ ├── insert.mdx │ │ │ │ ├── insertAndStreamBack.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── maxAge.mdx │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ ├── state.mdx │ │ │ │ ├── update.mdx │ │ │ │ └── userMetadata.mdx │ │ │ ├── cache-override/ │ │ │ │ └── CacheOverride/ │ │ │ │ └── CacheOverride.mdx │ │ │ ├── compute/ │ │ │ │ ├── purgeSurrogateKey.mdx │ │ │ │ └── vCpuTime.mdx │ │ │ ├── config-store/ │ │ │ │ └── ConfigStore/ │ │ │ │ ├── ConfigStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── device/ │ │ │ │ └── Device/ │ │ │ │ ├── lookup.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── brand.mdx │ │ │ │ ├── hardwareType.mdx │ │ │ │ ├── isBot.mdx │ │ │ │ ├── isDesktop.mdx │ │ │ │ ├── isGameConsole.mdx │ │ │ │ ├── isMediaPlayer.mdx │ │ │ │ ├── isMobile.mdx │ │ │ │ ├── isSmartTV.mdx │ │ │ │ ├── isTablet.mdx │ │ │ │ ├── isTouchscreen.mdx │ │ │ │ ├── model.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toJSON.mdx │ │ │ ├── dictionary/ │ │ │ │ └── Dictionary/ │ │ │ │ ├── Dictionary.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── edge-rate-limiter/ │ │ │ │ ├── EdgeRateLimiter/ │ │ │ │ │ ├── EdgeRateLimiter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── checkRate.mdx │ │ │ │ ├── PenaltyBox/ │ │ │ │ │ ├── PenaltyBox.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ └── has.mdx │ │ │ │ └── RateCounter/ │ │ │ │ ├── RateCounter.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── increment.mdx │ │ │ │ ├── lookupCount.mdx │ │ │ │ └── lookupRate.mdx │ │ │ ├── env/ │ │ │ │ └── env.mdx │ │ │ ├── experimental/ │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── includeBytes.mdx │ │ │ │ ├── mapAndLogError.mdx │ │ │ │ ├── mapError.mdx │ │ │ │ ├── sdkVersion.mdx │ │ │ │ └── setReusableSandboxOptions.mdx │ │ │ ├── fanout/ │ │ │ │ └── createFanoutHandoff.mdx │ │ │ ├── geolocation/ │ │ │ │ └── getGeolocationForIpAddress.mdx │ │ │ ├── globals/ │ │ │ │ ├── AggregrateError/ │ │ │ │ │ └── AggregrateError.mdx │ │ │ │ ├── Array/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Array.mdx │ │ │ │ │ ├── from.mdx │ │ │ │ │ ├── isArray.mdx │ │ │ │ │ ├── of.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── @@unscopables.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── copyWithin.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── every.mdx │ │ │ │ │ ├── fill.mdx │ │ │ │ │ ├── filter.mdx │ │ │ │ │ ├── find.mdx │ │ │ │ │ ├── findIndex.mdx │ │ │ │ │ ├── flat.mdx │ │ │ │ │ ├── flatMap.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── join.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── map.mdx │ │ │ │ │ ├── pop.mdx │ │ │ │ │ ├── push.mdx │ │ │ │ │ ├── reduce.mdx │ │ │ │ │ ├── reduceRight.mdx │ │ │ │ │ ├── reverse.mdx │ │ │ │ │ ├── shift.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── some.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── splice.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── unshift.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── ArrayBuffer/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ │ ├── isView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ └── slice.mdx │ │ │ │ ├── BigInt/ │ │ │ │ │ ├── BigInt.mdx │ │ │ │ │ ├── asIntN.mdx │ │ │ │ │ ├── asUintN.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── BigInt64Array/ │ │ │ │ │ └── BigInt64Array.mdx │ │ │ │ ├── BigUint64Array/ │ │ │ │ │ └── BigUint64Array.mdx │ │ │ │ ├── Blob/ │ │ │ │ │ ├── Blob.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── stream.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── type.mdx │ │ │ │ ├── Boolean/ │ │ │ │ │ ├── Boolean.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── size.mdx │ │ │ │ ├── CompressionStream/ │ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── CryptoKey/ │ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── algorithm.mdx │ │ │ │ │ ├── extractable.mdx │ │ │ │ │ ├── type.mdx │ │ │ │ │ └── usages.mdx │ │ │ │ ├── DOMException/ │ │ │ │ │ ├── DOMException.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ └── name.mdx │ │ │ │ ├── DataView/ │ │ │ │ │ ├── DataView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── buffer.mdx │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ ├── byteOffset.mdx │ │ │ │ │ ├── getBigInt64.mdx │ │ │ │ │ ├── getBigUint64.mdx │ │ │ │ │ ├── getFloat32.mdx │ │ │ │ │ ├── getFloat64.mdx │ │ │ │ │ ├── getInt16.mdx │ │ │ │ │ ├── getInt32.mdx │ │ │ │ │ ├── getInt8.mdx │ │ │ │ │ ├── getUint16.mdx │ │ │ │ │ ├── getUint32.mdx │ │ │ │ │ ├── getUint8.mdx │ │ │ │ │ ├── setBigInt64.mdx │ │ │ │ │ ├── setBigUint64.mdx │ │ │ │ │ ├── setFloat32.mdx │ │ │ │ │ ├── setFloat64.mdx │ │ │ │ │ ├── setInt16.mdx │ │ │ │ │ ├── setInt32.mdx │ │ │ │ │ ├── setInt8.mdx │ │ │ │ │ ├── setUint16.mdx │ │ │ │ │ ├── setUint32.mdx │ │ │ │ │ └── setUint8.mdx │ │ │ │ ├── Date/ │ │ │ │ │ ├── Date.mdx │ │ │ │ │ ├── UTC.mdx │ │ │ │ │ ├── now.mdx │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── getDate.mdx │ │ │ │ │ ├── getDay.mdx │ │ │ │ │ ├── getFullYear.mdx │ │ │ │ │ ├── getHours.mdx │ │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ │ ├── getMinutes.mdx │ │ │ │ │ ├── getMonth.mdx │ │ │ │ │ ├── getSeconds.mdx │ │ │ │ │ ├── getTime.mdx │ │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ │ ├── getUTCDate.mdx │ │ │ │ │ ├── getUTCDay.mdx │ │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ │ ├── getUTCHours.mdx │ │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ │ ├── getYear.mdx │ │ │ │ │ ├── setDate.mdx │ │ │ │ │ ├── setFullYear.mdx │ │ │ │ │ ├── setHours.mdx │ │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ │ ├── setMinutes.mdx │ │ │ │ │ ├── setMonth.mdx │ │ │ │ │ ├── setSeconds.mdx │ │ │ │ │ ├── setTime.mdx │ │ │ │ │ ├── setUTCDate.mdx │ │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ │ ├── setUTCHours.mdx │ │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ │ ├── setYear.mdx │ │ │ │ │ ├── toDateString.mdx │ │ │ │ │ ├── toISOString.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toTimeString.mdx │ │ │ │ │ ├── toUTCString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── DecompressionStream/ │ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── EcKeyImportParams/ │ │ │ │ │ └── EcKeyImportParams.mdx │ │ │ │ ├── EcdsaParams/ │ │ │ │ │ └── EcdsaParams.mdx │ │ │ │ ├── Error/ │ │ │ │ │ ├── Error.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cause.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── EvalError/ │ │ │ │ │ └── EvalError.mdx │ │ │ │ ├── FetchEvent/ │ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respondWith.mdx │ │ │ │ │ ├── sendEarlyHints.mdx │ │ │ │ │ └── waitUntil.mdx │ │ │ │ ├── FinalizationRegistry/ │ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── register.mdx │ │ │ │ │ └── unregister.mdx │ │ │ │ ├── Float32Array/ │ │ │ │ │ └── Float32Array.mdx │ │ │ │ ├── Float64Array/ │ │ │ │ │ └── Float64Array.mdx │ │ │ │ ├── FormData/ │ │ │ │ │ ├── FormData.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getAll.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Function/ │ │ │ │ │ ├── Function.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── bind.mdx │ │ │ │ │ ├── call.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── Headers/ │ │ │ │ │ ├── Headers.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getSetCookie.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── HmacImportParams/ │ │ │ │ │ └── HmacImportParams.mdx │ │ │ │ ├── Infinity.mdx │ │ │ │ ├── Int16Array/ │ │ │ │ │ └── Int16Array.mdx │ │ │ │ ├── Int32Array/ │ │ │ │ │ └── Int32Array.mdx │ │ │ │ ├── Int8Array/ │ │ │ │ │ └── Int8Array.mdx │ │ │ │ ├── JSON/ │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── stringify.mdx │ │ │ │ ├── Map/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Map.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Math/ │ │ │ │ │ ├── E.mdx │ │ │ │ │ ├── LN10.mdx │ │ │ │ │ ├── LN2.mdx │ │ │ │ │ ├── LOG10e.mdx │ │ │ │ │ ├── LOG2e.mdx │ │ │ │ │ ├── PI.mdx │ │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ │ ├── SQRT2.mdx │ │ │ │ │ ├── abs.mdx │ │ │ │ │ ├── acos.mdx │ │ │ │ │ ├── acosh.mdx │ │ │ │ │ ├── asin.mdx │ │ │ │ │ ├── asinh.mdx │ │ │ │ │ ├── atan.mdx │ │ │ │ │ ├── atan2.mdx │ │ │ │ │ ├── atanh.mdx │ │ │ │ │ ├── cbrt.mdx │ │ │ │ │ ├── ceil.mdx │ │ │ │ │ ├── clz32.mdx │ │ │ │ │ ├── cos.mdx │ │ │ │ │ ├── cosh.mdx │ │ │ │ │ ├── exp.mdx │ │ │ │ │ ├── expm1.mdx │ │ │ │ │ ├── floor.mdx │ │ │ │ │ ├── fround.mdx │ │ │ │ │ ├── hypot.mdx │ │ │ │ │ ├── imul.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── log10.mdx │ │ │ │ │ ├── log1p.mdx │ │ │ │ │ ├── log2.mdx │ │ │ │ │ ├── max.mdx │ │ │ │ │ ├── min.mdx │ │ │ │ │ ├── pow.mdx │ │ │ │ │ ├── random.mdx │ │ │ │ │ ├── round.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ ├── sin.mdx │ │ │ │ │ ├── sinh.mdx │ │ │ │ │ ├── sqrt.mdx │ │ │ │ │ ├── tan.mdx │ │ │ │ │ ├── tanh.mdx │ │ │ │ │ └── trunc.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number/ │ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ │ ├── NaN.mdx │ │ │ │ │ ├── Number.mdx │ │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ │ ├── epsilon.mdx │ │ │ │ │ ├── isFinite.mdx │ │ │ │ │ ├── isInteger.mdx │ │ │ │ │ ├── isNaN.mdx │ │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ │ ├── parseFloat.mdx │ │ │ │ │ ├── parseInt.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toExponential.mdx │ │ │ │ │ ├── toFixed.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toPrecision.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── Object/ │ │ │ │ │ ├── Object.mdx │ │ │ │ │ ├── assign.mdx │ │ │ │ │ ├── create.mdx │ │ │ │ │ ├── defineProperties.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── freeze.mdx │ │ │ │ │ ├── fromEntries.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── hasOwn.mdx │ │ │ │ │ ├── is.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── isFrozen.mdx │ │ │ │ │ ├── isSealed.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── seal.mdx │ │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Promise/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Promise.mdx │ │ │ │ │ ├── all.mdx │ │ │ │ │ ├── allSettled.mdx │ │ │ │ │ ├── any.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ │ ├── finally.mdx │ │ │ │ │ │ └── then.mdx │ │ │ │ │ ├── race.mdx │ │ │ │ │ ├── reject.mdx │ │ │ │ │ └── resolve.mdx │ │ │ │ ├── Proxy/ │ │ │ │ │ ├── Proxy.mdx │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ │ ├── construct.mdx │ │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ │ ├── get.mdx │ │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ │ ├── has.mdx │ │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ │ ├── set.mdx │ │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ │ └── revocable.mdx │ │ │ │ ├── RangeError/ │ │ │ │ │ └── RangeError.mdx │ │ │ │ ├── ReadableByteStreamController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byobRequest.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStream/ │ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── getReader.mdx │ │ │ │ │ ├── locked.mdx │ │ │ │ │ ├── pipeThrough.mdx │ │ │ │ │ ├── pipeTo.mdx │ │ │ │ │ └── tee.mdx │ │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respond.mdx │ │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ │ └── view.mdx │ │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReferenceError/ │ │ │ │ │ └── ReferenceError.mdx │ │ │ │ ├── Reflect/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ ├── Request/ │ │ │ │ │ ├── Request.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── blob.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── clone.mdx │ │ │ │ │ ├── formData.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── method.mdx │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ ├── Response/ │ │ │ │ │ ├── Response.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ │ ├── blob.mdx │ │ │ │ │ │ ├── body.mdx │ │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ │ ├── formData.mdx │ │ │ │ │ │ ├── headers.mdx │ │ │ │ │ │ ├── ip.mdx │ │ │ │ │ │ ├── json.mdx │ │ │ │ │ │ ├── ok.mdx │ │ │ │ │ │ ├── port.mdx │ │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ │ ├── status.mdx │ │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ │ ├── text.mdx │ │ │ │ │ │ └── url.mdx │ │ │ │ │ └── redirect.mdx │ │ │ │ ├── RsaHashedImportParams/ │ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ │ ├── Set/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Set.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── String/ │ │ │ │ │ ├── String.mdx │ │ │ │ │ ├── fromCharCode.mdx │ │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ │ ├── at.mdx │ │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ │ ├── concat.mdx │ │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ │ ├── includes.mdx │ │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ │ ├── length.mdx │ │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ │ ├── match.mdx │ │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ │ ├── replace.mdx │ │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ │ ├── search.mdx │ │ │ │ │ │ ├── slice.mdx │ │ │ │ │ │ ├── split.mdx │ │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ │ ├── substr.mdx │ │ │ │ │ │ ├── substring.mdx │ │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ │ ├── trim.mdx │ │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ └── raw.mdx │ │ │ │ ├── SubtleCrypto/ │ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── digest.mdx │ │ │ │ │ ├── importKey.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ └── verify.mdx │ │ │ │ ├── Symbol/ │ │ │ │ │ ├── Symbol.mdx │ │ │ │ │ ├── asyncIterator.mdx │ │ │ │ │ ├── for.mdx │ │ │ │ │ ├── hasInstance.mdx │ │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ │ ├── iterator.mdx │ │ │ │ │ ├── keyFor.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ │ ├── description.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── species.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── toPrimitive.mdx │ │ │ │ │ ├── toStringTag.mdx │ │ │ │ │ └── unscopables.mdx │ │ │ │ ├── SyntaxError/ │ │ │ │ │ └── SyntaxError.mdx │ │ │ │ ├── TextDecoder/ │ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── decode.mdx │ │ │ │ │ ├── encoding.mdx │ │ │ │ │ ├── fatal.mdx │ │ │ │ │ └── ignoreBOM.mdx │ │ │ │ ├── TextEncoder/ │ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── encode.mdx │ │ │ │ │ └── encoding.mdx │ │ │ │ ├── TransformStream/ │ │ │ │ │ ├── TransformStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ └── terminate.mdx │ │ │ │ ├── TypeError/ │ │ │ │ │ └── TypeError.mdx │ │ │ │ ├── URIError/ │ │ │ │ │ └── URIError.mdx │ │ │ │ ├── URL/ │ │ │ │ │ ├── URL.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── password.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── searchParams.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── username.mdx │ │ │ │ ├── URLSearchParams/ │ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Uint16Array/ │ │ │ │ │ └── Uint16Array.mdx │ │ │ │ ├── Uint32Array/ │ │ │ │ │ └── Uint32Array.mdx │ │ │ │ ├── Uint8Array/ │ │ │ │ │ └── Uint8Array.mdx │ │ │ │ ├── Uint8ClampedArray/ │ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ │ ├── WeakMap/ │ │ │ │ │ ├── WeakMap.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ └── set.mdx │ │ │ │ ├── WeakRef/ │ │ │ │ │ ├── WeakRef.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── deref.mdx │ │ │ │ ├── WeakSet/ │ │ │ │ │ ├── WeakSet.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ └── has.mdx │ │ │ │ ├── WorkerLocation/ │ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── WritableStream/ │ │ │ │ │ ├── WritableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── getWriter.mdx │ │ │ │ │ └── locked.mdx │ │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ │ └── error.mdx │ │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── ready.mdx │ │ │ │ │ ├── releaseLock.mdx │ │ │ │ │ └── write.mdx │ │ │ │ ├── atob.mdx │ │ │ │ ├── btoa.mdx │ │ │ │ ├── clearInterval.mdx │ │ │ │ ├── clearTimeout.mdx │ │ │ │ ├── console/ │ │ │ │ │ ├── assert.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── count.mdx │ │ │ │ │ ├── countReset.mdx │ │ │ │ │ ├── debug.mdx │ │ │ │ │ ├── dir.mdx │ │ │ │ │ ├── dirxml.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ ├── group.mdx │ │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ │ ├── groupEnd.mdx │ │ │ │ │ ├── info.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── time.mdx │ │ │ │ │ ├── timeEnd.mdx │ │ │ │ │ ├── timeLog.mdx │ │ │ │ │ ├── trace.mdx │ │ │ │ │ └── warn.mdx │ │ │ │ ├── crypto/ │ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ │ ├── randomUUID.mdx │ │ │ │ │ └── subtle.mdx │ │ │ │ ├── decodeURI.mdx │ │ │ │ ├── decodeURIComponent.mdx │ │ │ │ ├── encodeURI.mdx │ │ │ │ ├── encodeURIComponent.mdx │ │ │ │ ├── escape.mdx │ │ │ │ ├── eval.mdx │ │ │ │ ├── fetch.mdx │ │ │ │ ├── globalThis.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── location.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ ├── performance/ │ │ │ │ │ ├── now.mdx │ │ │ │ │ └── timeOrigin.mdx │ │ │ │ ├── setInterval.mdx │ │ │ │ ├── setTimeout.mdx │ │ │ │ ├── structuredClone.mdx │ │ │ │ ├── undefined.mdx │ │ │ │ └── unescape.mdx │ │ │ ├── html-rewriter/ │ │ │ │ ├── Element/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── after.mdx │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── before.mdx │ │ │ │ │ ├── hasAttribute.mdx │ │ │ │ │ ├── prepend.mdx │ │ │ │ │ ├── removeAttribute.mdx │ │ │ │ │ ├── replaceChildren.mdx │ │ │ │ │ ├── replaceWith.mdx │ │ │ │ │ ├── selector.mdx │ │ │ │ │ ├── setAttribute.mdx │ │ │ │ │ └── tag.mdx │ │ │ │ └── HTMLRewritingStream/ │ │ │ │ ├── HTMLRewritingStream.mdx │ │ │ │ └── prototype/ │ │ │ │ └── onElement.mdx │ │ │ ├── image-optimizer/ │ │ │ │ ├── Auto.mdx │ │ │ │ ├── BWAlgorithm.mdx │ │ │ │ ├── CropMode.mdx │ │ │ │ ├── Disable.mdx │ │ │ │ ├── Enable.mdx │ │ │ │ ├── Fit.mdx │ │ │ │ ├── Format.mdx │ │ │ │ ├── Metadata.mdx │ │ │ │ ├── Optimize.mdx │ │ │ │ ├── Orient.mdx │ │ │ │ ├── Profile.mdx │ │ │ │ ├── Region.mdx │ │ │ │ ├── ResizeFilter.mdx │ │ │ │ └── imageOptimizerOptions.mdx │ │ │ ├── index.mdx │ │ │ ├── kv-store/ │ │ │ │ ├── KVStore/ │ │ │ │ │ ├── KVStore.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── list.mdx │ │ │ │ │ └── put.mdx │ │ │ │ └── KVStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ ├── metadata.mdx │ │ │ │ ├── metadataText.mdx │ │ │ │ └── text.mdx │ │ │ ├── logger/ │ │ │ │ ├── Logger/ │ │ │ │ │ ├── Logger.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── log.mdx │ │ │ │ └── configureConsole.mdx │ │ │ ├── migration-guide/ │ │ │ │ └── index.mdx │ │ │ ├── secret-store/ │ │ │ │ ├── SecretStore/ │ │ │ │ │ ├── SecretStore.mdx │ │ │ │ │ ├── fromBytes.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── get.mdx │ │ │ │ └── SecretStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── plaintext.mdx │ │ │ │ └── rawBytes.mdx │ │ │ ├── security/ │ │ │ │ └── inspect.mdx │ │ │ ├── shielding/ │ │ │ │ └── Shield/ │ │ │ │ ├── Shield.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── encryptedBackend.mdx │ │ │ │ ├── runningOn.mdx │ │ │ │ └── unencryptedBackend.mdx │ │ │ └── websocket/ │ │ │ └── createWebsocketHandoff.mdx │ │ ├── version-3.40.1/ │ │ │ ├── acl/ │ │ │ │ └── Acl/ │ │ │ │ ├── open.mdx │ │ │ │ └── prototype/ │ │ │ │ └── lookup.mdx │ │ │ ├── backend/ │ │ │ │ ├── Backend/ │ │ │ │ │ ├── Backend.mdx │ │ │ │ │ ├── exists.mdx │ │ │ │ │ ├── fromName.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── betweenBytesTimeout.mdx │ │ │ │ │ ├── connectTimeout.mdx │ │ │ │ │ ├── firstByteTimeout.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ ├── hostOverride.mdx │ │ │ │ │ ├── httpKeepaliveTime.mdx │ │ │ │ │ ├── isDynamic.mdx │ │ │ │ │ ├── isSSL.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── target.mdx │ │ │ │ │ ├── tcpKeepalive.mdx │ │ │ │ │ ├── tlsMaxVersion.mdx │ │ │ │ │ ├── tlsMinVersion.mdx │ │ │ │ │ ├── toName.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── enforceExplicitBackends.mdx │ │ │ │ └── setDefaultDynamicBackendConfig.mdx │ │ │ ├── cache/ │ │ │ │ ├── CacheEntry/ │ │ │ │ │ ├── age.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── hits.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── maxAge.mdx │ │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ │ ├── state.mdx │ │ │ │ │ └── userMetadata.mdx │ │ │ │ ├── CacheState/ │ │ │ │ │ ├── found.mdx │ │ │ │ │ ├── mustInsertOrUpdate.mdx │ │ │ │ │ ├── stale.mdx │ │ │ │ │ └── usable.mdx │ │ │ │ ├── CoreCache/ │ │ │ │ │ ├── insert.mdx │ │ │ │ │ ├── lookup.mdx │ │ │ │ │ └── transactionLookup.mdx │ │ │ │ ├── SimpleCache/ │ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOrSet.mdx │ │ │ │ │ └── purge.mdx │ │ │ │ ├── SimpleCacheEntry/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ └── text.mdx │ │ │ │ └── TransactionCacheEntry/ │ │ │ │ ├── age.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── cancel.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── hits.mdx │ │ │ │ ├── insert.mdx │ │ │ │ ├── insertAndStreamBack.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── maxAge.mdx │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ ├── state.mdx │ │ │ │ ├── update.mdx │ │ │ │ └── userMetadata.mdx │ │ │ ├── cache-override/ │ │ │ │ └── CacheOverride/ │ │ │ │ └── CacheOverride.mdx │ │ │ ├── compute/ │ │ │ │ ├── purgeSurrogateKey.mdx │ │ │ │ └── vCpuTime.mdx │ │ │ ├── config-store/ │ │ │ │ └── ConfigStore/ │ │ │ │ ├── ConfigStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── device/ │ │ │ │ └── Device/ │ │ │ │ ├── lookup.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── brand.mdx │ │ │ │ ├── hardwareType.mdx │ │ │ │ ├── isBot.mdx │ │ │ │ ├── isDesktop.mdx │ │ │ │ ├── isGameConsole.mdx │ │ │ │ ├── isMediaPlayer.mdx │ │ │ │ ├── isMobile.mdx │ │ │ │ ├── isSmartTV.mdx │ │ │ │ ├── isTablet.mdx │ │ │ │ ├── isTouchscreen.mdx │ │ │ │ ├── model.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toJSON.mdx │ │ │ ├── dictionary/ │ │ │ │ └── Dictionary/ │ │ │ │ ├── Dictionary.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── edge-rate-limiter/ │ │ │ │ ├── EdgeRateLimiter/ │ │ │ │ │ ├── EdgeRateLimiter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── checkRate.mdx │ │ │ │ ├── PenaltyBox/ │ │ │ │ │ ├── PenaltyBox.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ └── has.mdx │ │ │ │ └── RateCounter/ │ │ │ │ ├── RateCounter.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── increment.mdx │ │ │ │ ├── lookupCount.mdx │ │ │ │ └── lookupRate.mdx │ │ │ ├── env/ │ │ │ │ └── env.mdx │ │ │ ├── experimental/ │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── includeBytes.mdx │ │ │ │ ├── mapAndLogError.mdx │ │ │ │ ├── mapError.mdx │ │ │ │ ├── sdkVersion.mdx │ │ │ │ └── setReusableSandboxOptions.mdx │ │ │ ├── fanout/ │ │ │ │ └── createFanoutHandoff.mdx │ │ │ ├── geolocation/ │ │ │ │ └── getGeolocationForIpAddress.mdx │ │ │ ├── globals/ │ │ │ │ ├── AggregrateError/ │ │ │ │ │ └── AggregrateError.mdx │ │ │ │ ├── Array/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Array.mdx │ │ │ │ │ ├── from.mdx │ │ │ │ │ ├── isArray.mdx │ │ │ │ │ ├── of.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── @@unscopables.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── copyWithin.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── every.mdx │ │ │ │ │ ├── fill.mdx │ │ │ │ │ ├── filter.mdx │ │ │ │ │ ├── find.mdx │ │ │ │ │ ├── findIndex.mdx │ │ │ │ │ ├── flat.mdx │ │ │ │ │ ├── flatMap.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── join.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── map.mdx │ │ │ │ │ ├── pop.mdx │ │ │ │ │ ├── push.mdx │ │ │ │ │ ├── reduce.mdx │ │ │ │ │ ├── reduceRight.mdx │ │ │ │ │ ├── reverse.mdx │ │ │ │ │ ├── shift.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── some.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── splice.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── unshift.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── ArrayBuffer/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ │ ├── isView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ └── slice.mdx │ │ │ │ ├── BigInt/ │ │ │ │ │ ├── BigInt.mdx │ │ │ │ │ ├── asIntN.mdx │ │ │ │ │ ├── asUintN.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── BigInt64Array/ │ │ │ │ │ └── BigInt64Array.mdx │ │ │ │ ├── BigUint64Array/ │ │ │ │ │ └── BigUint64Array.mdx │ │ │ │ ├── Blob/ │ │ │ │ │ ├── Blob.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── stream.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── type.mdx │ │ │ │ ├── Boolean/ │ │ │ │ │ ├── Boolean.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── size.mdx │ │ │ │ ├── CompressionStream/ │ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── CryptoKey/ │ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── algorithm.mdx │ │ │ │ │ ├── extractable.mdx │ │ │ │ │ ├── type.mdx │ │ │ │ │ └── usages.mdx │ │ │ │ ├── DOMException/ │ │ │ │ │ ├── DOMException.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ └── name.mdx │ │ │ │ ├── DataView/ │ │ │ │ │ ├── DataView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── buffer.mdx │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ ├── byteOffset.mdx │ │ │ │ │ ├── getBigInt64.mdx │ │ │ │ │ ├── getBigUint64.mdx │ │ │ │ │ ├── getFloat32.mdx │ │ │ │ │ ├── getFloat64.mdx │ │ │ │ │ ├── getInt16.mdx │ │ │ │ │ ├── getInt32.mdx │ │ │ │ │ ├── getInt8.mdx │ │ │ │ │ ├── getUint16.mdx │ │ │ │ │ ├── getUint32.mdx │ │ │ │ │ ├── getUint8.mdx │ │ │ │ │ ├── setBigInt64.mdx │ │ │ │ │ ├── setBigUint64.mdx │ │ │ │ │ ├── setFloat32.mdx │ │ │ │ │ ├── setFloat64.mdx │ │ │ │ │ ├── setInt16.mdx │ │ │ │ │ ├── setInt32.mdx │ │ │ │ │ ├── setInt8.mdx │ │ │ │ │ ├── setUint16.mdx │ │ │ │ │ ├── setUint32.mdx │ │ │ │ │ └── setUint8.mdx │ │ │ │ ├── Date/ │ │ │ │ │ ├── Date.mdx │ │ │ │ │ ├── UTC.mdx │ │ │ │ │ ├── now.mdx │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── getDate.mdx │ │ │ │ │ ├── getDay.mdx │ │ │ │ │ ├── getFullYear.mdx │ │ │ │ │ ├── getHours.mdx │ │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ │ ├── getMinutes.mdx │ │ │ │ │ ├── getMonth.mdx │ │ │ │ │ ├── getSeconds.mdx │ │ │ │ │ ├── getTime.mdx │ │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ │ ├── getUTCDate.mdx │ │ │ │ │ ├── getUTCDay.mdx │ │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ │ ├── getUTCHours.mdx │ │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ │ ├── getYear.mdx │ │ │ │ │ ├── setDate.mdx │ │ │ │ │ ├── setFullYear.mdx │ │ │ │ │ ├── setHours.mdx │ │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ │ ├── setMinutes.mdx │ │ │ │ │ ├── setMonth.mdx │ │ │ │ │ ├── setSeconds.mdx │ │ │ │ │ ├── setTime.mdx │ │ │ │ │ ├── setUTCDate.mdx │ │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ │ ├── setUTCHours.mdx │ │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ │ ├── setYear.mdx │ │ │ │ │ ├── toDateString.mdx │ │ │ │ │ ├── toISOString.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toTimeString.mdx │ │ │ │ │ ├── toUTCString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── DecompressionStream/ │ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── EcKeyImportParams/ │ │ │ │ │ └── EcKeyImportParams.mdx │ │ │ │ ├── EcdsaParams/ │ │ │ │ │ └── EcdsaParams.mdx │ │ │ │ ├── Error/ │ │ │ │ │ ├── Error.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cause.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── EvalError/ │ │ │ │ │ └── EvalError.mdx │ │ │ │ ├── FetchEvent/ │ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respondWith.mdx │ │ │ │ │ ├── sendEarlyHints.mdx │ │ │ │ │ └── waitUntil.mdx │ │ │ │ ├── FinalizationRegistry/ │ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── register.mdx │ │ │ │ │ └── unregister.mdx │ │ │ │ ├── Float32Array/ │ │ │ │ │ └── Float32Array.mdx │ │ │ │ ├── Float64Array/ │ │ │ │ │ └── Float64Array.mdx │ │ │ │ ├── FormData/ │ │ │ │ │ ├── FormData.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getAll.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Function/ │ │ │ │ │ ├── Function.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── bind.mdx │ │ │ │ │ ├── call.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── Headers/ │ │ │ │ │ ├── Headers.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getSetCookie.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── HmacImportParams/ │ │ │ │ │ └── HmacImportParams.mdx │ │ │ │ ├── Infinity.mdx │ │ │ │ ├── Int16Array/ │ │ │ │ │ └── Int16Array.mdx │ │ │ │ ├── Int32Array/ │ │ │ │ │ └── Int32Array.mdx │ │ │ │ ├── Int8Array/ │ │ │ │ │ └── Int8Array.mdx │ │ │ │ ├── JSON/ │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── stringify.mdx │ │ │ │ ├── Map/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Map.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Math/ │ │ │ │ │ ├── E.mdx │ │ │ │ │ ├── LN10.mdx │ │ │ │ │ ├── LN2.mdx │ │ │ │ │ ├── LOG10e.mdx │ │ │ │ │ ├── LOG2e.mdx │ │ │ │ │ ├── PI.mdx │ │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ │ ├── SQRT2.mdx │ │ │ │ │ ├── abs.mdx │ │ │ │ │ ├── acos.mdx │ │ │ │ │ ├── acosh.mdx │ │ │ │ │ ├── asin.mdx │ │ │ │ │ ├── asinh.mdx │ │ │ │ │ ├── atan.mdx │ │ │ │ │ ├── atan2.mdx │ │ │ │ │ ├── atanh.mdx │ │ │ │ │ ├── cbrt.mdx │ │ │ │ │ ├── ceil.mdx │ │ │ │ │ ├── clz32.mdx │ │ │ │ │ ├── cos.mdx │ │ │ │ │ ├── cosh.mdx │ │ │ │ │ ├── exp.mdx │ │ │ │ │ ├── expm1.mdx │ │ │ │ │ ├── floor.mdx │ │ │ │ │ ├── fround.mdx │ │ │ │ │ ├── hypot.mdx │ │ │ │ │ ├── imul.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── log10.mdx │ │ │ │ │ ├── log1p.mdx │ │ │ │ │ ├── log2.mdx │ │ │ │ │ ├── max.mdx │ │ │ │ │ ├── min.mdx │ │ │ │ │ ├── pow.mdx │ │ │ │ │ ├── random.mdx │ │ │ │ │ ├── round.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ ├── sin.mdx │ │ │ │ │ ├── sinh.mdx │ │ │ │ │ ├── sqrt.mdx │ │ │ │ │ ├── tan.mdx │ │ │ │ │ ├── tanh.mdx │ │ │ │ │ └── trunc.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number/ │ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ │ ├── NaN.mdx │ │ │ │ │ ├── Number.mdx │ │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ │ ├── epsilon.mdx │ │ │ │ │ ├── isFinite.mdx │ │ │ │ │ ├── isInteger.mdx │ │ │ │ │ ├── isNaN.mdx │ │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ │ ├── parseFloat.mdx │ │ │ │ │ ├── parseInt.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toExponential.mdx │ │ │ │ │ ├── toFixed.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toPrecision.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── Object/ │ │ │ │ │ ├── Object.mdx │ │ │ │ │ ├── assign.mdx │ │ │ │ │ ├── create.mdx │ │ │ │ │ ├── defineProperties.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── freeze.mdx │ │ │ │ │ ├── fromEntries.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── hasOwn.mdx │ │ │ │ │ ├── is.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── isFrozen.mdx │ │ │ │ │ ├── isSealed.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── seal.mdx │ │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Promise/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Promise.mdx │ │ │ │ │ ├── all.mdx │ │ │ │ │ ├── allSettled.mdx │ │ │ │ │ ├── any.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ │ ├── finally.mdx │ │ │ │ │ │ └── then.mdx │ │ │ │ │ ├── race.mdx │ │ │ │ │ ├── reject.mdx │ │ │ │ │ └── resolve.mdx │ │ │ │ ├── Proxy/ │ │ │ │ │ ├── Proxy.mdx │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ │ ├── construct.mdx │ │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ │ ├── get.mdx │ │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ │ ├── has.mdx │ │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ │ ├── set.mdx │ │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ │ └── revocable.mdx │ │ │ │ ├── RangeError/ │ │ │ │ │ └── RangeError.mdx │ │ │ │ ├── ReadableByteStreamController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byobRequest.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStream/ │ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── getReader.mdx │ │ │ │ │ ├── locked.mdx │ │ │ │ │ ├── pipeThrough.mdx │ │ │ │ │ ├── pipeTo.mdx │ │ │ │ │ └── tee.mdx │ │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respond.mdx │ │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ │ └── view.mdx │ │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReferenceError/ │ │ │ │ │ └── ReferenceError.mdx │ │ │ │ ├── Reflect/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ ├── Request/ │ │ │ │ │ ├── Request.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── blob.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── clone.mdx │ │ │ │ │ ├── formData.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── method.mdx │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ ├── Response/ │ │ │ │ │ ├── Response.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ │ ├── blob.mdx │ │ │ │ │ │ ├── body.mdx │ │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ │ ├── formData.mdx │ │ │ │ │ │ ├── headers.mdx │ │ │ │ │ │ ├── ip.mdx │ │ │ │ │ │ ├── json.mdx │ │ │ │ │ │ ├── ok.mdx │ │ │ │ │ │ ├── port.mdx │ │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ │ ├── status.mdx │ │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ │ ├── text.mdx │ │ │ │ │ │ └── url.mdx │ │ │ │ │ └── redirect.mdx │ │ │ │ ├── RsaHashedImportParams/ │ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ │ ├── Set/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Set.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── String/ │ │ │ │ │ ├── String.mdx │ │ │ │ │ ├── fromCharCode.mdx │ │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ │ ├── at.mdx │ │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ │ ├── concat.mdx │ │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ │ ├── includes.mdx │ │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ │ ├── length.mdx │ │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ │ ├── match.mdx │ │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ │ ├── replace.mdx │ │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ │ ├── search.mdx │ │ │ │ │ │ ├── slice.mdx │ │ │ │ │ │ ├── split.mdx │ │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ │ ├── substr.mdx │ │ │ │ │ │ ├── substring.mdx │ │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ │ ├── trim.mdx │ │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ └── raw.mdx │ │ │ │ ├── SubtleCrypto/ │ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── digest.mdx │ │ │ │ │ ├── importKey.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ └── verify.mdx │ │ │ │ ├── Symbol/ │ │ │ │ │ ├── Symbol.mdx │ │ │ │ │ ├── asyncIterator.mdx │ │ │ │ │ ├── for.mdx │ │ │ │ │ ├── hasInstance.mdx │ │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ │ ├── iterator.mdx │ │ │ │ │ ├── keyFor.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ │ ├── description.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── species.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── toPrimitive.mdx │ │ │ │ │ ├── toStringTag.mdx │ │ │ │ │ └── unscopables.mdx │ │ │ │ ├── SyntaxError/ │ │ │ │ │ └── SyntaxError.mdx │ │ │ │ ├── TextDecoder/ │ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── decode.mdx │ │ │ │ │ ├── encoding.mdx │ │ │ │ │ ├── fatal.mdx │ │ │ │ │ └── ignoreBOM.mdx │ │ │ │ ├── TextEncoder/ │ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── encode.mdx │ │ │ │ │ └── encoding.mdx │ │ │ │ ├── TransformStream/ │ │ │ │ │ ├── TransformStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ └── terminate.mdx │ │ │ │ ├── TypeError/ │ │ │ │ │ └── TypeError.mdx │ │ │ │ ├── URIError/ │ │ │ │ │ └── URIError.mdx │ │ │ │ ├── URL/ │ │ │ │ │ ├── URL.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── password.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── searchParams.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── username.mdx │ │ │ │ ├── URLSearchParams/ │ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Uint16Array/ │ │ │ │ │ └── Uint16Array.mdx │ │ │ │ ├── Uint32Array/ │ │ │ │ │ └── Uint32Array.mdx │ │ │ │ ├── Uint8Array/ │ │ │ │ │ └── Uint8Array.mdx │ │ │ │ ├── Uint8ClampedArray/ │ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ │ ├── WeakMap/ │ │ │ │ │ ├── WeakMap.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ └── set.mdx │ │ │ │ ├── WeakRef/ │ │ │ │ │ ├── WeakRef.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── deref.mdx │ │ │ │ ├── WeakSet/ │ │ │ │ │ ├── WeakSet.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ └── has.mdx │ │ │ │ ├── WorkerLocation/ │ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── WritableStream/ │ │ │ │ │ ├── WritableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── getWriter.mdx │ │ │ │ │ └── locked.mdx │ │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ │ └── error.mdx │ │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── ready.mdx │ │ │ │ │ ├── releaseLock.mdx │ │ │ │ │ └── write.mdx │ │ │ │ ├── atob.mdx │ │ │ │ ├── btoa.mdx │ │ │ │ ├── clearInterval.mdx │ │ │ │ ├── clearTimeout.mdx │ │ │ │ ├── console/ │ │ │ │ │ ├── assert.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── count.mdx │ │ │ │ │ ├── countReset.mdx │ │ │ │ │ ├── debug.mdx │ │ │ │ │ ├── dir.mdx │ │ │ │ │ ├── dirxml.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ ├── group.mdx │ │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ │ ├── groupEnd.mdx │ │ │ │ │ ├── info.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── time.mdx │ │ │ │ │ ├── timeEnd.mdx │ │ │ │ │ ├── timeLog.mdx │ │ │ │ │ ├── trace.mdx │ │ │ │ │ └── warn.mdx │ │ │ │ ├── crypto/ │ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ │ ├── randomUUID.mdx │ │ │ │ │ └── subtle.mdx │ │ │ │ ├── decodeURI.mdx │ │ │ │ ├── decodeURIComponent.mdx │ │ │ │ ├── encodeURI.mdx │ │ │ │ ├── encodeURIComponent.mdx │ │ │ │ ├── escape.mdx │ │ │ │ ├── eval.mdx │ │ │ │ ├── fetch.mdx │ │ │ │ ├── globalThis.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── location.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ ├── performance/ │ │ │ │ │ ├── now.mdx │ │ │ │ │ └── timeOrigin.mdx │ │ │ │ ├── setInterval.mdx │ │ │ │ ├── setTimeout.mdx │ │ │ │ ├── structuredClone.mdx │ │ │ │ ├── undefined.mdx │ │ │ │ └── unescape.mdx │ │ │ ├── html-rewriter/ │ │ │ │ ├── Element/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── after.mdx │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── before.mdx │ │ │ │ │ ├── hasAttribute.mdx │ │ │ │ │ ├── prepend.mdx │ │ │ │ │ ├── removeAttribute.mdx │ │ │ │ │ ├── replaceChildren.mdx │ │ │ │ │ ├── replaceWith.mdx │ │ │ │ │ ├── selector.mdx │ │ │ │ │ ├── setAttribute.mdx │ │ │ │ │ └── tag.mdx │ │ │ │ └── HTMLRewritingStream/ │ │ │ │ ├── HTMLRewritingStream.mdx │ │ │ │ └── prototype/ │ │ │ │ └── onElement.mdx │ │ │ ├── image-optimizer/ │ │ │ │ ├── Auto.mdx │ │ │ │ ├── BWAlgorithm.mdx │ │ │ │ ├── CropMode.mdx │ │ │ │ ├── Disable.mdx │ │ │ │ ├── Enable.mdx │ │ │ │ ├── Fit.mdx │ │ │ │ ├── Format.mdx │ │ │ │ ├── Metadata.mdx │ │ │ │ ├── Optimize.mdx │ │ │ │ ├── Orient.mdx │ │ │ │ ├── Profile.mdx │ │ │ │ ├── Region.mdx │ │ │ │ ├── ResizeFilter.mdx │ │ │ │ └── imageOptimizerOptions.mdx │ │ │ ├── index.mdx │ │ │ ├── kv-store/ │ │ │ │ ├── KVStore/ │ │ │ │ │ ├── KVStore.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── list.mdx │ │ │ │ │ └── put.mdx │ │ │ │ └── KVStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ ├── metadata.mdx │ │ │ │ ├── metadataText.mdx │ │ │ │ └── text.mdx │ │ │ ├── logger/ │ │ │ │ ├── Logger/ │ │ │ │ │ ├── Logger.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── log.mdx │ │ │ │ └── configureConsole.mdx │ │ │ ├── migration-guide/ │ │ │ │ └── index.mdx │ │ │ ├── secret-store/ │ │ │ │ ├── SecretStore/ │ │ │ │ │ ├── SecretStore.mdx │ │ │ │ │ ├── fromBytes.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── get.mdx │ │ │ │ └── SecretStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── plaintext.mdx │ │ │ │ └── rawBytes.mdx │ │ │ ├── security/ │ │ │ │ └── inspect.mdx │ │ │ ├── shielding/ │ │ │ │ └── Shield/ │ │ │ │ ├── Shield.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── encryptedBackend.mdx │ │ │ │ ├── runningOn.mdx │ │ │ │ └── unencryptedBackend.mdx │ │ │ └── websocket/ │ │ │ └── createWebsocketHandoff.mdx │ │ ├── version-3.41.0/ │ │ │ ├── acl/ │ │ │ │ └── Acl/ │ │ │ │ ├── open.mdx │ │ │ │ └── prototype/ │ │ │ │ └── lookup.mdx │ │ │ ├── backend/ │ │ │ │ ├── Backend/ │ │ │ │ │ ├── Backend.mdx │ │ │ │ │ ├── exists.mdx │ │ │ │ │ ├── fromName.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── betweenBytesTimeout.mdx │ │ │ │ │ ├── connectTimeout.mdx │ │ │ │ │ ├── firstByteTimeout.mdx │ │ │ │ │ ├── health.mdx │ │ │ │ │ ├── hostOverride.mdx │ │ │ │ │ ├── httpKeepaliveTime.mdx │ │ │ │ │ ├── isDynamic.mdx │ │ │ │ │ ├── isSSL.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── target.mdx │ │ │ │ │ ├── tcpKeepalive.mdx │ │ │ │ │ ├── tlsMaxVersion.mdx │ │ │ │ │ ├── tlsMinVersion.mdx │ │ │ │ │ ├── toName.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── enforceExplicitBackends.mdx │ │ │ │ └── setDefaultDynamicBackendConfig.mdx │ │ │ ├── cache/ │ │ │ │ ├── CacheEntry/ │ │ │ │ │ ├── age.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── hits.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── maxAge.mdx │ │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ │ ├── state.mdx │ │ │ │ │ └── userMetadata.mdx │ │ │ │ ├── CacheState/ │ │ │ │ │ ├── found.mdx │ │ │ │ │ ├── mustInsertOrUpdate.mdx │ │ │ │ │ ├── stale.mdx │ │ │ │ │ └── usable.mdx │ │ │ │ ├── CoreCache/ │ │ │ │ │ ├── insert.mdx │ │ │ │ │ ├── lookup.mdx │ │ │ │ │ └── transactionLookup.mdx │ │ │ │ ├── SimpleCache/ │ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOrSet.mdx │ │ │ │ │ └── purge.mdx │ │ │ │ ├── SimpleCacheEntry/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ └── text.mdx │ │ │ │ └── TransactionCacheEntry/ │ │ │ │ ├── age.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── cancel.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── hits.mdx │ │ │ │ ├── insert.mdx │ │ │ │ ├── insertAndStreamBack.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── maxAge.mdx │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ ├── state.mdx │ │ │ │ ├── update.mdx │ │ │ │ └── userMetadata.mdx │ │ │ ├── cache-override/ │ │ │ │ └── CacheOverride/ │ │ │ │ └── CacheOverride.mdx │ │ │ ├── compute/ │ │ │ │ ├── purgeSurrogateKey.mdx │ │ │ │ └── vCpuTime.mdx │ │ │ ├── config-store/ │ │ │ │ └── ConfigStore/ │ │ │ │ ├── ConfigStore.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── device/ │ │ │ │ └── Device/ │ │ │ │ ├── lookup.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── brand.mdx │ │ │ │ ├── hardwareType.mdx │ │ │ │ ├── isBot.mdx │ │ │ │ ├── isDesktop.mdx │ │ │ │ ├── isGameConsole.mdx │ │ │ │ ├── isMediaPlayer.mdx │ │ │ │ ├── isMobile.mdx │ │ │ │ ├── isSmartTV.mdx │ │ │ │ ├── isTablet.mdx │ │ │ │ ├── isTouchscreen.mdx │ │ │ │ ├── model.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toJSON.mdx │ │ │ ├── dictionary/ │ │ │ │ └── Dictionary/ │ │ │ │ ├── Dictionary.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ ├── edge-rate-limiter/ │ │ │ │ ├── EdgeRateLimiter/ │ │ │ │ │ ├── EdgeRateLimiter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── checkRate.mdx │ │ │ │ ├── PenaltyBox/ │ │ │ │ │ ├── PenaltyBox.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ └── has.mdx │ │ │ │ └── RateCounter/ │ │ │ │ ├── RateCounter.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── increment.mdx │ │ │ │ ├── lookupCount.mdx │ │ │ │ └── lookupRate.mdx │ │ │ ├── env/ │ │ │ │ └── env.mdx │ │ │ ├── experimental/ │ │ │ │ ├── allowDynamicBackends.mdx │ │ │ │ ├── includeBytes.mdx │ │ │ │ ├── mapAndLogError.mdx │ │ │ │ ├── mapError.mdx │ │ │ │ ├── sdkVersion.mdx │ │ │ │ └── setReusableSandboxOptions.mdx │ │ │ ├── fanout/ │ │ │ │ └── createFanoutHandoff.mdx │ │ │ ├── geolocation/ │ │ │ │ └── getGeolocationForIpAddress.mdx │ │ │ ├── globals/ │ │ │ │ ├── AggregrateError/ │ │ │ │ │ └── AggregrateError.mdx │ │ │ │ ├── Array/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Array.mdx │ │ │ │ │ ├── from.mdx │ │ │ │ │ ├── isArray.mdx │ │ │ │ │ ├── of.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── @@unscopables.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── copyWithin.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── every.mdx │ │ │ │ │ ├── fill.mdx │ │ │ │ │ ├── filter.mdx │ │ │ │ │ ├── find.mdx │ │ │ │ │ ├── findIndex.mdx │ │ │ │ │ ├── flat.mdx │ │ │ │ │ ├── flatMap.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── join.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── map.mdx │ │ │ │ │ ├── pop.mdx │ │ │ │ │ ├── push.mdx │ │ │ │ │ ├── reduce.mdx │ │ │ │ │ ├── reduceRight.mdx │ │ │ │ │ ├── reverse.mdx │ │ │ │ │ ├── shift.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── some.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── splice.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── unshift.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── ArrayBuffer/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ │ ├── isView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ └── slice.mdx │ │ │ │ ├── BigInt/ │ │ │ │ │ ├── BigInt.mdx │ │ │ │ │ ├── asIntN.mdx │ │ │ │ │ ├── asUintN.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── BigInt64Array/ │ │ │ │ │ └── BigInt64Array.mdx │ │ │ │ ├── BigUint64Array/ │ │ │ │ │ └── BigUint64Array.mdx │ │ │ │ ├── Blob/ │ │ │ │ │ ├── Blob.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── stream.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── type.mdx │ │ │ │ ├── Boolean/ │ │ │ │ │ ├── Boolean.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── size.mdx │ │ │ │ ├── CompressionStream/ │ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── CryptoKey/ │ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── algorithm.mdx │ │ │ │ │ ├── extractable.mdx │ │ │ │ │ ├── type.mdx │ │ │ │ │ └── usages.mdx │ │ │ │ ├── DOMException/ │ │ │ │ │ ├── DOMException.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ └── name.mdx │ │ │ │ ├── DataView/ │ │ │ │ │ ├── DataView.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── buffer.mdx │ │ │ │ │ ├── byteLength.mdx │ │ │ │ │ ├── byteOffset.mdx │ │ │ │ │ ├── getBigInt64.mdx │ │ │ │ │ ├── getBigUint64.mdx │ │ │ │ │ ├── getFloat32.mdx │ │ │ │ │ ├── getFloat64.mdx │ │ │ │ │ ├── getInt16.mdx │ │ │ │ │ ├── getInt32.mdx │ │ │ │ │ ├── getInt8.mdx │ │ │ │ │ ├── getUint16.mdx │ │ │ │ │ ├── getUint32.mdx │ │ │ │ │ ├── getUint8.mdx │ │ │ │ │ ├── setBigInt64.mdx │ │ │ │ │ ├── setBigUint64.mdx │ │ │ │ │ ├── setFloat32.mdx │ │ │ │ │ ├── setFloat64.mdx │ │ │ │ │ ├── setInt16.mdx │ │ │ │ │ ├── setInt32.mdx │ │ │ │ │ ├── setInt8.mdx │ │ │ │ │ ├── setUint16.mdx │ │ │ │ │ ├── setUint32.mdx │ │ │ │ │ └── setUint8.mdx │ │ │ │ ├── Date/ │ │ │ │ │ ├── Date.mdx │ │ │ │ │ ├── UTC.mdx │ │ │ │ │ ├── now.mdx │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── getDate.mdx │ │ │ │ │ ├── getDay.mdx │ │ │ │ │ ├── getFullYear.mdx │ │ │ │ │ ├── getHours.mdx │ │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ │ ├── getMinutes.mdx │ │ │ │ │ ├── getMonth.mdx │ │ │ │ │ ├── getSeconds.mdx │ │ │ │ │ ├── getTime.mdx │ │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ │ ├── getUTCDate.mdx │ │ │ │ │ ├── getUTCDay.mdx │ │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ │ ├── getUTCHours.mdx │ │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ │ ├── getYear.mdx │ │ │ │ │ ├── setDate.mdx │ │ │ │ │ ├── setFullYear.mdx │ │ │ │ │ ├── setHours.mdx │ │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ │ ├── setMinutes.mdx │ │ │ │ │ ├── setMonth.mdx │ │ │ │ │ ├── setSeconds.mdx │ │ │ │ │ ├── setTime.mdx │ │ │ │ │ ├── setUTCDate.mdx │ │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ │ ├── setUTCHours.mdx │ │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ │ ├── setYear.mdx │ │ │ │ │ ├── toDateString.mdx │ │ │ │ │ ├── toISOString.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toTimeString.mdx │ │ │ │ │ ├── toUTCString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── DecompressionStream/ │ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── EcKeyImportParams/ │ │ │ │ │ └── EcKeyImportParams.mdx │ │ │ │ ├── EcdsaParams/ │ │ │ │ │ └── EcdsaParams.mdx │ │ │ │ ├── Error/ │ │ │ │ │ ├── Error.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cause.mdx │ │ │ │ │ ├── message.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── EvalError/ │ │ │ │ │ └── EvalError.mdx │ │ │ │ ├── FetchEvent/ │ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respondWith.mdx │ │ │ │ │ ├── sendEarlyHints.mdx │ │ │ │ │ └── waitUntil.mdx │ │ │ │ ├── FinalizationRegistry/ │ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── register.mdx │ │ │ │ │ └── unregister.mdx │ │ │ │ ├── Float32Array/ │ │ │ │ │ └── Float32Array.mdx │ │ │ │ ├── Float64Array/ │ │ │ │ │ └── Float64Array.mdx │ │ │ │ ├── FormData/ │ │ │ │ │ ├── FormData.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getAll.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Function/ │ │ │ │ │ ├── Function.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── bind.mdx │ │ │ │ │ ├── call.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── name.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── Headers/ │ │ │ │ │ ├── Headers.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getSetCookie.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── HmacImportParams/ │ │ │ │ │ └── HmacImportParams.mdx │ │ │ │ ├── Infinity.mdx │ │ │ │ ├── Int16Array/ │ │ │ │ │ └── Int16Array.mdx │ │ │ │ ├── Int32Array/ │ │ │ │ │ └── Int32Array.mdx │ │ │ │ ├── Int8Array/ │ │ │ │ │ └── Int8Array.mdx │ │ │ │ ├── JSON/ │ │ │ │ │ ├── parse.mdx │ │ │ │ │ └── stringify.mdx │ │ │ │ ├── Map/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Map.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Math/ │ │ │ │ │ ├── E.mdx │ │ │ │ │ ├── LN10.mdx │ │ │ │ │ ├── LN2.mdx │ │ │ │ │ ├── LOG10e.mdx │ │ │ │ │ ├── LOG2e.mdx │ │ │ │ │ ├── PI.mdx │ │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ │ ├── SQRT2.mdx │ │ │ │ │ ├── abs.mdx │ │ │ │ │ ├── acos.mdx │ │ │ │ │ ├── acosh.mdx │ │ │ │ │ ├── asin.mdx │ │ │ │ │ ├── asinh.mdx │ │ │ │ │ ├── atan.mdx │ │ │ │ │ ├── atan2.mdx │ │ │ │ │ ├── atanh.mdx │ │ │ │ │ ├── cbrt.mdx │ │ │ │ │ ├── ceil.mdx │ │ │ │ │ ├── clz32.mdx │ │ │ │ │ ├── cos.mdx │ │ │ │ │ ├── cosh.mdx │ │ │ │ │ ├── exp.mdx │ │ │ │ │ ├── expm1.mdx │ │ │ │ │ ├── floor.mdx │ │ │ │ │ ├── fround.mdx │ │ │ │ │ ├── hypot.mdx │ │ │ │ │ ├── imul.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── log10.mdx │ │ │ │ │ ├── log1p.mdx │ │ │ │ │ ├── log2.mdx │ │ │ │ │ ├── max.mdx │ │ │ │ │ ├── min.mdx │ │ │ │ │ ├── pow.mdx │ │ │ │ │ ├── random.mdx │ │ │ │ │ ├── round.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ ├── sin.mdx │ │ │ │ │ ├── sinh.mdx │ │ │ │ │ ├── sqrt.mdx │ │ │ │ │ ├── tan.mdx │ │ │ │ │ ├── tanh.mdx │ │ │ │ │ └── trunc.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number/ │ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ │ ├── NaN.mdx │ │ │ │ │ ├── Number.mdx │ │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ │ ├── epsilon.mdx │ │ │ │ │ ├── isFinite.mdx │ │ │ │ │ ├── isInteger.mdx │ │ │ │ │ ├── isNaN.mdx │ │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ │ ├── parseFloat.mdx │ │ │ │ │ ├── parseInt.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── toExponential.mdx │ │ │ │ │ ├── toFixed.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toPrecision.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── Object/ │ │ │ │ │ ├── Object.mdx │ │ │ │ │ ├── assign.mdx │ │ │ │ │ ├── create.mdx │ │ │ │ │ ├── defineProperties.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── freeze.mdx │ │ │ │ │ ├── fromEntries.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── hasOwn.mdx │ │ │ │ │ ├── is.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── isFrozen.mdx │ │ │ │ │ ├── isSealed.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── seal.mdx │ │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Promise/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Promise.mdx │ │ │ │ │ ├── all.mdx │ │ │ │ │ ├── allSettled.mdx │ │ │ │ │ ├── any.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ │ ├── finally.mdx │ │ │ │ │ │ └── then.mdx │ │ │ │ │ ├── race.mdx │ │ │ │ │ ├── reject.mdx │ │ │ │ │ └── resolve.mdx │ │ │ │ ├── Proxy/ │ │ │ │ │ ├── Proxy.mdx │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ │ ├── construct.mdx │ │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ │ ├── get.mdx │ │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ │ ├── has.mdx │ │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ │ ├── set.mdx │ │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ │ └── revocable.mdx │ │ │ │ ├── RangeError/ │ │ │ │ │ └── RangeError.mdx │ │ │ │ ├── ReadableByteStreamController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── byobRequest.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStream/ │ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── getReader.mdx │ │ │ │ │ ├── locked.mdx │ │ │ │ │ ├── pipeThrough.mdx │ │ │ │ │ ├── pipeTo.mdx │ │ │ │ │ └── tee.mdx │ │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── respond.mdx │ │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ │ └── view.mdx │ │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ └── error.mdx │ │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── cancel.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── read.mdx │ │ │ │ │ └── releaseLock.mdx │ │ │ │ ├── ReferenceError/ │ │ │ │ │ └── ReferenceError.mdx │ │ │ │ ├── Reflect/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ ├── Request/ │ │ │ │ │ ├── Request.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── blob.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── clone.mdx │ │ │ │ │ ├── formData.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── method.mdx │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ ├── Response/ │ │ │ │ │ ├── Response.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ │ ├── blob.mdx │ │ │ │ │ │ ├── body.mdx │ │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ │ ├── formData.mdx │ │ │ │ │ │ ├── headers.mdx │ │ │ │ │ │ ├── ip.mdx │ │ │ │ │ │ ├── json.mdx │ │ │ │ │ │ ├── ok.mdx │ │ │ │ │ │ ├── port.mdx │ │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ │ ├── status.mdx │ │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ │ ├── text.mdx │ │ │ │ │ │ └── url.mdx │ │ │ │ │ └── redirect.mdx │ │ │ │ ├── RsaHashedImportParams/ │ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ │ ├── Set/ │ │ │ │ │ ├── @@species.mdx │ │ │ │ │ ├── Set.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── size.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── String/ │ │ │ │ │ ├── String.mdx │ │ │ │ │ ├── fromCharCode.mdx │ │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ │ ├── at.mdx │ │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ │ ├── concat.mdx │ │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ │ ├── includes.mdx │ │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ │ ├── length.mdx │ │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ │ ├── match.mdx │ │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ │ ├── replace.mdx │ │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ │ ├── search.mdx │ │ │ │ │ │ ├── slice.mdx │ │ │ │ │ │ ├── split.mdx │ │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ │ ├── substr.mdx │ │ │ │ │ │ ├── substring.mdx │ │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ │ ├── trim.mdx │ │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ └── raw.mdx │ │ │ │ ├── SubtleCrypto/ │ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── digest.mdx │ │ │ │ │ ├── importKey.mdx │ │ │ │ │ ├── sign.mdx │ │ │ │ │ └── verify.mdx │ │ │ │ ├── Symbol/ │ │ │ │ │ ├── Symbol.mdx │ │ │ │ │ ├── asyncIterator.mdx │ │ │ │ │ ├── for.mdx │ │ │ │ │ ├── hasInstance.mdx │ │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ │ ├── iterator.mdx │ │ │ │ │ ├── keyFor.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── prototype/ │ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ │ ├── description.mdx │ │ │ │ │ │ ├── toString.mdx │ │ │ │ │ │ └── valueOf.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── species.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── toPrimitive.mdx │ │ │ │ │ ├── toStringTag.mdx │ │ │ │ │ └── unscopables.mdx │ │ │ │ ├── SyntaxError/ │ │ │ │ │ └── SyntaxError.mdx │ │ │ │ ├── TextDecoder/ │ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── decode.mdx │ │ │ │ │ ├── encoding.mdx │ │ │ │ │ ├── fatal.mdx │ │ │ │ │ └── ignoreBOM.mdx │ │ │ │ ├── TextEncoder/ │ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── encode.mdx │ │ │ │ │ └── encoding.mdx │ │ │ │ ├── TransformStream/ │ │ │ │ │ ├── TransformStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── readable.mdx │ │ │ │ │ └── writable.mdx │ │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── enqueue.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ └── terminate.mdx │ │ │ │ ├── TypeError/ │ │ │ │ │ └── TypeError.mdx │ │ │ │ ├── URIError/ │ │ │ │ │ └── URIError.mdx │ │ │ │ ├── URL/ │ │ │ │ │ ├── URL.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── password.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── searchParams.mdx │ │ │ │ │ ├── toJSON.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── username.mdx │ │ │ │ ├── URLSearchParams/ │ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── entries.mdx │ │ │ │ │ ├── forEach.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── keys.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ ├── sort.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── values.mdx │ │ │ │ ├── Uint16Array/ │ │ │ │ │ └── Uint16Array.mdx │ │ │ │ ├── Uint32Array/ │ │ │ │ │ └── Uint32Array.mdx │ │ │ │ ├── Uint8Array/ │ │ │ │ │ └── Uint8Array.mdx │ │ │ │ ├── Uint8ClampedArray/ │ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ │ ├── WeakMap/ │ │ │ │ │ ├── WeakMap.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ └── set.mdx │ │ │ │ ├── WeakRef/ │ │ │ │ │ ├── WeakRef.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── deref.mdx │ │ │ │ ├── WeakSet/ │ │ │ │ │ ├── WeakSet.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── add.mdx │ │ │ │ │ ├── delete.mdx │ │ │ │ │ └── has.mdx │ │ │ │ ├── WorkerLocation/ │ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ │ ├── hash.mdx │ │ │ │ │ ├── host.mdx │ │ │ │ │ ├── hostname.mdx │ │ │ │ │ ├── href.mdx │ │ │ │ │ ├── origin.mdx │ │ │ │ │ ├── pathname.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── protocol.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ └── toString.mdx │ │ │ │ ├── WritableStream/ │ │ │ │ │ ├── WritableStream.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── getWriter.mdx │ │ │ │ │ └── locked.mdx │ │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ │ └── error.mdx │ │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── abort.mdx │ │ │ │ │ ├── close.mdx │ │ │ │ │ ├── closed.mdx │ │ │ │ │ ├── desiredSize.mdx │ │ │ │ │ ├── ready.mdx │ │ │ │ │ ├── releaseLock.mdx │ │ │ │ │ └── write.mdx │ │ │ │ ├── atob.mdx │ │ │ │ ├── btoa.mdx │ │ │ │ ├── clearInterval.mdx │ │ │ │ ├── clearTimeout.mdx │ │ │ │ ├── console/ │ │ │ │ │ ├── assert.mdx │ │ │ │ │ ├── clear.mdx │ │ │ │ │ ├── count.mdx │ │ │ │ │ ├── countReset.mdx │ │ │ │ │ ├── debug.mdx │ │ │ │ │ ├── dir.mdx │ │ │ │ │ ├── dirxml.mdx │ │ │ │ │ ├── error.mdx │ │ │ │ │ ├── group.mdx │ │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ │ ├── groupEnd.mdx │ │ │ │ │ ├── info.mdx │ │ │ │ │ ├── log.mdx │ │ │ │ │ ├── time.mdx │ │ │ │ │ ├── timeEnd.mdx │ │ │ │ │ ├── timeLog.mdx │ │ │ │ │ ├── trace.mdx │ │ │ │ │ └── warn.mdx │ │ │ │ ├── crypto/ │ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ │ ├── randomUUID.mdx │ │ │ │ │ └── subtle.mdx │ │ │ │ ├── decodeURI.mdx │ │ │ │ ├── decodeURIComponent.mdx │ │ │ │ ├── encodeURI.mdx │ │ │ │ ├── encodeURIComponent.mdx │ │ │ │ ├── escape.mdx │ │ │ │ ├── eval.mdx │ │ │ │ ├── fetch.mdx │ │ │ │ ├── globalThis.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── location.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ ├── performance/ │ │ │ │ │ ├── now.mdx │ │ │ │ │ └── timeOrigin.mdx │ │ │ │ ├── setInterval.mdx │ │ │ │ ├── setTimeout.mdx │ │ │ │ ├── structuredClone.mdx │ │ │ │ ├── undefined.mdx │ │ │ │ └── unescape.mdx │ │ │ ├── html-rewriter/ │ │ │ │ ├── Element/ │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── after.mdx │ │ │ │ │ ├── append.mdx │ │ │ │ │ ├── before.mdx │ │ │ │ │ ├── hasAttribute.mdx │ │ │ │ │ ├── prepend.mdx │ │ │ │ │ ├── removeAttribute.mdx │ │ │ │ │ ├── replaceChildren.mdx │ │ │ │ │ ├── replaceWith.mdx │ │ │ │ │ ├── selector.mdx │ │ │ │ │ ├── setAttribute.mdx │ │ │ │ │ └── tag.mdx │ │ │ │ └── HTMLRewritingStream/ │ │ │ │ ├── HTMLRewritingStream.mdx │ │ │ │ └── prototype/ │ │ │ │ └── onElement.mdx │ │ │ ├── image-optimizer/ │ │ │ │ ├── Auto.mdx │ │ │ │ ├── BWAlgorithm.mdx │ │ │ │ ├── CropMode.mdx │ │ │ │ ├── Disable.mdx │ │ │ │ ├── Enable.mdx │ │ │ │ ├── Fit.mdx │ │ │ │ ├── Format.mdx │ │ │ │ ├── Metadata.mdx │ │ │ │ ├── Optimize.mdx │ │ │ │ ├── Orient.mdx │ │ │ │ ├── Profile.mdx │ │ │ │ ├── Region.mdx │ │ │ │ ├── ResizeFilter.mdx │ │ │ │ └── imageOptimizerOptions.mdx │ │ │ ├── index.mdx │ │ │ ├── kv-store/ │ │ │ │ ├── KVStore/ │ │ │ │ │ ├── KVStore.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ ├── delete.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── list.mdx │ │ │ │ │ └── put.mdx │ │ │ │ └── KVStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ ├── metadata.mdx │ │ │ │ ├── metadataText.mdx │ │ │ │ └── text.mdx │ │ │ ├── logger/ │ │ │ │ ├── Logger/ │ │ │ │ │ ├── Logger.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── log.mdx │ │ │ │ └── configureConsole.mdx │ │ │ ├── migration-guide/ │ │ │ │ └── index.mdx │ │ │ ├── secret-store/ │ │ │ │ ├── SecretStore/ │ │ │ │ │ ├── SecretStore.mdx │ │ │ │ │ ├── fromBytes.mdx │ │ │ │ │ └── prototype/ │ │ │ │ │ └── get.mdx │ │ │ │ └── SecretStoreEntry/ │ │ │ │ └── prototype/ │ │ │ │ ├── plaintext.mdx │ │ │ │ └── rawBytes.mdx │ │ │ ├── security/ │ │ │ │ └── inspect.mdx │ │ │ ├── shielding/ │ │ │ │ └── Shield/ │ │ │ │ ├── Shield.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── encryptedBackend.mdx │ │ │ │ ├── runningOn.mdx │ │ │ │ └── unencryptedBackend.mdx │ │ │ └── websocket/ │ │ │ └── createWebsocketHandoff.mdx │ │ └── version-3.41.2/ │ │ ├── acl/ │ │ │ └── Acl/ │ │ │ ├── open.mdx │ │ │ └── prototype/ │ │ │ └── lookup.mdx │ │ ├── backend/ │ │ │ ├── Backend/ │ │ │ │ ├── Backend.mdx │ │ │ │ ├── exists.mdx │ │ │ │ ├── fromName.mdx │ │ │ │ ├── health.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── betweenBytesTimeout.mdx │ │ │ │ ├── connectTimeout.mdx │ │ │ │ ├── firstByteTimeout.mdx │ │ │ │ ├── health.mdx │ │ │ │ ├── hostOverride.mdx │ │ │ │ ├── httpKeepaliveTime.mdx │ │ │ │ ├── isDynamic.mdx │ │ │ │ ├── isSSL.mdx │ │ │ │ ├── name.mdx │ │ │ │ ├── port.mdx │ │ │ │ ├── target.mdx │ │ │ │ ├── tcpKeepalive.mdx │ │ │ │ ├── tlsMaxVersion.mdx │ │ │ │ ├── tlsMinVersion.mdx │ │ │ │ ├── toName.mdx │ │ │ │ └── toString.mdx │ │ │ ├── allowDynamicBackends.mdx │ │ │ ├── enforceExplicitBackends.mdx │ │ │ └── setDefaultDynamicBackendConfig.mdx │ │ ├── cache/ │ │ │ ├── CacheEntry/ │ │ │ │ ├── age.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── hits.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── maxAge.mdx │ │ │ │ ├── staleWhileRevalidate.mdx │ │ │ │ ├── state.mdx │ │ │ │ └── userMetadata.mdx │ │ │ ├── CacheState/ │ │ │ │ ├── found.mdx │ │ │ │ ├── mustInsertOrUpdate.mdx │ │ │ │ ├── stale.mdx │ │ │ │ └── usable.mdx │ │ │ ├── CoreCache/ │ │ │ │ ├── insert.mdx │ │ │ │ ├── lookup.mdx │ │ │ │ └── transactionLookup.mdx │ │ │ ├── SimpleCache/ │ │ │ │ ├── SimpleCache.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── getOrSet.mdx │ │ │ │ └── purge.mdx │ │ │ ├── SimpleCacheEntry/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── json.mdx │ │ │ │ └── text.mdx │ │ │ └── TransactionCacheEntry/ │ │ │ ├── age.mdx │ │ │ ├── body.mdx │ │ │ ├── cancel.mdx │ │ │ ├── close.mdx │ │ │ ├── hits.mdx │ │ │ ├── insert.mdx │ │ │ ├── insertAndStreamBack.mdx │ │ │ ├── length.mdx │ │ │ ├── maxAge.mdx │ │ │ ├── staleWhileRevalidate.mdx │ │ │ ├── state.mdx │ │ │ ├── update.mdx │ │ │ └── userMetadata.mdx │ │ ├── cache-override/ │ │ │ └── CacheOverride/ │ │ │ └── CacheOverride.mdx │ │ ├── compute/ │ │ │ ├── purgeSurrogateKey.mdx │ │ │ └── vCpuTime.mdx │ │ ├── config-store/ │ │ │ └── ConfigStore/ │ │ │ ├── ConfigStore.mdx │ │ │ └── prototype/ │ │ │ └── get.mdx │ │ ├── device/ │ │ │ └── Device/ │ │ │ ├── lookup.mdx │ │ │ └── prototype/ │ │ │ ├── brand.mdx │ │ │ ├── hardwareType.mdx │ │ │ ├── isBot.mdx │ │ │ ├── isDesktop.mdx │ │ │ ├── isGameConsole.mdx │ │ │ ├── isMediaPlayer.mdx │ │ │ ├── isMobile.mdx │ │ │ ├── isSmartTV.mdx │ │ │ ├── isTablet.mdx │ │ │ ├── isTouchscreen.mdx │ │ │ ├── model.mdx │ │ │ ├── name.mdx │ │ │ └── toJSON.mdx │ │ ├── dictionary/ │ │ │ └── Dictionary/ │ │ │ ├── Dictionary.mdx │ │ │ └── prototype/ │ │ │ └── get.mdx │ │ ├── edge-rate-limiter/ │ │ │ ├── EdgeRateLimiter/ │ │ │ │ ├── EdgeRateLimiter.mdx │ │ │ │ └── prototype/ │ │ │ │ └── checkRate.mdx │ │ │ ├── PenaltyBox/ │ │ │ │ ├── PenaltyBox.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── add.mdx │ │ │ │ └── has.mdx │ │ │ └── RateCounter/ │ │ │ ├── RateCounter.mdx │ │ │ └── prototype/ │ │ │ ├── increment.mdx │ │ │ ├── lookupCount.mdx │ │ │ └── lookupRate.mdx │ │ ├── env/ │ │ │ └── env.mdx │ │ ├── experimental/ │ │ │ ├── allowDynamicBackends.mdx │ │ │ ├── includeBytes.mdx │ │ │ ├── mapAndLogError.mdx │ │ │ ├── mapError.mdx │ │ │ ├── sdkVersion.mdx │ │ │ └── setReusableSandboxOptions.mdx │ │ ├── fanout/ │ │ │ └── createFanoutHandoff.mdx │ │ ├── geolocation/ │ │ │ └── getGeolocationForIpAddress.mdx │ │ ├── globals/ │ │ │ ├── AggregrateError/ │ │ │ │ └── AggregrateError.mdx │ │ │ ├── Array/ │ │ │ │ ├── @@species.mdx │ │ │ │ ├── Array.mdx │ │ │ │ ├── from.mdx │ │ │ │ ├── isArray.mdx │ │ │ │ ├── of.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── @@iterator.mdx │ │ │ │ ├── @@unscopables.mdx │ │ │ │ ├── at.mdx │ │ │ │ ├── concat.mdx │ │ │ │ ├── copyWithin.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── every.mdx │ │ │ │ ├── fill.mdx │ │ │ │ ├── filter.mdx │ │ │ │ ├── find.mdx │ │ │ │ ├── findIndex.mdx │ │ │ │ ├── flat.mdx │ │ │ │ ├── flatMap.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── includes.mdx │ │ │ │ ├── indexOf.mdx │ │ │ │ ├── join.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── map.mdx │ │ │ │ ├── pop.mdx │ │ │ │ ├── push.mdx │ │ │ │ ├── reduce.mdx │ │ │ │ ├── reduceRight.mdx │ │ │ │ ├── reverse.mdx │ │ │ │ ├── shift.mdx │ │ │ │ ├── slice.mdx │ │ │ │ ├── some.mdx │ │ │ │ ├── sort.mdx │ │ │ │ ├── splice.mdx │ │ │ │ ├── toLocaleString.mdx │ │ │ │ ├── toString.mdx │ │ │ │ ├── unshift.mdx │ │ │ │ └── values.mdx │ │ │ ├── ArrayBuffer/ │ │ │ │ ├── @@species.mdx │ │ │ │ ├── ArrayBuffer.mdx │ │ │ │ ├── isView.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── byteLength.mdx │ │ │ │ └── slice.mdx │ │ │ ├── BigInt/ │ │ │ │ ├── BigInt.mdx │ │ │ │ ├── asIntN.mdx │ │ │ │ ├── asUintN.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ ├── toString.mdx │ │ │ │ └── valueOf.mdx │ │ │ ├── BigInt64Array/ │ │ │ │ └── BigInt64Array.mdx │ │ │ ├── BigUint64Array/ │ │ │ │ └── BigUint64Array.mdx │ │ │ ├── Blob/ │ │ │ │ ├── Blob.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── size.mdx │ │ │ │ ├── slice.mdx │ │ │ │ ├── stream.mdx │ │ │ │ ├── text.mdx │ │ │ │ └── type.mdx │ │ │ ├── Boolean/ │ │ │ │ ├── Boolean.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── toString.mdx │ │ │ │ └── valueOf.mdx │ │ │ ├── ByteLengthQueuingStrategy/ │ │ │ │ ├── ByteLengthQueuingStrategy.mdx │ │ │ │ └── prototype/ │ │ │ │ └── size.mdx │ │ │ ├── CompressionStream/ │ │ │ │ ├── CompressionStream.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── readable.mdx │ │ │ │ └── writable.mdx │ │ │ ├── CryptoKey/ │ │ │ │ ├── CryptoKey.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── algorithm.mdx │ │ │ │ ├── extractable.mdx │ │ │ │ ├── type.mdx │ │ │ │ └── usages.mdx │ │ │ ├── DOMException/ │ │ │ │ ├── DOMException.mdx │ │ │ │ ├── code.mdx │ │ │ │ ├── message.mdx │ │ │ │ └── name.mdx │ │ │ ├── DataView/ │ │ │ │ ├── DataView.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── buffer.mdx │ │ │ │ ├── byteLength.mdx │ │ │ │ ├── byteOffset.mdx │ │ │ │ ├── getBigInt64.mdx │ │ │ │ ├── getBigUint64.mdx │ │ │ │ ├── getFloat32.mdx │ │ │ │ ├── getFloat64.mdx │ │ │ │ ├── getInt16.mdx │ │ │ │ ├── getInt32.mdx │ │ │ │ ├── getInt8.mdx │ │ │ │ ├── getUint16.mdx │ │ │ │ ├── getUint32.mdx │ │ │ │ ├── getUint8.mdx │ │ │ │ ├── setBigInt64.mdx │ │ │ │ ├── setBigUint64.mdx │ │ │ │ ├── setFloat32.mdx │ │ │ │ ├── setFloat64.mdx │ │ │ │ ├── setInt16.mdx │ │ │ │ ├── setInt32.mdx │ │ │ │ ├── setInt8.mdx │ │ │ │ ├── setUint16.mdx │ │ │ │ ├── setUint32.mdx │ │ │ │ └── setUint8.mdx │ │ │ ├── Date/ │ │ │ │ ├── Date.mdx │ │ │ │ ├── UTC.mdx │ │ │ │ ├── now.mdx │ │ │ │ ├── parse.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ ├── getDate.mdx │ │ │ │ ├── getDay.mdx │ │ │ │ ├── getFullYear.mdx │ │ │ │ ├── getHours.mdx │ │ │ │ ├── getMilliseconds.mdx │ │ │ │ ├── getMinutes.mdx │ │ │ │ ├── getMonth.mdx │ │ │ │ ├── getSeconds.mdx │ │ │ │ ├── getTime.mdx │ │ │ │ ├── getTimezoneOffset.mdx │ │ │ │ ├── getUTCDate.mdx │ │ │ │ ├── getUTCDay.mdx │ │ │ │ ├── getUTCFullYear.mdx │ │ │ │ ├── getUTCHours.mdx │ │ │ │ ├── getUTCMilliseconds.mdx │ │ │ │ ├── getUTCMinutes.mdx │ │ │ │ ├── getUTCMonth.mdx │ │ │ │ ├── getUTCSeconds.mdx │ │ │ │ ├── getYear.mdx │ │ │ │ ├── setDate.mdx │ │ │ │ ├── setFullYear.mdx │ │ │ │ ├── setHours.mdx │ │ │ │ ├── setMilliseconds.mdx │ │ │ │ ├── setMinutes.mdx │ │ │ │ ├── setMonth.mdx │ │ │ │ ├── setSeconds.mdx │ │ │ │ ├── setTime.mdx │ │ │ │ ├── setUTCDate.mdx │ │ │ │ ├── setUTCFullYear.mdx │ │ │ │ ├── setUTCHours.mdx │ │ │ │ ├── setUTCMilliseconds.mdx │ │ │ │ ├── setUTCMinutes.mdx │ │ │ │ ├── setUTCMonth.mdx │ │ │ │ ├── setUTCSeconds.mdx │ │ │ │ ├── setYear.mdx │ │ │ │ ├── toDateString.mdx │ │ │ │ ├── toISOString.mdx │ │ │ │ ├── toJSON.mdx │ │ │ │ ├── toLocaleDateString.mdx │ │ │ │ ├── toLocaleString.mdx │ │ │ │ ├── toLocaleTimeString.mdx │ │ │ │ ├── toString.mdx │ │ │ │ ├── toTimeString.mdx │ │ │ │ ├── toUTCString.mdx │ │ │ │ └── valueOf.mdx │ │ │ ├── DecompressionStream/ │ │ │ │ ├── DecompressionStream.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── readable.mdx │ │ │ │ └── writable.mdx │ │ │ ├── EcKeyImportParams/ │ │ │ │ └── EcKeyImportParams.mdx │ │ │ ├── EcdsaParams/ │ │ │ │ └── EcdsaParams.mdx │ │ │ ├── Error/ │ │ │ │ ├── Error.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── cause.mdx │ │ │ │ ├── message.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toString.mdx │ │ │ ├── EvalError/ │ │ │ │ └── EvalError.mdx │ │ │ ├── FetchEvent/ │ │ │ │ ├── FetchEvent.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── respondWith.mdx │ │ │ │ ├── sendEarlyHints.mdx │ │ │ │ └── waitUntil.mdx │ │ │ ├── FinalizationRegistry/ │ │ │ │ ├── FinalizationRegistry.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── register.mdx │ │ │ │ └── unregister.mdx │ │ │ ├── Float32Array/ │ │ │ │ └── Float32Array.mdx │ │ │ ├── Float64Array/ │ │ │ │ └── Float64Array.mdx │ │ │ ├── FormData/ │ │ │ │ ├── FormData.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── append.mdx │ │ │ │ ├── delete.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── getAll.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── set.mdx │ │ │ │ └── values.mdx │ │ │ ├── Function/ │ │ │ │ ├── Function.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── apply.mdx │ │ │ │ ├── bind.mdx │ │ │ │ ├── call.mdx │ │ │ │ ├── index.mdx │ │ │ │ ├── length.mdx │ │ │ │ ├── name.mdx │ │ │ │ └── toString.mdx │ │ │ ├── Headers/ │ │ │ │ ├── Headers.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── append.mdx │ │ │ │ ├── delete.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── getSetCookie.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── set.mdx │ │ │ │ └── values.mdx │ │ │ ├── HmacImportParams/ │ │ │ │ └── HmacImportParams.mdx │ │ │ ├── Infinity.mdx │ │ │ ├── Int16Array/ │ │ │ │ └── Int16Array.mdx │ │ │ ├── Int32Array/ │ │ │ │ └── Int32Array.mdx │ │ │ ├── Int8Array/ │ │ │ │ └── Int8Array.mdx │ │ │ ├── JSON/ │ │ │ │ ├── parse.mdx │ │ │ │ └── stringify.mdx │ │ │ ├── Map/ │ │ │ │ ├── @@species.mdx │ │ │ │ ├── Map.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── @@iterator.mdx │ │ │ │ ├── clear.mdx │ │ │ │ ├── delete.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── set.mdx │ │ │ │ ├── size.mdx │ │ │ │ └── values.mdx │ │ │ ├── Math/ │ │ │ │ ├── E.mdx │ │ │ │ ├── LN10.mdx │ │ │ │ ├── LN2.mdx │ │ │ │ ├── LOG10e.mdx │ │ │ │ ├── LOG2e.mdx │ │ │ │ ├── PI.mdx │ │ │ │ ├── SQRT1_2.mdx │ │ │ │ ├── SQRT2.mdx │ │ │ │ ├── abs.mdx │ │ │ │ ├── acos.mdx │ │ │ │ ├── acosh.mdx │ │ │ │ ├── asin.mdx │ │ │ │ ├── asinh.mdx │ │ │ │ ├── atan.mdx │ │ │ │ ├── atan2.mdx │ │ │ │ ├── atanh.mdx │ │ │ │ ├── cbrt.mdx │ │ │ │ ├── ceil.mdx │ │ │ │ ├── clz32.mdx │ │ │ │ ├── cos.mdx │ │ │ │ ├── cosh.mdx │ │ │ │ ├── exp.mdx │ │ │ │ ├── expm1.mdx │ │ │ │ ├── floor.mdx │ │ │ │ ├── fround.mdx │ │ │ │ ├── hypot.mdx │ │ │ │ ├── imul.mdx │ │ │ │ ├── log.mdx │ │ │ │ ├── log10.mdx │ │ │ │ ├── log1p.mdx │ │ │ │ ├── log2.mdx │ │ │ │ ├── max.mdx │ │ │ │ ├── min.mdx │ │ │ │ ├── pow.mdx │ │ │ │ ├── random.mdx │ │ │ │ ├── round.mdx │ │ │ │ ├── sign.mdx │ │ │ │ ├── sin.mdx │ │ │ │ ├── sinh.mdx │ │ │ │ ├── sqrt.mdx │ │ │ │ ├── tan.mdx │ │ │ │ ├── tanh.mdx │ │ │ │ └── trunc.mdx │ │ │ ├── NaN.mdx │ │ │ ├── Number/ │ │ │ │ ├── MAX_SAFE_INTEGER.mdx │ │ │ │ ├── MAX_VALUE.mdx │ │ │ │ ├── MIN_SAFE_INTEGER.mdx │ │ │ │ ├── MIN_VALUE.mdx │ │ │ │ ├── NEGATIVE_INFINITY.mdx │ │ │ │ ├── NaN.mdx │ │ │ │ ├── Number.mdx │ │ │ │ ├── POSITIVE_INFINITY.mdx │ │ │ │ ├── epsilon.mdx │ │ │ │ ├── isFinite.mdx │ │ │ │ ├── isInteger.mdx │ │ │ │ ├── isNaN.mdx │ │ │ │ ├── isSafeInteger.mdx │ │ │ │ ├── parseFloat.mdx │ │ │ │ ├── parseInt.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── toExponential.mdx │ │ │ │ ├── toFixed.mdx │ │ │ │ ├── toLocaleString.mdx │ │ │ │ ├── toPrecision.mdx │ │ │ │ ├── toString.mdx │ │ │ │ └── valueOf.mdx │ │ │ ├── Object/ │ │ │ │ ├── Object.mdx │ │ │ │ ├── assign.mdx │ │ │ │ ├── create.mdx │ │ │ │ ├── defineProperties.mdx │ │ │ │ ├── defineProperty.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── freeze.mdx │ │ │ │ ├── fromEntries.mdx │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ ├── getOwnPropertyDescriptors.mdx │ │ │ │ ├── getOwnPropertyNames.mdx │ │ │ │ ├── getOwnPropertySymbols.mdx │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ ├── hasOwn.mdx │ │ │ │ ├── is.mdx │ │ │ │ ├── isExtensible.mdx │ │ │ │ ├── isFrozen.mdx │ │ │ │ ├── isSealed.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── preventExtensions.mdx │ │ │ │ ├── prototype/ │ │ │ │ │ ├── constructor.mdx │ │ │ │ │ ├── hasOwnProperty.mdx │ │ │ │ │ ├── isPrototypeOf.mdx │ │ │ │ │ ├── propertyIsEnumerable.mdx │ │ │ │ │ ├── toLocaleString.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── seal.mdx │ │ │ │ ├── setPrototypeOf.mdx │ │ │ │ └── values.mdx │ │ │ ├── Promise/ │ │ │ │ ├── @@species.mdx │ │ │ │ ├── Promise.mdx │ │ │ │ ├── all.mdx │ │ │ │ ├── allSettled.mdx │ │ │ │ ├── any.mdx │ │ │ │ ├── prototype/ │ │ │ │ │ ├── catch.mdx │ │ │ │ │ ├── finally.mdx │ │ │ │ │ └── then.mdx │ │ │ │ ├── race.mdx │ │ │ │ ├── reject.mdx │ │ │ │ └── resolve.mdx │ │ │ ├── Proxy/ │ │ │ │ ├── Proxy.mdx │ │ │ │ ├── proxy/ │ │ │ │ │ ├── apply.mdx │ │ │ │ │ ├── construct.mdx │ │ │ │ │ ├── defineProperty.mdx │ │ │ │ │ ├── deleteProperty.mdx │ │ │ │ │ ├── get.mdx │ │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ │ ├── has.mdx │ │ │ │ │ ├── isExtensible.mdx │ │ │ │ │ ├── ownKeys.mdx │ │ │ │ │ ├── preventExtensions.mdx │ │ │ │ │ ├── set.mdx │ │ │ │ │ └── setPrototypeOf.mdx │ │ │ │ └── revocable.mdx │ │ │ ├── RangeError/ │ │ │ │ └── RangeError.mdx │ │ │ ├── ReadableByteStreamController/ │ │ │ │ └── prototype/ │ │ │ │ ├── byobRequest.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── desiredSize.mdx │ │ │ │ ├── enqueue.mdx │ │ │ │ └── error.mdx │ │ │ ├── ReadableStream/ │ │ │ │ ├── ReadableStream.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── cancel.mdx │ │ │ │ ├── getReader.mdx │ │ │ │ ├── locked.mdx │ │ │ │ ├── pipeThrough.mdx │ │ │ │ ├── pipeTo.mdx │ │ │ │ └── tee.mdx │ │ │ ├── ReadableStreamBYOBReader/ │ │ │ │ ├── ReadableStreamBYOBReader.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── cancel.mdx │ │ │ │ ├── closed.mdx │ │ │ │ ├── read.mdx │ │ │ │ └── releaseLock.mdx │ │ │ ├── ReadableStreamBYOBRequest/ │ │ │ │ └── prototype/ │ │ │ │ ├── respond.mdx │ │ │ │ ├── respondWithNewView.mdx │ │ │ │ └── view.mdx │ │ │ ├── ReadableStreamDefaultController/ │ │ │ │ └── prototype/ │ │ │ │ ├── close.mdx │ │ │ │ ├── desiredSize.mdx │ │ │ │ ├── enqueue.mdx │ │ │ │ └── error.mdx │ │ │ ├── ReadableStreamDefaultReader/ │ │ │ │ ├── ReadableStreamDefaultReader.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── cancel.mdx │ │ │ │ ├── closed.mdx │ │ │ │ ├── read.mdx │ │ │ │ └── releaseLock.mdx │ │ │ ├── ReferenceError/ │ │ │ │ └── ReferenceError.mdx │ │ │ ├── Reflect/ │ │ │ │ ├── apply.mdx │ │ │ │ ├── construct.mdx │ │ │ │ ├── defineProperty.mdx │ │ │ │ ├── deleteProperty.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── getOwnPropertyDescriptor.mdx │ │ │ │ ├── getPrototypeOf.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── isExtensible.mdx │ │ │ │ ├── ownKeys.mdx │ │ │ │ ├── preventExtensions.mdx │ │ │ │ ├── set.mdx │ │ │ │ └── setPrototypeOf.mdx │ │ │ ├── Request/ │ │ │ │ ├── Request.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ ├── blob.mdx │ │ │ │ ├── body.mdx │ │ │ │ ├── bodyUsed.mdx │ │ │ │ ├── clone.mdx │ │ │ │ ├── formData.mdx │ │ │ │ ├── headers.mdx │ │ │ │ ├── json.mdx │ │ │ │ ├── method.mdx │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ ├── text.mdx │ │ │ │ └── url.mdx │ │ │ ├── Response/ │ │ │ │ ├── Response.mdx │ │ │ │ ├── prototype/ │ │ │ │ │ ├── arrayBuffer.mdx │ │ │ │ │ ├── blob.mdx │ │ │ │ │ ├── body.mdx │ │ │ │ │ ├── bodyUsed.mdx │ │ │ │ │ ├── formData.mdx │ │ │ │ │ ├── headers.mdx │ │ │ │ │ ├── ip.mdx │ │ │ │ │ ├── json.mdx │ │ │ │ │ ├── ok.mdx │ │ │ │ │ ├── port.mdx │ │ │ │ │ ├── setManualFramingHeaders.mdx │ │ │ │ │ ├── status.mdx │ │ │ │ │ ├── statusText.mdx │ │ │ │ │ ├── text.mdx │ │ │ │ │ └── url.mdx │ │ │ │ └── redirect.mdx │ │ │ ├── RsaHashedImportParams/ │ │ │ │ └── RsaHashedImportParams.mdx │ │ │ ├── Set/ │ │ │ │ ├── @@species.mdx │ │ │ │ ├── Set.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── @@iterator.mdx │ │ │ │ ├── add.mdx │ │ │ │ ├── clear.mdx │ │ │ │ ├── delete.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── size.mdx │ │ │ │ └── values.mdx │ │ │ ├── String/ │ │ │ │ ├── String.mdx │ │ │ │ ├── fromCharCode.mdx │ │ │ │ ├── fromCodePoint.mdx │ │ │ │ ├── prototype/ │ │ │ │ │ ├── @@iterator.mdx │ │ │ │ │ ├── at.mdx │ │ │ │ │ ├── charAt.mdx │ │ │ │ │ ├── charCodeAt.mdx │ │ │ │ │ ├── codePointAt.mdx │ │ │ │ │ ├── concat.mdx │ │ │ │ │ ├── endsWith.mdx │ │ │ │ │ ├── includes.mdx │ │ │ │ │ ├── indexOf.mdx │ │ │ │ │ ├── lastIndexOf.mdx │ │ │ │ │ ├── length.mdx │ │ │ │ │ ├── localeCompare.mdx │ │ │ │ │ ├── match.mdx │ │ │ │ │ ├── matchAll.mdx │ │ │ │ │ ├── padEnd.mdx │ │ │ │ │ ├── padStart.mdx │ │ │ │ │ ├── repeat.mdx │ │ │ │ │ ├── replace.mdx │ │ │ │ │ ├── replaceAll.mdx │ │ │ │ │ ├── search.mdx │ │ │ │ │ ├── slice.mdx │ │ │ │ │ ├── split.mdx │ │ │ │ │ ├── startsWith.mdx │ │ │ │ │ ├── substr.mdx │ │ │ │ │ ├── substring.mdx │ │ │ │ │ ├── toLocaleLowerCase.mdx │ │ │ │ │ ├── toLocaleUpperCase.mdx │ │ │ │ │ ├── toLowerCase.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ ├── toUpperCase.mdx │ │ │ │ │ ├── trim.mdx │ │ │ │ │ ├── trimEnd.mdx │ │ │ │ │ ├── trimStart.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ └── raw.mdx │ │ │ ├── SubtleCrypto/ │ │ │ │ ├── SubtleCrypto.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── digest.mdx │ │ │ │ ├── importKey.mdx │ │ │ │ ├── sign.mdx │ │ │ │ └── verify.mdx │ │ │ ├── Symbol/ │ │ │ │ ├── Symbol.mdx │ │ │ │ ├── asyncIterator.mdx │ │ │ │ ├── for.mdx │ │ │ │ ├── hasInstance.mdx │ │ │ │ ├── isConcatSpreadable.mdx │ │ │ │ ├── iterator.mdx │ │ │ │ ├── keyFor.mdx │ │ │ │ ├── match.mdx │ │ │ │ ├── matchAll.mdx │ │ │ │ ├── prototype/ │ │ │ │ │ ├── @@toPrimitive.mdx │ │ │ │ │ ├── description.mdx │ │ │ │ │ ├── toString.mdx │ │ │ │ │ └── valueOf.mdx │ │ │ │ ├── replace.mdx │ │ │ │ ├── search.mdx │ │ │ │ ├── species.mdx │ │ │ │ ├── split.mdx │ │ │ │ ├── toPrimitive.mdx │ │ │ │ ├── toStringTag.mdx │ │ │ │ └── unscopables.mdx │ │ │ ├── SyntaxError/ │ │ │ │ └── SyntaxError.mdx │ │ │ ├── TextDecoder/ │ │ │ │ ├── TextDecoder.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── decode.mdx │ │ │ │ ├── encoding.mdx │ │ │ │ ├── fatal.mdx │ │ │ │ └── ignoreBOM.mdx │ │ │ ├── TextEncoder/ │ │ │ │ ├── TextEncoder.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── encode.mdx │ │ │ │ └── encoding.mdx │ │ │ ├── TransformStream/ │ │ │ │ ├── TransformStream.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── readable.mdx │ │ │ │ └── writable.mdx │ │ │ ├── TransformStreamDefaultController/ │ │ │ │ └── prototype/ │ │ │ │ ├── desiredSize.mdx │ │ │ │ ├── enqueue.mdx │ │ │ │ ├── error.mdx │ │ │ │ └── terminate.mdx │ │ │ ├── TypeError/ │ │ │ │ └── TypeError.mdx │ │ │ ├── URIError/ │ │ │ │ └── URIError.mdx │ │ │ ├── URL/ │ │ │ │ ├── URL.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── hash.mdx │ │ │ │ ├── host.mdx │ │ │ │ ├── hostname.mdx │ │ │ │ ├── href.mdx │ │ │ │ ├── origin.mdx │ │ │ │ ├── password.mdx │ │ │ │ ├── pathname.mdx │ │ │ │ ├── port.mdx │ │ │ │ ├── protocol.mdx │ │ │ │ ├── search.mdx │ │ │ │ ├── searchParams.mdx │ │ │ │ ├── toJSON.mdx │ │ │ │ ├── toString.mdx │ │ │ │ └── username.mdx │ │ │ ├── URLSearchParams/ │ │ │ │ ├── URLSearchParams.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── append.mdx │ │ │ │ ├── delete.mdx │ │ │ │ ├── entries.mdx │ │ │ │ ├── forEach.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── has.mdx │ │ │ │ ├── keys.mdx │ │ │ │ ├── set.mdx │ │ │ │ ├── sort.mdx │ │ │ │ ├── toString.mdx │ │ │ │ └── values.mdx │ │ │ ├── Uint16Array/ │ │ │ │ └── Uint16Array.mdx │ │ │ ├── Uint32Array/ │ │ │ │ └── Uint32Array.mdx │ │ │ ├── Uint8Array/ │ │ │ │ └── Uint8Array.mdx │ │ │ ├── Uint8ClampedArray/ │ │ │ │ └── Uint8ClampedArray.mdx │ │ │ ├── WeakMap/ │ │ │ │ ├── WeakMap.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── delete.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── has.mdx │ │ │ │ └── set.mdx │ │ │ ├── WeakRef/ │ │ │ │ ├── WeakRef.mdx │ │ │ │ └── prototype/ │ │ │ │ └── deref.mdx │ │ │ ├── WeakSet/ │ │ │ │ ├── WeakSet.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── add.mdx │ │ │ │ ├── delete.mdx │ │ │ │ └── has.mdx │ │ │ ├── WorkerLocation/ │ │ │ │ ├── WorkerLocation.mdx │ │ │ │ ├── hash.mdx │ │ │ │ ├── host.mdx │ │ │ │ ├── hostname.mdx │ │ │ │ ├── href.mdx │ │ │ │ ├── origin.mdx │ │ │ │ ├── pathname.mdx │ │ │ │ ├── port.mdx │ │ │ │ ├── protocol.mdx │ │ │ │ ├── search.mdx │ │ │ │ └── toString.mdx │ │ │ ├── WritableStream/ │ │ │ │ ├── WritableStream.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── abort.mdx │ │ │ │ ├── getWriter.mdx │ │ │ │ └── locked.mdx │ │ │ ├── WritableStreamDefaultController/ │ │ │ │ └── error.mdx │ │ │ ├── WritableStreamDefaultWriter/ │ │ │ │ ├── WritableStreamDefaultWriter.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── abort.mdx │ │ │ │ ├── close.mdx │ │ │ │ ├── closed.mdx │ │ │ │ ├── desiredSize.mdx │ │ │ │ ├── ready.mdx │ │ │ │ ├── releaseLock.mdx │ │ │ │ └── write.mdx │ │ │ ├── atob.mdx │ │ │ ├── btoa.mdx │ │ │ ├── clearInterval.mdx │ │ │ ├── clearTimeout.mdx │ │ │ ├── console/ │ │ │ │ ├── assert.mdx │ │ │ │ ├── clear.mdx │ │ │ │ ├── count.mdx │ │ │ │ ├── countReset.mdx │ │ │ │ ├── debug.mdx │ │ │ │ ├── dir.mdx │ │ │ │ ├── dirxml.mdx │ │ │ │ ├── error.mdx │ │ │ │ ├── group.mdx │ │ │ │ ├── groupCollapsed.mdx │ │ │ │ ├── groupEnd.mdx │ │ │ │ ├── info.mdx │ │ │ │ ├── log.mdx │ │ │ │ ├── time.mdx │ │ │ │ ├── timeEnd.mdx │ │ │ │ ├── timeLog.mdx │ │ │ │ ├── trace.mdx │ │ │ │ └── warn.mdx │ │ │ ├── crypto/ │ │ │ │ ├── getRandomValues.mdx │ │ │ │ ├── randomUUID.mdx │ │ │ │ └── subtle.mdx │ │ │ ├── decodeURI.mdx │ │ │ ├── decodeURIComponent.mdx │ │ │ ├── encodeURI.mdx │ │ │ ├── encodeURIComponent.mdx │ │ │ ├── escape.mdx │ │ │ ├── eval.mdx │ │ │ ├── fetch.mdx │ │ │ ├── globalThis.mdx │ │ │ ├── isFinite.mdx │ │ │ ├── isNaN.mdx │ │ │ ├── location.mdx │ │ │ ├── parseFloat.mdx │ │ │ ├── parseInt.mdx │ │ │ ├── performance/ │ │ │ │ ├── now.mdx │ │ │ │ └── timeOrigin.mdx │ │ │ ├── setInterval.mdx │ │ │ ├── setTimeout.mdx │ │ │ ├── structuredClone.mdx │ │ │ ├── undefined.mdx │ │ │ └── unescape.mdx │ │ ├── html-rewriter/ │ │ │ ├── Element/ │ │ │ │ └── prototype/ │ │ │ │ ├── after.mdx │ │ │ │ ├── append.mdx │ │ │ │ ├── before.mdx │ │ │ │ ├── hasAttribute.mdx │ │ │ │ ├── prepend.mdx │ │ │ │ ├── removeAttribute.mdx │ │ │ │ ├── replaceChildren.mdx │ │ │ │ ├── replaceWith.mdx │ │ │ │ ├── selector.mdx │ │ │ │ ├── setAttribute.mdx │ │ │ │ └── tag.mdx │ │ │ └── HTMLRewritingStream/ │ │ │ ├── HTMLRewritingStream.mdx │ │ │ └── prototype/ │ │ │ └── onElement.mdx │ │ ├── image-optimizer/ │ │ │ ├── Auto.mdx │ │ │ ├── BWAlgorithm.mdx │ │ │ ├── CropMode.mdx │ │ │ ├── Disable.mdx │ │ │ ├── Enable.mdx │ │ │ ├── Fit.mdx │ │ │ ├── Format.mdx │ │ │ ├── Metadata.mdx │ │ │ ├── Optimize.mdx │ │ │ ├── Orient.mdx │ │ │ ├── Profile.mdx │ │ │ ├── Region.mdx │ │ │ ├── ResizeFilter.mdx │ │ │ └── imageOptimizerOptions.mdx │ │ ├── index.mdx │ │ ├── kv-store/ │ │ │ ├── KVStore/ │ │ │ │ ├── KVStore.mdx │ │ │ │ └── prototype/ │ │ │ │ ├── delete.mdx │ │ │ │ ├── get.mdx │ │ │ │ ├── list.mdx │ │ │ │ └── put.mdx │ │ │ └── KVStoreEntry/ │ │ │ └── prototype/ │ │ │ ├── arrayBuffer.mdx │ │ │ ├── body.mdx │ │ │ ├── bodyUsed.mdx │ │ │ ├── json.mdx │ │ │ ├── metadata.mdx │ │ │ ├── metadataText.mdx │ │ │ └── text.mdx │ │ ├── logger/ │ │ │ ├── Logger/ │ │ │ │ ├── Logger.mdx │ │ │ │ └── prototype/ │ │ │ │ └── log.mdx │ │ │ └── configureConsole.mdx │ │ ├── migration-guide/ │ │ │ └── index.mdx │ │ ├── secret-store/ │ │ │ ├── SecretStore/ │ │ │ │ ├── SecretStore.mdx │ │ │ │ ├── fromBytes.mdx │ │ │ │ └── prototype/ │ │ │ │ └── get.mdx │ │ │ └── SecretStoreEntry/ │ │ │ └── prototype/ │ │ │ ├── plaintext.mdx │ │ │ └── rawBytes.mdx │ │ ├── security/ │ │ │ └── inspect.mdx │ │ ├── shielding/ │ │ │ └── Shield/ │ │ │ ├── Shield.mdx │ │ │ └── prototype/ │ │ │ ├── encryptedBackend.mdx │ │ │ ├── runningOn.mdx │ │ │ └── unencryptedBackend.mdx │ │ └── websocket/ │ │ └── createWebsocketHandoff.mdx │ ├── versioned_sidebars/ │ │ ├── version-1.13.0-sidebars.json │ │ ├── version-2.5.0-sidebars.json │ │ ├── version-3.38.4-sidebars.json │ │ ├── version-3.39.0-sidebars.json │ │ ├── version-3.39.1-sidebars.json │ │ ├── version-3.39.2-sidebars.json │ │ ├── version-3.39.3-sidebars.json │ │ ├── version-3.40.0-sidebars.json │ │ ├── version-3.40.1-sidebars.json │ │ ├── version-3.41.0-sidebars.json │ │ └── version-3.41.2-sidebars.json │ └── versions.json ├── eslint.config.mjs ├── integration-tests/ │ ├── cli/ │ │ ├── build-config.test.js │ │ ├── custom-input-path.test.js │ │ ├── custom-output-path.test.js │ │ ├── engine-wasm-path-is-not-a-file.test.js │ │ ├── env.test.js │ │ ├── input-path-is-not-a-file.test.js │ │ ├── invalid.test.js │ │ ├── non-existent-engine-wasm-path.test.js │ │ ├── non-existent-input-path.test.js │ │ ├── output-path-is-not-a-file.test.js │ │ ├── valid.test.js │ │ ├── version.test.js │ │ └── weval-bin.test.js │ └── js-compute/ │ ├── build-one.sh │ ├── cleanupAll.js │ ├── compare-downstream-response.js │ ├── compare-headers.js │ ├── env.js │ ├── fixtures/ │ │ ├── app/ │ │ │ ├── .eslintrc.cjs │ │ │ ├── fastly.toml.in │ │ │ ├── message.txt │ │ │ ├── src/ │ │ │ │ ├── assertions.js │ │ │ │ ├── async-select.js │ │ │ │ ├── btoa.js │ │ │ │ ├── byob.js │ │ │ │ ├── byte-repeater.js │ │ │ │ ├── cache-core.js │ │ │ │ ├── cache-override.js │ │ │ │ ├── cache-simple.js │ │ │ │ ├── client.js │ │ │ │ ├── compute.js │ │ │ │ ├── config-store.js │ │ │ │ ├── crypto.js │ │ │ │ ├── device.js │ │ │ │ ├── dictionary.js │ │ │ │ ├── early-hints.js │ │ │ │ ├── edge-rate-limiter.js │ │ │ │ ├── env.js │ │ │ │ ├── error.js │ │ │ │ ├── fanout.js │ │ │ │ ├── fast-check.js │ │ │ │ ├── fastly-global.js │ │ │ │ ├── fetch-errors.js │ │ │ │ ├── geoip.js │ │ │ │ ├── headers.js │ │ │ │ ├── html-rewriter.js │ │ │ │ ├── image-optimizer.js │ │ │ │ ├── include-bytes.js │ │ │ │ ├── index.js │ │ │ │ ├── logger.js │ │ │ │ ├── manual-framing-headers.js │ │ │ │ ├── missing-backend.js │ │ │ │ ├── multiple-set-cookie.js │ │ │ │ ├── performance.js │ │ │ │ ├── proxy-transform-stream.js │ │ │ │ ├── random.js │ │ │ │ ├── react-byob.js │ │ │ │ ├── request-auto-decompress.js │ │ │ │ ├── request-body-async-simple.js │ │ │ │ ├── request-cache-key.js │ │ │ │ ├── request-clone.js │ │ │ │ ├── request-headers.js │ │ │ │ ├── request-method.js │ │ │ │ ├── response-json.js │ │ │ │ ├── response-redirect.js │ │ │ │ ├── response.js │ │ │ │ ├── routes.js │ │ │ │ ├── secret-store.js │ │ │ │ ├── security.js │ │ │ │ ├── server.js │ │ │ │ ├── shielding.js │ │ │ │ ├── tee.js │ │ │ │ ├── timers.js │ │ │ │ ├── urlsearchparams.js │ │ │ │ └── websocket.js │ │ │ └── tests.json │ │ ├── module-mode/ │ │ │ ├── .eslintrc.cjs │ │ │ ├── fastly.toml.in │ │ │ ├── src/ │ │ │ │ ├── acl.js │ │ │ │ ├── assertions.js │ │ │ │ ├── console.js │ │ │ │ ├── dynamic-backend.js │ │ │ │ ├── hello-world.js │ │ │ │ ├── hono.js │ │ │ │ ├── http-cache.js │ │ │ │ ├── index.js │ │ │ │ ├── kv-store.js │ │ │ │ ├── routes.js │ │ │ │ └── transform-stream.js │ │ │ └── tests.json │ │ └── reusable-sandboxes/ │ │ ├── fastly.toml.in │ │ ├── src/ │ │ │ ├── assertions.js │ │ │ ├── index.js │ │ │ ├── interleave.js │ │ │ └── routes.js │ │ └── tests.json │ ├── package.json │ ├── readme.md │ ├── replace-host.sh │ ├── setup.js │ ├── teardown.js │ ├── test.js │ └── util.js ├── package.json ├── patches/ │ └── typedoc-plugin-versions+0.2.2.patch ├── rsrc/ │ └── trace-mapping.inject.js ├── runtime/ │ ├── fastly/ │ │ ├── CMakeLists.txt │ │ ├── build-debug.sh │ │ ├── build-release-weval.sh │ │ ├── build-release.sh │ │ ├── builtins/ │ │ │ ├── acl.cpp │ │ │ ├── acl.h │ │ │ ├── backend.cpp │ │ │ ├── backend.h │ │ │ ├── body.cpp │ │ │ ├── body.h │ │ │ ├── cache-core.cpp │ │ │ ├── cache-core.h │ │ │ ├── cache-override.cpp │ │ │ ├── cache-override.h │ │ │ ├── cache-simple.cpp │ │ │ ├── cache-simple.h │ │ │ ├── config-store.cpp │ │ │ ├── config-store.h │ │ │ ├── device.cpp │ │ │ ├── device.h │ │ │ ├── dictionary.cpp │ │ │ ├── dictionary.h │ │ │ ├── edge-rate-limiter.cpp │ │ │ ├── edge-rate-limiter.h │ │ │ ├── fastly.cpp │ │ │ ├── fastly.h │ │ │ ├── fetch/ │ │ │ │ ├── fetch.cpp │ │ │ │ ├── fetch.h │ │ │ │ ├── request-response.cpp │ │ │ │ └── request-response.h │ │ │ ├── fetch-event.cpp │ │ │ ├── fetch-event.h │ │ │ ├── html-rewriter.cpp │ │ │ ├── html-rewriter.h │ │ │ ├── image-optimizer-options.inc │ │ │ ├── image-optimizer.cpp │ │ │ ├── image-optimizer.h │ │ │ ├── kv-store.cpp │ │ │ ├── kv-store.h │ │ │ ├── logger.cpp │ │ │ ├── logger.h │ │ │ ├── secret-store.cpp │ │ │ ├── secret-store.h │ │ │ ├── shielding.cpp │ │ │ └── shielding.h │ │ ├── common/ │ │ │ ├── ip_octets_to_js_string.cpp │ │ │ ├── ip_octets_to_js_string.h │ │ │ ├── normalize_http_method.cpp │ │ │ ├── normalize_http_method.h │ │ │ ├── sequence.hpp │ │ │ ├── validations.cpp │ │ │ └── validations.h │ │ ├── crates/ │ │ │ └── rust-lol-html/ │ │ │ ├── Cargo.toml │ │ │ ├── LICENSE │ │ │ ├── build.rs │ │ │ ├── include/ │ │ │ │ └── lol_html.h │ │ │ └── src/ │ │ │ ├── comment.rs │ │ │ ├── doctype.rs │ │ │ ├── document_end.rs │ │ │ ├── element.rs │ │ │ ├── errors.rs │ │ │ ├── lib.rs │ │ │ ├── rewriter.rs │ │ │ ├── rewriter_builder.rs │ │ │ ├── selector.rs │ │ │ ├── streaming.rs │ │ │ ├── string.rs │ │ │ └── text_chunk.rs │ │ ├── handler.cpp │ │ ├── host-api/ │ │ │ ├── error_numbers.msg │ │ │ ├── fastly.h │ │ │ ├── host_api.cmake │ │ │ ├── host_api.cpp │ │ │ ├── host_api_fastly.h │ │ │ └── host_call.cpp │ │ └── patches/ │ │ ├── starlingmonkey-builtin-trace-finalize.patch │ │ └── starlingmonkey-reset.patch │ └── rust-toolchain.toml ├── src/ │ ├── addSdkMetadataField.ts │ ├── cli/ │ │ └── js-compute-runtime-cli.ts │ ├── compileApplicationToWasm.ts │ ├── compiler-steps/ │ │ ├── addFastlyHelpers.ts │ │ ├── addStackMappingHelpers.ts │ │ ├── bundle.ts │ │ ├── composeSourcemaps.ts │ │ └── precompileRegexes.ts │ ├── compilerPipeline.ts │ ├── config.ts │ ├── env.ts │ ├── esbuild-plugins/ │ │ ├── fastlyPlugin.ts │ │ └── swallowTopLevelExportsPlugin.ts │ ├── files.ts │ ├── index.ts │ ├── parseInputs.ts │ ├── pipeline.ts │ ├── printHelp.ts │ └── types/ │ └── modules.d.ts ├── target/ │ └── rust-analyzer/ │ └── flycheck0/ │ ├── stderr │ └── stdout ├── test-d/ │ ├── backend.test-d.ts │ ├── cache-override.test-d.ts │ ├── compute.test-d.ts │ ├── config-store.test-d.ts │ ├── dictionary.test-d.ts │ ├── env.test-d.ts │ ├── experimental.test-d.ts │ ├── fanout.test-d.ts │ ├── geolocation.test-d.ts │ ├── globals.test-d.ts │ ├── image-optimizer.test-d.ts │ ├── kv-store.test-d.ts │ ├── logger.test-d.ts │ ├── shielding.test-d.ts │ └── websocket.test-d.ts ├── tests/ │ └── wpt-harness/ │ ├── build-wpt-runtime.sh │ ├── expectations/ │ │ ├── FileAPI/ │ │ │ ├── blob/ │ │ │ │ ├── Blob-array-buffer.any.js.json │ │ │ │ ├── Blob-bytes.any.js.json │ │ │ │ ├── Blob-constructor-dom.window.js.json │ │ │ │ ├── Blob-constructor.any.js.json │ │ │ │ ├── Blob-slice-overflow.any.js.json │ │ │ │ ├── Blob-slice.any.js.json │ │ │ │ ├── Blob-stream.any.js.json │ │ │ │ └── Blob-text.any.js.json │ │ │ └── file/ │ │ │ └── File-constructor.any.js.json │ │ ├── WebCryptoAPI/ │ │ │ ├── digest/ │ │ │ │ └── digest.https.any.js.json │ │ │ ├── getRandomValues.any.js.json │ │ │ ├── idlharness.https.any.js.json │ │ │ ├── import_export/ │ │ │ │ └── ec_importKey.https.any.js.json │ │ │ ├── randomUUID.https.any.js.json │ │ │ └── sign_verify/ │ │ │ ├── ecdsa.https.any.js.json │ │ │ └── hmac.https.any.js.json │ │ ├── compression/ │ │ │ ├── compression-bad-chunks.tentative.any.js.json │ │ │ ├── compression-constructor-error.tentative.any.js.json │ │ │ ├── compression-including-empty-chunk.tentative.any.js.json │ │ │ ├── compression-large-flush-output.any.js.json │ │ │ ├── compression-multiple-chunks.tentative.any.js.json │ │ │ ├── compression-output-length.tentative.any.js.json │ │ │ ├── compression-stream.tentative.any.js.json │ │ │ ├── compression-with-detach.tentative.window.js.json │ │ │ ├── decompression-bad-chunks.tentative.any.js.json │ │ │ ├── decompression-buffersource.tentative.any.js.json │ │ │ ├── decompression-constructor-error.tentative.any.js.json │ │ │ ├── decompression-correct-input.tentative.any.js.json │ │ │ ├── decompression-corrupt-input.tentative.any.js.json │ │ │ ├── decompression-empty-input.tentative.any.js.json │ │ │ ├── decompression-split-chunk.tentative.any.js.json │ │ │ ├── decompression-uint8array-output.tentative.any.js.json │ │ │ ├── decompression-with-detach.tentative.window.js.json │ │ │ └── idlharness.https.any.js.json │ │ ├── console/ │ │ │ ├── console-is-a-namespace.any.js.json │ │ │ ├── console-label-conversion.any.js.json │ │ │ ├── console-log-symbol.any.js.json │ │ │ ├── console-namespace-object-class-string.any.js.json │ │ │ ├── console-tests-historical.any.js.json │ │ │ └── idlharness.any.js.json │ │ ├── dom/ │ │ │ └── events/ │ │ │ ├── AddEventListenerOptions-once.any.js.json │ │ │ ├── AddEventListenerOptions-passive.any.js.json │ │ │ ├── Event-constructors.any.js.json │ │ │ ├── EventTarget-add-remove-listener.any.js.json │ │ │ ├── EventTarget-addEventListener.any.js.json │ │ │ ├── EventTarget-constructible.any.js.json │ │ │ └── EventTarget-removeEventListener.any.js.json │ │ ├── encoding/ │ │ │ ├── api-basics.any.js.json │ │ │ ├── api-invalid-label.any.js.json │ │ │ ├── api-replacement-encodings.any.js.json │ │ │ ├── api-surrogates-utf8.any.js.json │ │ │ ├── encodeInto.any.js.json │ │ │ ├── idlharness.any.js.json │ │ │ ├── iso-2022-jp-decoder.any.js.json │ │ │ ├── replacement-encodings.any.js.json │ │ │ ├── textdecoder-arguments.any.js.json │ │ │ ├── textdecoder-byte-order-marks.any.js.json │ │ │ ├── textdecoder-copy.any.js.json │ │ │ ├── textdecoder-eof.any.js.json │ │ │ ├── textdecoder-fatal-single-byte.any.js.json │ │ │ ├── textdecoder-fatal-streaming.any.js.json │ │ │ ├── textdecoder-fatal.any.js.json │ │ │ ├── textdecoder-ignorebom.any.js.json │ │ │ ├── textdecoder-labels.any.js.json │ │ │ ├── textdecoder-streaming.any.js.json │ │ │ ├── textdecoder-utf16-surrogates.any.js.json │ │ │ ├── textencoder-constructor-non-utf.any.js.json │ │ │ ├── textencoder-utf16-surrogates.any.js.json │ │ │ └── unsupported-encodings.any.js.json │ │ ├── fetch/ │ │ │ ├── api/ │ │ │ │ ├── abort/ │ │ │ │ │ ├── general.any.js.json │ │ │ │ │ └── request.any.js.json │ │ │ │ ├── basic/ │ │ │ │ │ ├── accept-header.any.js.json │ │ │ │ │ ├── conditional-get.any.js.json │ │ │ │ │ ├── header-value-combining.any.js.json │ │ │ │ │ ├── header-value-null-byte.any.js.json │ │ │ │ │ ├── historical.any.js.json │ │ │ │ │ ├── http-response-code.any.js.json │ │ │ │ │ ├── integrity.sub.any.js.json │ │ │ │ │ ├── keepalive.any.js.json │ │ │ │ │ ├── mode-same-origin.any.js.json │ │ │ │ │ ├── referrer.any.js.json │ │ │ │ │ ├── request-forbidden-headers.any.js.json │ │ │ │ │ ├── request-head.any.js.json │ │ │ │ │ ├── request-headers-case.any.js.json │ │ │ │ │ ├── request-headers-nonascii.any.js.json │ │ │ │ │ ├── request-headers.any.js.json │ │ │ │ │ ├── request-referrer.any.js.json │ │ │ │ │ ├── request-upload.any.js.json │ │ │ │ │ ├── response-null-body.any.js.json │ │ │ │ │ ├── response-url.sub.any.js.json │ │ │ │ │ ├── scheme-about.any.js.json │ │ │ │ │ ├── scheme-blob.sub.any.js.json │ │ │ │ │ ├── scheme-data.any.js.json │ │ │ │ │ ├── scheme-others.sub.any.js.json │ │ │ │ │ ├── status.h2.any.js.json │ │ │ │ │ ├── stream-response.any.js.json │ │ │ │ │ ├── stream-safe-creation.any.js.json │ │ │ │ │ └── text-utf8.any.js.json │ │ │ │ ├── body/ │ │ │ │ │ ├── cloned-any.js.json │ │ │ │ │ └── formdata.any.js.json │ │ │ │ ├── headers/ │ │ │ │ │ ├── header-setcookie.any.js.json │ │ │ │ │ ├── header-values-normalize.any.js.json │ │ │ │ │ ├── header-values.any.js.json │ │ │ │ │ ├── headers-basic.any.js.json │ │ │ │ │ ├── headers-casing.any.js.json │ │ │ │ │ ├── headers-combine.any.js.json │ │ │ │ │ ├── headers-errors.any.js.json │ │ │ │ │ ├── headers-no-cors.any.js.json │ │ │ │ │ ├── headers-normalize.any.js.json │ │ │ │ │ ├── headers-record.any.js.json │ │ │ │ │ └── headers-structure.any.js.json │ │ │ │ ├── redirect/ │ │ │ │ │ ├── redirect-back-to-original-origin.any.js.json │ │ │ │ │ ├── redirect-count.any.js.json │ │ │ │ │ ├── redirect-empty-location.any.js.json │ │ │ │ │ ├── redirect-keepalive.any.js.json │ │ │ │ │ ├── redirect-keepalive.https.any.js.json │ │ │ │ │ ├── redirect-location-escape.tentative.any.js.json │ │ │ │ │ ├── redirect-location.any.js.json │ │ │ │ │ ├── redirect-method.any.js.json │ │ │ │ │ ├── redirect-mode.any.js.json │ │ │ │ │ ├── redirect-origin.any.js.json │ │ │ │ │ ├── redirect-referrer-override.any.js.json │ │ │ │ │ ├── redirect-referrer.any.js.json │ │ │ │ │ ├── redirect-schemes.any.js.json │ │ │ │ │ ├── redirect-to-dataurl.any.js.json │ │ │ │ │ └── redirect-upload.h2.any.js.json │ │ │ │ ├── request/ │ │ │ │ │ ├── forbidden-method.any.js.json │ │ │ │ │ ├── request-bad-port.any.js.json │ │ │ │ │ ├── request-cache-default-conditional.any.js.json │ │ │ │ │ ├── request-cache-default.any.js.json │ │ │ │ │ ├── request-cache-force-cache.any.js.json │ │ │ │ │ ├── request-cache-no-cache.any.js.json │ │ │ │ │ ├── request-cache-no-store.any.js.json │ │ │ │ │ ├── request-cache-only-if-cached.any.js.json │ │ │ │ │ ├── request-cache-reload.any.js.json │ │ │ │ │ ├── request-constructor-init-body-override.any.js.json │ │ │ │ │ ├── request-consume-empty.any.js.json │ │ │ │ │ ├── request-consume.any.js.json │ │ │ │ │ ├── request-disturbed.any.js.json │ │ │ │ │ ├── request-error.any.js.json │ │ │ │ │ ├── request-headers.any.js.json │ │ │ │ │ ├── request-init-002.any.js.json │ │ │ │ │ ├── request-init-contenttype.any.js.json │ │ │ │ │ ├── request-init-priority.any.js.json │ │ │ │ │ ├── request-init-stream.any.js.json │ │ │ │ │ ├── request-keepalive.any.js.json │ │ │ │ │ └── request-structure.any.js.json │ │ │ │ └── response/ │ │ │ │ ├── json.any.js.json │ │ │ │ ├── response-blob-realm.any.js.json │ │ │ │ ├── response-cancel-stream.any.js.json │ │ │ │ ├── response-consume-empty.any.js.json │ │ │ │ ├── response-consume-stream.any.js.json │ │ │ │ ├── response-error-from-stream.any.js.json │ │ │ │ ├── response-error.any.js.json │ │ │ │ ├── response-from-stream.any.js.json │ │ │ │ ├── response-headers-guard.any.js.json │ │ │ │ ├── response-init-001.any.js.json │ │ │ │ ├── response-init-002.any.js.json │ │ │ │ ├── response-init-contenttype.any.js.json │ │ │ │ ├── response-static-error.any.js.json │ │ │ │ ├── response-static-json.any.js.json │ │ │ │ ├── response-static-redirect.any.js.json │ │ │ │ ├── response-stream-bad-chunk.any.js.json │ │ │ │ ├── response-stream-disturbed-1.any.js.json │ │ │ │ ├── response-stream-disturbed-2.any.js.json │ │ │ │ ├── response-stream-disturbed-3.any.js.json │ │ │ │ ├── response-stream-disturbed-4.any.js.json │ │ │ │ ├── response-stream-disturbed-5.any.js.json │ │ │ │ ├── response-stream-disturbed-6.any.js.json │ │ │ │ ├── response-stream-disturbed-by-pipe.any.js.json │ │ │ │ └── response-stream-with-broken-then.any.js.json │ │ │ ├── content-type/ │ │ │ │ ├── multipart-malformed.any.js.json │ │ │ │ └── multipart.window.js.json │ │ │ └── data-urls/ │ │ │ ├── base64.any.js.json │ │ │ └── processing.any.js.json │ │ ├── hr-time/ │ │ │ ├── basic.any.js.json │ │ │ ├── idlharness.any.js.json │ │ │ └── monotonic-clock.any.js.json │ │ ├── html/ │ │ │ └── webappapis/ │ │ │ ├── atob/ │ │ │ │ └── base64.any.js.json │ │ │ ├── structured-clone/ │ │ │ │ └── structured-clone.any.js.json │ │ │ └── timers/ │ │ │ ├── clearinterval-from-callback.any.js.json │ │ │ ├── cleartimeout-clearinterval.any.js.json │ │ │ ├── missing-timeout-setinterval.any.js.json │ │ │ ├── negative-setinterval.any.js.json │ │ │ ├── negative-settimeout.any.js.json │ │ │ ├── type-long-setinterval.any.js.json │ │ │ └── type-long-settimeout.any.js.json │ │ ├── streams/ │ │ │ ├── idlharness.any.js.json │ │ │ ├── piping/ │ │ │ │ ├── close-propagation-backward.any.js.json │ │ │ │ ├── close-propagation-forward.any.js.json │ │ │ │ ├── error-propagation-backward.any.js.json │ │ │ │ ├── error-propagation-forward.any.js.json │ │ │ │ ├── flow-control.any.js.json │ │ │ │ ├── general-addition.any.js.json │ │ │ │ ├── general.any.js.json │ │ │ │ ├── multiple-propagation.any.js.json │ │ │ │ ├── then-interception.any.js.json │ │ │ │ ├── throwing-options.any.js.json │ │ │ │ └── transform-streams.any.js.json │ │ │ ├── queuing-strategies.any.js.json │ │ │ ├── readable-byte-streams/ │ │ │ │ ├── bad-buffers-and-views.any.js.json │ │ │ │ ├── construct-byob-request.any.js.json │ │ │ │ ├── enqueue-with-detached-buffer.any.js.json │ │ │ │ ├── general.any.js.json │ │ │ │ ├── non-transferable-buffers.any.js.json │ │ │ │ ├── read-min.any.js.json │ │ │ │ ├── respond-after-enqueue.any.js.json │ │ │ │ └── tee.any.js.json │ │ │ ├── readable-streams/ │ │ │ │ ├── async-iterator.any.js.json │ │ │ │ ├── bad-strategies.any.js.json │ │ │ │ ├── bad-underlying-sources.any.js.json │ │ │ │ ├── cancel.any.js.json │ │ │ │ ├── constructor.any.js.json │ │ │ │ ├── count-queuing-strategy-integration.any.js.json │ │ │ │ ├── default-reader.any.js.json │ │ │ │ ├── floating-point-total-queue-size.any.js.json │ │ │ │ ├── from.any.js.json │ │ │ │ ├── garbage-collection.any.js.json │ │ │ │ ├── general.any.js.json │ │ │ │ ├── owning-type-message-port.any.js.json │ │ │ │ ├── owning-type-video-frame.any.js.json │ │ │ │ ├── owning-type.any.js.json │ │ │ │ ├── patched-global.any.js.json │ │ │ │ ├── reentrant-strategies.any.js.json │ │ │ │ ├── tee.any.js.json │ │ │ │ └── templated.any.js.json │ │ │ ├── transform-streams/ │ │ │ │ ├── backpressure.any.js.json │ │ │ │ ├── cancel.any.js.json │ │ │ │ ├── errors.any.js.json │ │ │ │ ├── flush.any.js.json │ │ │ │ ├── general.any.js.json │ │ │ │ ├── lipfuzz.any.js.json │ │ │ │ ├── patched-global.any.js.json │ │ │ │ ├── properties.any.js.json │ │ │ │ ├── reentrant-strategies.any.js.json │ │ │ │ ├── strategies.any.js.json │ │ │ │ └── terminate.any.js.json │ │ │ └── writable-streams/ │ │ │ ├── aborting.any.js.json │ │ │ ├── bad-strategies.any.js.json │ │ │ ├── bad-underlying-sinks.any.js.json │ │ │ ├── byte-length-queuing-strategy.any.js.json │ │ │ ├── close.any.js.json │ │ │ ├── constructor.any.js.json │ │ │ ├── count-queuing-strategy.any.js.json │ │ │ ├── error.any.js.json │ │ │ ├── floating-point-total-queue-size.any.js.json │ │ │ ├── general.any.js.json │ │ │ ├── properties.any.js.json │ │ │ ├── reentrant-strategy.any.js.json │ │ │ ├── start.any.js.json │ │ │ └── write.any.js.json │ │ ├── url/ │ │ │ ├── historical.any.js.json │ │ │ ├── url-constructor.any.js.json │ │ │ ├── url-origin.any.js.json │ │ │ ├── url-searchparams.any.js.json │ │ │ ├── url-setters-stripping.any.js.json │ │ │ ├── url-setters.any.js.json │ │ │ ├── url-statics-canparse.any.js.json │ │ │ ├── url-statics-parse.any.js.json │ │ │ ├── url-tojson.any.js.json │ │ │ ├── urlencoded-parser.any.js.json │ │ │ ├── urlsearchparams-append.any.js.json │ │ │ ├── urlsearchparams-constructor.any.js.json │ │ │ ├── urlsearchparams-delete.any.js.json │ │ │ ├── urlsearchparams-foreach.any.js.json │ │ │ ├── urlsearchparams-get.any.js.json │ │ │ ├── urlsearchparams-getall.any.js.json │ │ │ ├── urlsearchparams-has.any.js.json │ │ │ ├── urlsearchparams-set.any.js.json │ │ │ ├── urlsearchparams-size.any.js.json │ │ │ ├── urlsearchparams-sort.any.js.json │ │ │ └── urlsearchparams-stringifier.any.js.json │ │ ├── webidl/ │ │ │ └── ecmascript-binding/ │ │ │ └── es-exceptions/ │ │ │ ├── DOMException-constants.any.js.json │ │ │ ├── DOMException-constructor-and-prototype.any.js.json │ │ │ ├── DOMException-constructor-behavior.any.js.json │ │ │ └── DOMException-custom-bindings.any.js.json │ │ └── xhr/ │ │ └── formdata/ │ │ ├── append.any.js.json │ │ ├── constructor.any.js.json │ │ ├── delete.any.js.json │ │ ├── foreach.any.js.json │ │ ├── get.any.js.json │ │ ├── has.any.js.json │ │ ├── iteration.any.js.json │ │ ├── set-blob.any.js.json │ │ └── set.any.js.json │ ├── post-harness.js │ ├── pre-harness.js │ ├── results-page.template.html │ ├── results-section-error.template.html │ ├── results-section.template.html │ ├── run-wpt.mjs │ ├── run-wpt.sh │ ├── tests.json │ └── viceroy.toml ├── tsconfig.json ├── typedoc.json └── types/ ├── acl.d.ts ├── backend.d.ts ├── body.d.ts ├── cache-override.d.ts ├── cache.d.ts ├── compute.d.ts ├── config-store.d.ts ├── device.d.ts ├── dictionary.d.ts ├── edge-rate-limiter.d.ts ├── env.d.ts ├── experimental.d.ts ├── fanout.d.ts ├── geolocation.d.ts ├── globals.d.ts ├── html-rewriter.d.ts ├── image-optimizer.d.ts ├── index.d.ts ├── index.js ├── kv-store.d.ts ├── logger.d.ts ├── secret-store.d.ts ├── security.d.ts ├── shielding.d.ts └── websocket.d.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .clang-format ================================================ --- Language: Cpp # BasedOnStyle: LLVM AccessModifierOffset: -2 AlignAfterOpenBracket: Align AlignConsecutiveMacros: false AlignConsecutiveAssignments: false AlignConsecutiveBitFields: false AlignConsecutiveDeclarations: false AlignEscapedNewlines: Right AlignOperands: Align AlignTrailingComments: true AllowAllArgumentsOnNextLine: true AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortEnumsOnASingleLine: true AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: All AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: Never AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: MultiLine BinPackArguments: true BinPackParameters: true BraceWrapping: AfterCaseLabel: false AfterClass: false AfterControlStatement: Never AfterEnum: false AfterFunction: false AfterNamespace: false AfterObjCDeclaration: false AfterStruct: false AfterUnion: false AfterExternBlock: false BeforeCatch: false BeforeElse: false BeforeLambdaBody: false BeforeWhile: false IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true BreakBeforeBinaryOperators: None BreakBeforeBraces: Attach BreakBeforeInheritanceComma: false BreakInheritanceList: BeforeColon BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeColon BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true ColumnLimit: 100 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DeriveLineEnding: true DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH IncludeBlocks: Preserve IncludeCategories: - Regex: '^"(llvm|llvm-c|clang|clang-c)/' Priority: 2 SortPriority: 0 - Regex: '^(<|"(gtest|gmock|isl|json)/)' Priority: 3 SortPriority: 0 - Regex: '.*' Priority: 1 SortPriority: 0 IncludeIsMainRegex: '(Test)?$' IncludeIsMainSourceRegex: '' IndentCaseLabels: false IndentCaseBlocks: false IndentGotoLabels: true IndentPPDirectives: None IndentExternBlock: AfterExternBlock IndentWidth: 2 IndentWrappedFunctionNames: false InsertTrailingCommas: None JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: true MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Auto ObjCBlockIndentWidth: 2 ObjCBreakBeforeNestedBlockParam: true ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Right ReflowComments: true SortIncludes: true SortUsingDeclarations: true SpaceAfterCStyleCast: false SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: true SpaceBeforeAssignmentOperators: true SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements SpaceBeforeRangeBasedForLoopColon: true SpaceInEmptyBlock: false SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInConditionalStatement: false SpacesInContainerLiterals: true SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false SpaceBeforeSquareBrackets: false Standard: Latest StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION TabWidth: 8 UseCRLF: false UseTab: Never WhitespaceSensitiveMacros: - STRINGIZE - PP_STRINGIZE - BOOST_PP_STRINGIZE ... ================================================ FILE: .github/dependabot.yml ================================================ # To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "cargo" directory: "/" schedule: interval: "daily" groups: cargo: patterns: - "*" open-pull-requests-limit: 1 - package-ecosystem: "npm" directory: "/integration-tests/js-compute" schedule: interval: "daily" groups: npm: patterns: - "*" open-pull-requests-limit: 1 ================================================ FILE: .github/workflows/cleanup.yml ================================================ name: 'Cleanup' on: workflow_dispatch permissions: contents: read env: fastly-cli_version: 14.2.0 jobs: cleanup: name: Cleanup runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v3 with: node-version: 'lts/*' - run: cd ./integration-tests/js-compute && npm install - name: Set up Fastly CLI uses: fastly/compute-actions/setup@v4 with: token: ${{ secrets.GITHUB_TOKEN }} cli_version: ${{ env.fastly-cli_version }} - run: node integration-tests/js-compute/cleanupAll.js env: FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }} ================================================ FILE: .github/workflows/dependencies.yml ================================================ name: 'Dependency Review' on: [pull_request] permissions: contents: read jobs: dependency-review: name: Dependency Review runs-on: ubuntu-latest steps: - uses: actions/dependency-review-action@v2.2.0 with: allow-licenses: Apache-2.0, MIT, BSD-3-Clause, ISC, BSD-2-Clause, MIT OR (CC0-1.0 AND MIT), CC0-1.0 OR MIT OR (CC0-1.0 AND MIT), CC-BY-3.0, CC0-1.0, MIT OR Apache-2.0, MIT AND Apache-2.0, MIT OR WTFPL, BSD-2-Clause OR (MIT OR Apache-2.0), Python-2.0, ISC AND MIT, Apache-2.0 AND MIT, MIT/Apache-2.0, Apache-2.0 OR MIT, (Apache-2.0 OR MIT) AND BSD-3-Clause, Zlib OR Apache-2.0 OR MIT, MIT OR Apache-2.0 OR Zlib, MIT OR (Apache-2.0 OR Zlib), (Apache-2.0 WITH LLVM-exception), 0BSD, CC-BY-4.0, Unlicense, MPL-1.1, LicenseRef-scancode-unicode AND MIT, Unlicense OR MIT fail-on-scopes: runtime ================================================ FILE: .github/workflows/main.yml ================================================ name: CI concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true on: pull_request: push: branches: [main] defaults: run: shell: bash env: # Note: when updated, also update version in ensure-cargo-installs viceroy_version: 0.16.5 # Note: when updated, also update version in ensure-cargo-installs ! AND ! release-please.yml wasm-tools_version: 1.216.0 fastly-cli_version: 14.2.0 jobs: check-changelog: if: github.ref != 'refs/heads/main' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v3 with: node-version: 'lts/*' - run: npm ci - run: npm run format-changelog check-docusaurus: if: github.ref != 'refs/heads/main' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v3 with: node-version: 'lts/*' - run: cd documentation && npm run add-fastly-prefix - run: cd documentation && npm ci - run: cd documentation && npm run build ensure-cargo-installs: name: Ensure that all required "cargo install" commands are run, or we have a cache hit strategy: matrix: include: - crate: viceroy version: 0.16.5 # Note: workflow-level env vars can't be used in matrix definitions options: "" - crate: wasm-tools version: 1.216.0 # Note: workflow-level env vars can't be used in matrix definitions options: "" runs-on: ubuntu-latest steps: - name: Cache ${{ matrix.crate }} ${{ matrix.version }} id: cache-crate uses: actions/cache@v3 with: path: "/home/runner/.cargo/bin/${{ matrix.crate }}" key: crate-cache-${{ matrix.crate }}-${{ matrix.version }} - name: Install ${{ matrix.crate }} ${{ matrix.version }} if: steps.cache-crate.outputs.cache-hit != 'true' run: cargo install ${{ matrix.crate }} ${{ matrix.options }} --version ${{ matrix.version }} --force shellcheck: env: SHELLCHECK_VERSION: v0.8.0 runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/cache@v3 id: cache-shellcheck with: path: ${{ runner.tool_cache }}/shellcheck key: shellcheck-${{ runner.os }}-${{ env.SHELLCHECK_VERSION }} - name: Download shellcheck if: steps.cache-shellcheck.output.cache-hit != 'true' run: | version="${{ env.SHELLCHECK_VERSION }}" baseurl="https://github.com/koalaman/shellcheck/releases/download" curl -Lso "shellcheck.tar.xz" \ "${baseurl}/${version}/shellcheck-${version}.linux.x86_64.tar.xz" mkdir -p "${{ runner.tool_cache }}/shellcheck/bin" tar -xf shellcheck.tar.xz -C "${{ runner.tool_cache }}/shellcheck/bin" - name: Add shellcheck to path run: echo "${{ runner.tool_cache }}/shellcheck/bin" >> $GITHUB_PATH - name: Run shellcheck run: ci/shellcheck.sh format: if: github.ref != 'refs/heads/main' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: "Install wasi-sdk-20 (linux)" run: | set -x curl -sS -L -O https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-20/wasi-sdk-20.0-linux.tar.gz tar xf wasi-sdk-20.0-linux.tar.gz sudo mkdir -p /opt/wasi-sdk sudo mv wasi-sdk-20.0/* /opt/wasi-sdk/ ls /opt/wasi-sdk/ - run: | /opt/wasi-sdk/bin/clang-format --version ci/clang-format.sh - run: | ci/rustfmt.sh - run: npm install - run: npm run format:check test-npm-package: if: github.ref != 'refs/heads/main' needs: [build] strategy: matrix: node-version: [18, 22] os: [ ubuntu-latest, windows-latest, macos-latest ] exclude: - os: macos-latest node-version: 18 - os: windows-latest node-version: 18 runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v3 with: node-version: ${{ matrix.node-version }} - name: Download Engine uses: actions/download-artifact@v4 with: name: fastly-release - name: Download Engine uses: actions/download-artifact@v4 with: name: fastly-debug - name: Download Engine uses: actions/download-artifact@v4 with: name: fastly-weval - name: Download Engine Weval Cache uses: actions/download-artifact@v4 with: name: fastly-weval-ic-cache - run: npm install - name: Build CLI run: npm run build:cli - run: npm test build-debug: name: Debug Build needs: [ensure-cargo-installs] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - name: Set up Node LTS uses: actions/setup-node@v3 with: node-version: 'lts/*' - run: npm ci - name: Install Rust 1.81.0 run: | rustup toolchain install 1.81.0 rustup target add wasm32-wasip1 --toolchain 1.81.0 - name: Restore wasm-tools from cache uses: actions/cache@v3 id: wasm-tools with: path: "/home/runner/.cargo/bin/wasm-tools" key: crate-cache-wasm-tools-${{ env.wasm-tools_version }} - name: Build CLI run: npm run build:cli - name: Build with full debug info run: npm run build:debug:info - uses: actions/upload-artifact@v4 with: if-no-files-found: error name: fastly-debug path: fastly.debug.wasm build: name: Build needs: [ensure-cargo-installs] runs-on: ubuntu-latest strategy: matrix: profile: [release, weval] steps: - uses: actions/checkout@v4 with: submodules: true - name: Set up Node LTS uses: actions/setup-node@v3 with: node-version: 'lts/*' - run: npm ci - name: Install Rust 1.81.0 run: | rustup toolchain install 1.81.0 rustup target add wasm32-wasip1 --toolchain 1.81.0 - name: Restore wasm-tools from cache uses: actions/cache@v3 id: wasm-tools with: path: "/home/runner/.cargo/bin/wasm-tools" key: crate-cache-wasm-tools-${{ env.wasm-tools_version }} - name: Build CLI run: npm run build:cli - name: Build if: matrix.profile == 'release' run: npm run build:release - name: Build if: matrix.profile == 'weval' run: npm run build:weval - uses: actions/upload-artifact@v4 with: if-no-files-found: error name: fastly-${{ matrix.profile }} path: fastly${{ matrix.profile == 'debug' && '.debug.wasm' || (matrix.profile == 'weval' && '-weval.wasm' || '.wasm') }} - uses: actions/upload-artifact@v4 if: matrix.profile == 'weval' with: name: fastly-${{ matrix.profile }}-ic-cache path: fastly-ics.wevalcache run-wpt-debug: if: github.ref != 'refs/heads/main' name: Run Web Platform Tests Debug needs: [build-debug, ensure-cargo-installs] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - name: Set up Node LTS uses: actions/setup-node@v3 with: node-version: 'lts/*' - run: npm ci - name: Download Engine uses: actions/download-artifact@v4 with: name: fastly-debug - name: Restore Viceroy from cache uses: actions/cache@v3 with: path: "/home/runner/.cargo/bin/viceroy" key: crate-cache-viceroy-${{ env.viceroy_version }} - name: Restore wasm-tools from cache uses: actions/cache@v3 id: wasm-tools with: path: "/home/runner/.cargo/bin/wasm-tools" key: crate-cache-wasm-tools-${{ env.wasm-tools_version }} - name: Build CLI run: npm run build:cli - name: Build WPT runtime run: tests/wpt-harness/build-wpt-runtime.sh --debug-build - name: Prepare WPT hosts run: | cd tests/wpt-harness/wpt ./wpt make-hosts-file | sudo tee -a /etc/hosts - name: Run tests timeout-minutes: 20 run: node ./tests/wpt-harness/run-wpt.mjs -vv run-wpt: strategy: matrix: profile: [release, weval] if: github.ref != 'refs/heads/main' name: Run Web Platform Tests needs: [build, ensure-cargo-installs] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - name: Set up Node LTS uses: actions/setup-node@v3 with: node-version: 'lts/*' - run: npm ci - name: Download Engine uses: actions/download-artifact@v4 with: name: fastly-${{ matrix.profile }} - name: Download Engine Weval Cache if: matrix.profile == 'weval' uses: actions/download-artifact@v4 with: name: fastly-weval-ic-cache - name: Restore Viceroy from cache uses: actions/cache@v3 with: path: "/home/runner/.cargo/bin/viceroy" key: crate-cache-viceroy-${{ env.viceroy_version }} - name: Restore wasm-tools from cache uses: actions/cache@v3 id: wasm-tools with: path: "/home/runner/.cargo/bin/wasm-tools" key: crate-cache-wasm-tools-${{ env.wasm-tools_version }} - name: Build CLI run: npm run build:cli - name: Build WPT runtime run: tests/wpt-harness/build-wpt-runtime.sh ${{matrix.profile == 'weval' && '--enable-experimental-aot' || matrix.profile == 'debug' && '--debug-build' || ''}} - name: Prepare WPT hosts run: | cd tests/wpt-harness/wpt ./wpt make-hosts-file | sudo tee -a /etc/hosts - name: Run tests timeout-minutes: 20 run: node ./tests/wpt-harness/run-wpt.mjs -vv sdktest: concurrency: group: ${{ github.head_ref }}--sdktest-${{matrix.profile}}-${{matrix.platform}} if: github.ref != 'refs/heads/main' runs-on: ubuntu-latest strategy: fail-fast: false matrix: platform: [viceroy, compute] profile: [release, weval] features: [none, http-cache] exclude: - platform: viceroy features: http-cache needs: [build, ensure-cargo-installs] steps: - name: Checkout fastly/js-compute-runtime uses: actions/checkout@v6 with: submodules: false - uses: actions/setup-node@v3 with: node-version: 'lts/*' - name: Set up Fastly CLI uses: fastly/compute-actions/setup@v4 with: token: ${{ secrets.GITHUB_TOKEN }} cli_version: ${{ env.fastly-cli_version }} - name: Restore Viceroy from cache if: matrix.platform == 'viceroy' uses: actions/cache@v3 id: viceroy with: path: "/home/runner/.cargo/bin/viceroy" key: crate-cache-viceroy-${{ env.viceroy_version }} - name: Restore wasm-tools from cache uses: actions/cache@v3 id: wasm-tools with: path: "/home/runner/.cargo/bin/wasm-tools" key: crate-cache-wasm-tools-${{ env.wasm-tools_version }} - name: Download Engine uses: actions/download-artifact@v4 with: name: fastly-${{ matrix.profile }} - name: Download Engine (AOT weval cache) uses: actions/download-artifact@v4 if: matrix.profile == 'weval' with: name: fastly-${{ matrix.profile }}-ic-cache - name: Npm install run: npm install && cd ./integration-tests/js-compute && npm install - name: Build CLI run: npm run build:cli - name: Run Tests run: SUFFIX_STRING=${{matrix.profile}}-${{ github.run_id }}-${{ github.run_attempt }} node integration-tests/js-compute/test.js --ci --skip-teardown${{ matrix.platform == 'viceroy' && ' --local' || '' }}${{ matrix.profile == 'weval' && ' --aot' || '' }}${{ matrix.features == 'http-cache' && ' --http-cache' || '' }} env: FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }} - name: Run Module Mode Tests run: SUFFIX_STRING=${{matrix.profile}}-${{ github.run_id }}-${{ github.run_attempt }} node integration-tests/js-compute/test.js --ci --fixture=module-mode${{ matrix.platform == 'viceroy' && ' --local' || '' }}${{ matrix.profile == 'weval' && ' --aot' || '' }}${{ matrix.features == 'http-cache' && ' --http-cache' || '' }} env: FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }} - name: Run Reusable Sandbox Tests if: matrix.platform == 'viceroy' run: SUFFIX_STRING=${{matrix.profile}}-${{ github.run_id }}-${{ github.run_attempt }} node integration-tests/js-compute/test.js --ci --serial --fixture=reusable-sandboxes --local${{ matrix.profile == 'weval' && ' --aot' || '' }}${{ matrix.features == 'http-cache' && ' --http-cache' || '' }} env: FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }} sdktest-debug: concurrency: group: ${{ github.head_ref }}--sdktest-debug-${{matrix.platform}} if: github.ref != 'refs/heads/main' runs-on: ubuntu-latest strategy: fail-fast: false matrix: platform: [viceroy, compute] features: [none, http-cache] exclude: - platform: viceroy features: http-cache needs: [build-debug, ensure-cargo-installs] steps: - name: Checkout fastly/js-compute-runtime uses: actions/checkout@v4 with: submodules: false - uses: actions/setup-node@v3 with: node-version: 'lts/*' - name: Set up Fastly CLI uses: fastly/compute-actions/setup@v4 with: token: ${{ secrets.GITHUB_TOKEN }} cli_version: ${{ env.fastly-cli_version }} - name: Restore Viceroy from cache if: matrix.platform == 'viceroy' uses: actions/cache@v3 id: viceroy with: path: "/home/runner/.cargo/bin/viceroy" key: crate-cache-viceroy-${{ env.viceroy_version }} - name: Restore wasm-tools from cache uses: actions/cache@v3 id: wasm-tools with: path: "/home/runner/.cargo/bin/wasm-tools" key: crate-cache-wasm-tools-${{ env.wasm-tools_version }} - name: Download Engine uses: actions/download-artifact@v4 with: name: fastly-debug - name: Strip debug sections (compute only) if: matrix.platform == 'compute' run: wasm-tools strip fastly.debug.wasm -d ".debug_(info|loc|ranges|abbrev|line|str)" -o fastly.debug.wasm - name: Npm install run: npm install && cd ./integration-tests/js-compute && npm install - name: Build CLI run: npm run build:cli - name: Run Tests run: SUFFIX_STRING=debug-${{ github.run_id }}-${{ github.run_attempt }} node integration-tests/js-compute/test.js --ci --skip-teardown --debug-build${{ matrix.platform == 'viceroy' && ' --local' || '' }}${{ matrix.features == 'http-cache' && ' --http-cache' || '' }} env: FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }} - name: Run Module Mode Tests run: SUFFIX_STRING=debug-${{ github.run_id }}-${{ github.run_attempt }} node integration-tests/js-compute/test.js --ci --fixture=module-mode --debug-build${{ matrix.platform == 'viceroy' && ' --local' || '' }}${{ matrix.features == 'http-cache' && ' --http-cache' || '' }} env: FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }} - name: Run Reusable Sandbox Tests if: matrix.platform == 'viceroy' run: SUFFIX_STRING=debug-${{ github.run_id }}-${{ github.run_attempt }} node integration-tests/js-compute/test.js --ci --serial --fixture=reusable-sandboxes --debug-build${{ matrix.platform == 'viceroy' && ' --local' || '' }}${{ matrix.features == 'http-cache' && ' --http-cache' || '' }} env: FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }} ================================================ FILE: .github/workflows/release-please.yml ================================================ on: push: branches: - main permissions: id-token: write contents: write issues: write pull-requests: write packages: write env: wasm-tools_version: 1.216.0 name: release-please jobs: release: runs-on: ubuntu-latest outputs: releases_created: ${{ steps.release.outputs.releases_created }} pr: ${{ steps.release.outputs.pr }} steps: - uses: google-github-actions/release-please-action@v3 id: release with: release-type: node package-name: "@fastly/js-compute" changelog-path: "CHANGELOG.md" bump-minor-pre-major: true bump-patch-for-minor-pre-major: true draft: false prerelease: false token: ${{ secrets.GITHUB_TOKEN }} update-lock-and-docs: runs-on: ubuntu-latest needs: release if: ${{ needs.release.outputs.pr && !needs.release.outputs.releases_created }} steps: - name: Checkout uses: actions/checkout@v3 with: submodules: true ref: release-please--branches--main--components--js-compute fetch-depth: 2 token: ${{ secrets.GITHUB_TOKEN }} - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: 'lts/*' - name: Cache Compute File Server CLI id: cache-compute-file-server-cli uses: actions/cache@v3 with: path: "/home/runner/.cargo/bin/compute-file-server-cli" key: crate-cache-compute-file-server-cli - name: Install Compute File Server CLI if: steps.cache-compute-file-server-cli.outputs.cache-hit != 'true' run: cd compute-file-server-cli && cargo install --path . - run: npm update working-directory: ./documentation - run: npm run add-fastly-prefix working-directory: ./documentation - run: npm run docusaurus docs:version "$(npm pkg get version --json --prefix=../ | jq -r)" working-directory: ./documentation - run: npm update working-directory: ./documentation/app - run: npm run build:files working-directory: ./documentation/app - run: npm install && npm run format-changelog - run: npm run remove-fastly-prefix working-directory: ./documentation - name: Committing and push changes run: | git config user.name "${GITHUB_ACTOR}" git config user.email "${GITHUB_ACTOR}@users.noreply.github.com" git add . git commit -m "chore: add docs for $(npm pkg get version --json | jq -r)" git push --force build: name: Build runs-on: ubuntu-latest needs: release if: ${{ needs.release.outputs.releases_created }} strategy: matrix: profile: [debug, release, weval] steps: - uses: actions/checkout@v3 with: submodules: true - name: Set up Node LTS uses: actions/setup-node@v3 with: node-version: 'lts/*' - run: npm ci - name: Install Rust 1.81.0 run: | rustup toolchain install 1.81.0 rustup target add wasm32-wasip1 --toolchain 1.81.0 - name: Restore wasm-tools from cache uses: actions/cache@v3 id: wasm-tools with: path: "/home/runner/.cargo/bin/wasm-tools" key: crate-cache-wasm-tools-${{ env.wasm-tools_version }} - name: Build CLI run: npm run build:cli - name: Build if: ${{ matrix.profile == 'release' }} run: npm run build:release - name: Build if: ${{ matrix.profile == 'debug' }} run: npm run build:debug - name: Build if: ${{ matrix.profile == 'weval' }} run: npm run build:weval - uses: actions/upload-artifact@v4 with: if-no-files-found: error name: fastly-${{ matrix.profile }} path: fastly${{ matrix.profile == 'debug' && '.debug.wasm' || (matrix.profile == 'weval' && '-weval.wasm' || '.wasm') }} - uses: actions/upload-artifact@v4 if: ${{ matrix.profile == 'weval' }} with: name: fastly-${{ matrix.profile }}-ic-cache path: fastly-ics.wevalcache publish: runs-on: ubuntu-latest needs: [release, build] if: ${{ needs.release.outputs.releases_created }} steps: - uses: actions/checkout@v3 with: submodules: true - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: 'lts/*' registry-url: 'https://registry.npmjs.org' - name: Restore wasm-tools from cache uses: actions/cache@v3 id: wasm-tools with: path: "/home/runner/.cargo/bin/wasm-tools" key: crate-cache-wasm-tools-${{ env.wasm-tools_version }} - name: Cache Compute File Server CLI id: cache-compute-file-server-cli uses: actions/cache@v3 with: path: "/home/runner/.cargo/bin/compute-file-server-cli" key: crate-cache-compute-file-server-cli - name: Install Compute File Server CLI if: steps.cache-compute-file-server-cli.outputs.cache-hit != 'true' run: cd compute-file-server-cli && cargo install --path . - run: npm install --immutable - name: Download Engine Release uses: actions/download-artifact@v4 with: name: fastly-release - name: Download Engine Debug uses: actions/download-artifact@v4 with: name: fastly-debug - name: Download Engine Weval uses: actions/download-artifact@v4 with: name: fastly-weval - name: Download Engine Weval Cache uses: actions/download-artifact@v4 with: name: fastly-weval-ic-cache - name: Build CLI run: npm run build:cli - name: npmjs publish run: npm publish - name: github package registry publish run: | cat << EOF > .npmrc //npm.pkg.github.com/:_authToken=${GITHUB_TOKEN} @fastly:registry=https://npm.pkg.github.com registry=https://registry.npmjs.org/ always-auth=true EOF npm publish rm .npmrc env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: npm run add-fastly-prefix working-directory: ./documentation - run: npm ci working-directory: ./documentation - name: Set up Fastly CLI uses: fastly/compute-actions/setup@v2 with: token: ${{ secrets.GITHUB_TOKEN }} cli_version: '14.2.0' - run: npm run deploy timeout-minutes: 120 env: FASTLY_API_TOKEN: ${{secrets.FASTLY_API_TOKEN}} working-directory: ./documentation ================================================ FILE: .gitignore ================================================ # TypeScript build output dist/ # Integration Tests build output /integration-tests/**/fixtures/**/*.tar.gz /integration-tests/**/fixtures/**/fastly.toml /integration-tests/**/fixtures/**/*.wasm /integration-tests/**/fixtures/**/*.js.map /runtime/fastly/build-*/ node_modules/ .DS_Store # compiler_flags /fastly-weval.wasm /fastly.debug.wasm /fastly.wasm /fastly-ics.wevalcache tests/wpt-harness/wpt-test-runner.js wpt-runtime.wasm docs-app/bin/main.wasm docs-app/pkg/*.tar.gz yarn-error.log .vscode ================================================ FILE: .gitmodules ================================================ [submodule "tests/wpt-harness/wpt"] path = tests/wpt-harness/wpt url = https://github.com/web-platform-tests/wpt.git shallow = true [submodule "runtime/StarlingMonkey"] path = runtime/StarlingMonkey url = git@github.com:bytecodealliance/StarlingMonkey ================================================ FILE: .prettierrc.json ================================================ { "singleQuote": true } ================================================ FILE: CHANGELOG.md ================================================ # Changelog ## 3.41.2 (2026-05-04) ### Fixed * `HttpBody::read_all` for large bodies ([#1444](https://github.com/fastly/js-compute-runtime/issues/1444)) ([99f45b5](https://github.com/fastly/js-compute-runtime/commit/99f45b53253d1109202c24cddc3357752873ca90)) * Check pending exceptions between requests in reusable sandbox mode ([#1425](https://github.com/fastly/js-compute-runtime/issues/1425)) ([64a6b21](https://github.com/fastly/js-compute-runtime/commit/64a6b213c605d2ae714b8a49faad9893284998a5)) * Memory issues exposed by high GC zeal ([#1442](https://github.com/fastly/js-compute-runtime/issues/1442)) ([f406308](https://github.com/fastly/js-compute-runtime/commit/f406308ce6ced5b8475839ce43736fb588d3e4b5)) * Memory leak in normalize\_http\_method ([#1449](https://github.com/fastly/js-compute-runtime/issues/1449)) ([669b58a](https://github.com/fastly/js-compute-runtime/commit/669b58a0f34a03f56571723c442b3fee61c90b3b)) * mislabeled `Response::Slots::URL` slot ([#1445](https://github.com/fastly/js-compute-runtime/issues/1445)) ([6d4d268](https://github.com/fastly/js-compute-runtime/commit/6d4d26815acc817365bc41d0784095650847765a)) * Numeric overflow issue in Core Cache API ([#1448](https://github.com/fastly/js-compute-runtime/issues/1448)) ([360c9bf](https://github.com/fastly/js-compute-runtime/commit/360c9bfff611e226c5dbf5fac61d98e993feded3)) * Potential buffer size issues in shielding ([#1443](https://github.com/fastly/js-compute-runtime/issues/1443)) ([4bf9d72](https://github.com/fastly/js-compute-runtime/commit/4bf9d722b68893f188a89c1e6019c9a7699a023b)) * Reset StarlingMonkey engine between requests ([#1426](https://github.com/fastly/js-compute-runtime/issues/1426)) ([238cf70](https://github.com/fastly/js-compute-runtime/commit/238cf70ecd743f73c662ae3757244859d4d2aaad)) * SSL string cipher intersection ([#1446](https://github.com/fastly/js-compute-runtime/issues/1446)) ([13ef2d5](https://github.com/fastly/js-compute-runtime/commit/13ef2d59a4a0c2e93cc0faa8cd98387e3bdee731)) * Use length rather than NUL-terminator when copying `HostString`s ([#1429](https://github.com/fastly/js-compute-runtime/issues/1429)) ([8aa3f4c](https://github.com/fastly/js-compute-runtime/commit/8aa3f4c2cfa441585ac5d3ee1a0ac4d58196162a)) ## 3.41.1 (2026-04-10) ### Fixed * Deal with bodyless statuses in CandidateResponse situations ([#1414](https://github.com/fastly/js-compute-runtime/issues/1414)) ([cfd6c4b](https://github.com/fastly/js-compute-runtime/commit/cfd6c4bd0ac41bb3037bbcdfb7ba7c6608ce65e6)) * Mark FetchEvent as done when we redirect to ws/grip proxies ([9831bd4](https://github.com/fastly/js-compute-runtime/commit/9831bd48f34ad6e80c7932a02b6acd5292ee2799)) * Support `setCacheKey` for HTTP cache ([#1411](https://github.com/fastly/js-compute-runtime/issues/1411)) ([a707c3d](https://github.com/fastly/js-compute-runtime/commit/a707c3d1156893f969b02da1fec3807c0d095860)) ## 3.41.0 (2026-04-08) ### Added * Add `--gc-frequency` option to `debug-build.sh` ([#1395](https://github.com/fastly/js-compute-runtime/issues/1395)) ([a6e4a1f](https://github.com/fastly/js-compute-runtime/commit/a6e4a1fd11acc62b7ce409f1aa2e017ff85b347c)) * Allow the use of project-level external config file for js-compute-runtime CLI behavior ([#1405](https://github.com/fastly/js-compute-runtime/issues/1405)) ([9749cab](https://github.com/fastly/js-compute-runtime/commit/9749cab9f87be27a19a3a9c14bbddcfe2c590c1f)) * Support installation in projects that use TypeScript 6 ([e4273a3](https://github.com/fastly/js-compute-runtime/commit/e4273a3f004e9af0a61d21c67a1cb6c5680cde29)) ### Fixed * Allow `--aot-cache` and `--debug-intermediate-files` flags to be specified with equals ([#1403](https://github.com/fastly/js-compute-runtime/issues/1403)) ([81a75f8](https://github.com/fastly/js-compute-runtime/commit/81a75f8704bd2befa899e55f382920f7da13f26f)) * Double free in `convertBodyInit` ([#1387](https://github.com/fastly/js-compute-runtime/issues/1387)) ([72acfc3](https://github.com/fastly/js-compute-runtime/commit/72acfc3dc9077026746faaf323e5b11ecf48a4db)) * GC fixes for edge rate limiter ([#1397](https://github.com/fastly/js-compute-runtime/issues/1397)) ([fd9e322](https://github.com/fastly/js-compute-runtime/commit/fd9e322fd852612f8df5d925b6e3a6c646b56109)) * GC issue in handoffs ([#1396](https://github.com/fastly/js-compute-runtime/issues/1396)) ([b57fc8f](https://github.com/fastly/js-compute-runtime/commit/b57fc8f720cd530543ba8c8738c9dfe7bdff905e)) * Shielding GC ([#1401](https://github.com/fastly/js-compute-runtime/issues/1401)) ([6de2f55](https://github.com/fastly/js-compute-runtime/commit/6de2f55b97c45dcd9aa246b22c7dbdafa883ee42)) ## 3.40.1 (2026-02-24) ### Fixed * **early-hints:** early hints don't need to be sync inside a FetchEve… ([#1323](https://github.com/fastly/js-compute-runtime/issues/1323)) ([22ac0cc](https://github.com/fastly/js-compute-runtime/commit/22ac0ccd3205a0136e39621e2cfe93968a5be9f3)) ## 3.40.0 (2026-02-17) ### Added * Allow custom weval binary ([#1315](https://github.com/fastly/js-compute-runtime/issues/1315)) ([b143150](https://github.com/fastly/js-compute-runtime/commit/b143150df609f217e8160759c0cf1dae2f86afb7)) * Reusable sandboxes ([#1314](https://github.com/fastly/js-compute-runtime/issues/1314)) ([70a9d28](https://github.com/fastly/js-compute-runtime/commit/70a9d282d276176777d3369e164d8f89d3e96209)) ### Fixed * Add `security` to docs rename script ([#1316](https://github.com/fastly/js-compute-runtime/issues/1316)) ([7028c0b](https://github.com/fastly/js-compute-runtime/commit/7028c0bd819c44b870140d1536039f9aad6ddd4e)) ## 3.39.4 (2026-02-13) ### Fixed * Body truncation error in chained extract\_body requests ([#1310](https://github.com/fastly/js-compute-runtime/issues/1310)) ([b929648](https://github.com/fastly/js-compute-runtime/commit/b929648bef34c0d41fe387fc755a2554372bb946)) ## 3.39.3 (2026-02-12) ### Fixed * Don't throw from `event.client.geo` or `event.client.address` on hostcall error ([#1306](https://github.com/fastly/js-compute-runtime/issues/1306)) ([471b112](https://github.com/fastly/js-compute-runtime/commit/471b1128a32b3a2233a95eb14e2887abbb6183c0)) ## 3.39.2 (2026-02-09) ### Fixed * NPM publication ([f80c089](https://github.com/fastly/js-compute-runtime/commit/f80c089fa9a50835955c0b1a1b42bc24b5eceb3d)) ## 3.39.1 (2026-02-09) ### Fixed * For now, go back to old behavior for default exported types. ([#1298](https://github.com/fastly/js-compute-runtime/issues/1298)) ([e6d96d4](https://github.com/fastly/js-compute-runtime/commit/e6d96d47206821855d80d651bfa248a6d7da4453)) * TransformStream shortcutting fixes ([#1301](https://github.com/fastly/js-compute-runtime/issues/1301)) ([51369ae](https://github.com/fastly/js-compute-runtime/commit/51369ae51d721199e0bbc6f6d168f4b8f7aee947)) ## 3.39.0 (2026-01-28) ### Added * Add `isBot` support to device detection ([#1287](https://github.com/fastly/js-compute-runtime/issues/1287)) ([fe079b1](https://github.com/fastly/js-compute-runtime/commit/fe079b16858ff18da3fe9210da0f5cc3c6bee0b0)) * Implement `firstByteTimeout` for shielding ([#1286](https://github.com/fastly/js-compute-runtime/issues/1286)) ([ad445b7](https://github.com/fastly/js-compute-runtime/commit/ad445b70ddd56bcd39d6201ad3f15e860cb85db4)) * Map the FastlyStatus values into KVStoreError values the same way the Rust SDK does ([#1280](https://github.com/fastly/js-compute-runtime/issues/1280)) ([726f4e2](https://github.com/fastly/js-compute-runtime/commit/726f4e285805e91cfcc0c7fdd58f127e4d2e9094)) ### Fixed * Correct default export ([#1269](https://github.com/fastly/js-compute-runtime/issues/1269)) ([58d872e](https://github.com/fastly/js-compute-runtime/commit/58d872e2ff6b6351ac4018f590f3a27a1e015297)) * suppress sourcemap for bundle() step when `--enable-stack-traces` is not set ([#1277](https://github.com/fastly/js-compute-runtime/issues/1277)) ([ab8c12e](https://github.com/fastly/js-compute-runtime/commit/ab8c12e6aaf22dcf52ca74834fb5712a7ed83b42)) ## 3.38.4 (2026-01-23) ### Fixed * Don't shortcut transform too early ([#1281](https://github.com/fastly/js-compute-runtime/issues/1281)) ([291814e](https://github.com/fastly/js-compute-runtime/commit/291814e330ae5e1e894f0a57db0dedc8b27fd9bd)) ## 3.38.3 (2026-01-22) ### Fixed * clean script to include TypeScript output directory ([#1270](https://github.com/fastly/js-compute-runtime/issues/1270)) ([015e40c](https://github.com/fastly/js-compute-runtime/commit/015e40c7f6cf6bf95f5a2ff7c52f4225948146a1)) * pin lol\_html to 2.7.0 ([#1276](https://github.com/fastly/js-compute-runtime/issues/1276)) ([363550a](https://github.com/fastly/js-compute-runtime/commit/363550ae80056fb0e6fda2c7b67ddf4859d67fa8)) * Rename shielding docs ([#1272](https://github.com/fastly/js-compute-runtime/issues/1272)) ([e12ab47](https://github.com/fastly/js-compute-runtime/commit/e12ab476821e9656dcdb5025e6ed54f40daf8da5)) * Try and shortcut transform stream reading before doing a regular read ([#1279](https://github.com/fastly/js-compute-runtime/issues/1279)) ([6b9b939](https://github.com/fastly/js-compute-runtime/commit/6b9b939471e1589091f6cfa2f7864a528df35b1c)) ## 3.38.2 (2025-12-19) ### Fixed * Handle cross-volume renames of intermediate files ([#1264](https://github.com/fastly/js-compute-runtime/issues/1264)) ([94e5671](https://github.com/fastly/js-compute-runtime/commit/94e5671090cbde1c3159032c90aa3f3ad2fdc88a)) ## 3.38.1 (2025-12-18) ### Fixed * Build CLI in npm publish ([#1262](https://github.com/fastly/js-compute-runtime/issues/1262)) ([2fe6e2d](https://github.com/fastly/js-compute-runtime/commit/2fe6e2d5b38c74c4a3f7c4a4941d116ec75b1d88)) ## 3.38.0 (2025-12-18) ### Added * **config:** add support for config store buffers longer than 8k ([#1181](https://github.com/fastly/js-compute-runtime/issues/1181)) ([da4c169](https://github.com/fastly/js-compute-runtime/commit/da4c169f7a302c2e6c2a1796c791b9463c4dc2a8)) * **inspect:** add support for NGWAF inspect api ([#1212](https://github.com/fastly/js-compute-runtime/issues/1212)) ([98f45e4](https://github.com/fastly/js-compute-runtime/commit/98f45e4d678e294301c21be2ddf16c4482683ef7)) ### Fixed * Correct behaviour of chained body proxy streams in some circumstances ([#1259](https://github.com/fastly/js-compute-runtime/issues/1259)) ([11f9a4b](https://github.com/fastly/js-compute-runtime/commit/11f9a4b5b5fc90f9f2eb9f6a6958e971fbd52e19)) * make shielding.d.ts ambient ([#1256](https://github.com/fastly/js-compute-runtime/issues/1256)) ([7a0e987](https://github.com/fastly/js-compute-runtime/commit/7a0e9876d0e001ad6c1b87b3701ecfffddc7b5ad)) ## 3.37.0 (2025-12-11) ### Added * Add client fingerprint properties (tlsJA4, h2Fingerprint, ohFingerprint) ([#1248](https://github.com/fastly/js-compute-runtime/issues/1248)) ([9390e8c](https://github.com/fastly/js-compute-runtime/commit/9390e8cdf37206a570512cf8d36335c70bc5ccde)) * Shielding support ([#1241](https://github.com/fastly/js-compute-runtime/issues/1241)) ([985c55e](https://github.com/fastly/js-compute-runtime/commit/985c55e634227b8dac66aea9b7ba4ca982b41b9c)) ## 3.36.0 (2025-11-18) ### Added * Image Optimizer support ([#1224](https://github.com/fastly/js-compute-runtime/issues/1224)) ([c3dd3de](https://github.com/fastly/js-compute-runtime/commit/c3dd3de7436f999055eb0b3d83a1f59c1c26b5d1)) * Implement 103 Early Hints ([#1217](https://github.com/fastly/js-compute-runtime/issues/1217)) ([fda6ad3](https://github.com/fastly/js-compute-runtime/commit/fda6ad31d6f8ceee16cd950217be770a4f794bb3)) ### Fixed * **fanout:** commit request headers before fanout handoff ([#1222](https://github.com/fastly/js-compute-runtime/issues/1222)) ([8dfefad](https://github.com/fastly/js-compute-runtime/commit/8dfefadec46a2714be010c4a8c7e59cd43537fec)) * Fix broken KVStore test ([#1223](https://github.com/fastly/js-compute-runtime/issues/1223)) ([6055d88](https://github.com/fastly/js-compute-runtime/commit/6055d884f617336d8d6326bf26dcfb49265f5ae2)) ## 3.35.2 (2025-11-07) ### Fixed * **compute-file-server:** bump MSRV to fix ICU build issues ([#1221](https://github.com/fastly/js-compute-runtime/issues/1221)) ([379e511](https://github.com/fastly/js-compute-runtime/commit/379e51153e07962972b8a69e645e0f55912122d0)) * surrogateKeys not being added when using CoreCache ([#1219](https://github.com/fastly/js-compute-runtime/issues/1219)) ([b0efe20](https://github.com/fastly/js-compute-runtime/commit/b0efe20c2f6f96755bb450d139e002797b376802)) * **ws:** commit ws request headers before upgrading ([#1216](https://github.com/fastly/js-compute-runtime/issues/1216)) ([a15fa61](https://github.com/fastly/js-compute-runtime/commit/a15fa6148427801bbaf4d862b9a21884f21758f9)) ## 3.35.1 (2025-09-29) ### Fixed * Root HTML rewriter variables to ensure no GC ([#1202](https://github.com/fastly/js-compute-runtime/issues/1202)) ([6aaf9f3](https://github.com/fastly/js-compute-runtime/commit/6aaf9f391acccfb68c5a012d92bf324df04d4230)) ## 3.35.0 (2025-09-26) ### Added * HTML Rewriter ([0015ff1](https://github.com/fastly/js-compute-runtime/commit/0015ff155b9f57995ccf63671aee8c112b664678)) ### Fixed * Remove broken CI tests ([5b645f7](https://github.com/fastly/js-compute-runtime/commit/5b645f726f7a4f6eb741db3addda4b45be1dd63c)) * Update rust toolchain for compute-file-server-cli ([09d5a6d](https://github.com/fastly/js-compute-runtime/commit/09d5a6dc66b0f1befff7268915f13dc4d7ac0854)) ## 3.34.0 (2025-04-11) ### Added * add support for Websocket passthrough ([#1172](https://github.com/fastly/js-compute-runtime/issues/1172)) ([fcf2a54](https://github.com/fastly/js-compute-runtime/commit/fcf2a54e2935061b4d67ccb430d485d79ee0bd04)) ## 3.33.4 (2025-04-04) ### Fixed * publish workflow ([#1166](https://github.com/fastly/js-compute-runtime/issues/1166)) ([3db857c](https://github.com/fastly/js-compute-runtime/commit/3db857c095aabbb15060694c3c84ae985cee13a1)) ## 3.33.3 (2025-04-04) ### Fixed * config store documentation fix ([#1160](https://github.com/fastly/js-compute-runtime/issues/1160)) ([4047c7b](https://github.com/fastly/js-compute-runtime/commit/4047c7b0862bbaa799053cc341674725425f933a)) * TypeScript declaration for Headers ([#1155](https://github.com/fastly/js-compute-runtime/issues/1155)) ([a6664b9](https://github.com/fastly/js-compute-runtime/commit/a6664b908db4f2f784ddedc53798f7c31474530e)) ## 3.33.2 (2025-03-17) ### Fixed * TypeScript declaration return type of Acl.open() ([#1149](https://github.com/fastly/js-compute-runtime/issues/1149)) ([b9765f6](https://github.com/fastly/js-compute-runtime/commit/b9765f68823529327a8ec75268f4833d308ad6bd)) * TypeScript type definitions for Blob, File, FormData ([#1150](https://github.com/fastly/js-compute-runtime/issues/1150)) ([4c93d79](https://github.com/fastly/js-compute-runtime/commit/4c93d794390e3f2cb98e8e806744620e2cde3b3b)) * TypeScript type definitions for Event and EventTarget ([#1151](https://github.com/fastly/js-compute-runtime/issues/1151)) ([eb1ab0d](https://github.com/fastly/js-compute-runtime/commit/eb1ab0d2f693c199947e8b6ffc4a7c1d758024ad)) ## 3.33.1 (2025-03-12) ### Fixed * documentation fix ([#1147](https://github.com/fastly/js-compute-runtime/issues/1147)) ([15b9ea5](https://github.com/fastly/js-compute-runtime/commit/15b9ea5b3121e779f0873a1562cc51ed710135c7)) ## 3.33.0 (2025-03-12) ### Added * add support for EventTarget ([#1145](https://github.com/fastly/js-compute-runtime/issues/1145)) ([a735993](https://github.com/fastly/js-compute-runtime/commit/a735993e609b5e2405a5223e7bc02ef655a47d68)) * FormData support and Request.formData and Response.formData ([#1144](https://github.com/fastly/js-compute-runtime/issues/1144)) ([0214ae7](https://github.com/fastly/js-compute-runtime/commit/0214ae70b8d5afd1bc66231d779af5b606e89efb)) ### Fixed * Backend.prototype.health method definition ([#1143](https://github.com/fastly/js-compute-runtime/issues/1143)) ([42d429b](https://github.com/fastly/js-compute-runtime/commit/42d429bafdd7ec02854217675bdb58eba1e533a4)) * Weval stack overflow bug ([#1135](https://github.com/fastly/js-compute-runtime/issues/1135)) ([f6947d9](https://github.com/fastly/js-compute-runtime/commit/f6947d9eb9fcd10f91c8c439a8a5cd6db8169d9e)) ## 3.32.2 (2025-02-26) ### Fixed * ready-based immediate task indexing ([#1129](https://github.com/fastly/js-compute-runtime/issues/1129)) ([8cfad4f](https://github.com/fastly/js-compute-runtime/commit/8cfad4f78c137afbdc0281e92c39e31415a1188b)) ## 3.32.1 (2025-02-20) ### Fixed * docs server toolchain fix ([#1124](https://github.com/fastly/js-compute-runtime/issues/1124)) ([c2490d1](https://github.com/fastly/js-compute-runtime/commit/c2490d117754cb53a88cf3d40a1795a7b5177f54)) ## 3.32.0 (2025-02-20) ### Added * Acl Support ([#1073](https://github.com/fastly/js-compute-runtime/issues/1073)) ([0f93f7b](https://github.com/fastly/js-compute-runtime/commit/0f93f7ba72f3a7cdb3de979af8ef677bccc1bd5b)) ## 3.31.0 (2025-02-14) ### Added * KV store generation integer follow up ([#1029](https://github.com/fastly/js-compute-runtime/issues/1029)) ([#1108](https://github.com/fastly/js-compute-runtime/issues/1108)) ([8a076da](https://github.com/fastly/js-compute-runtime/commit/8a076dae5de19cb23cee0569359a6879667d6275)) ## 3.30.1 (2025-02-01) ### Fixed * docs build ([#1104](https://github.com/fastly/js-compute-runtime/issues/1104)) ([49b4758](https://github.com/fastly/js-compute-runtime/commit/49b47580819b0be4718f7156e7ab8d8eb8375143)) ## 3.30.0 (2025-01-31) ### Added * HTTP Cache API ([#1051](https://github.com/fastly/js-compute-runtime/issues/1051)) ([35e7565](https://github.com/fastly/js-compute-runtime/commit/35e7565eaa64a957445fbfd1b8acd9f78b289ba1)) ### Fixed * forbidden KV key special characters to match documentation ([#1097](https://github.com/fastly/js-compute-runtime/issues/1097)) ([fefc024](https://github.com/fastly/js-compute-runtime/commit/fefc024e9b53cc6e0a8bfa6769817a55e2ac154d)) ## 3.29.2 (2025-01-23) ### Fixed * release workflow artifact version ([#1094](https://github.com/fastly/js-compute-runtime/issues/1094)) ([1c46dd6](https://github.com/fastly/js-compute-runtime/commit/1c46dd6f70908ab9f73d6aa890288056004a8498)) ## 3.29.1 (2025-01-23) ### Fixed * to release process, update upload artifact ([#1092](https://github.com/fastly/js-compute-runtime/issues/1092)) ([fb5d25f](https://github.com/fastly/js-compute-runtime/commit/fb5d25ff2276c40a640c6e83ce521379687ce656)) ## 3.29.0 (2025-01-23) ### Added * Blob support for fetch API ([#1070](https://github.com/fastly/js-compute-runtime/issues/1070)) ([56aa96d](https://github.com/fastly/js-compute-runtime/commit/56aa96d5a223d45d79327f0a19bcfd93f1e90363)) * Fanout update to redirect\_to\_grip\_proxy\_v2 passing request handle ([#1079](https://github.com/fastly/js-compute-runtime/issues/1079)) ([baf0a6e](https://github.com/fastly/js-compute-runtime/commit/baf0a6e3f2d655954d7ae73944b7e72709356a2d)) * support --env option for the runtime build ([#1090](https://github.com/fastly/js-compute-runtime/issues/1090)) ([e81d252](https://github.com/fastly/js-compute-runtime/commit/e81d252e0f1c2a76441cef407c7c1dc84ed93dcc)) ### Fixed * reinstate broken wpt tests ([#1071](https://github.com/fastly/js-compute-runtime/issues/1071)) ([5e2c682](https://github.com/fastly/js-compute-runtime/commit/5e2c68228be24ea6bd286fca0ca1ffbe028199c2)) ## 3.28.0 (2024-12-09) ### Added * configureConsole function for configuring log prefixing and stderr ([#1065](https://github.com/fastly/js-compute-runtime/issues/1065)) ([9ed80ee](https://github.com/fastly/js-compute-runtime/commit/9ed80ee349b4178a54b960081fcae622a6406b70)) * StarlingMonkey update ([#1067](https://github.com/fastly/js-compute-runtime/issues/1067)) ([857f6fa](https://github.com/fastly/js-compute-runtime/commit/857f6fa497be5e4ba2b48392dbbdc11ab7e98e34)) ### Fixed * do not throw uninitialized for KV ([#1064](https://github.com/fastly/js-compute-runtime/issues/1064)) ([c160c4a](https://github.com/fastly/js-compute-runtime/commit/c160c4ab5378be20052fed66abc9d194a4329065)) * KVStore lookup fix for if-generation-match option ([#1069](https://github.com/fastly/js-compute-runtime/issues/1069)) ([9e4c795](https://github.com/fastly/js-compute-runtime/commit/9e4c795c3c083a85d36808e1ac26376a3779e0a4)) ## 3.27.3 (2024-12-03) ### Fixed * KVStore error handling ([#1060](https://github.com/fastly/js-compute-runtime/issues/1060)) ([95885d8](https://github.com/fastly/js-compute-runtime/commit/95885d88b471aa17421dc52073df98e055737e40)) ## 3.27.2 (2024-11-09) ### Fixed * docs build, ensuring compute-file-server-cli for publish ([#1044](https://github.com/fastly/js-compute-runtime/issues/1044)) ([40de0b8](https://github.com/fastly/js-compute-runtime/commit/40de0b86a012df7fdba8d764b22ea2893b3d8a0d)) ## 3.27.1 (2024-11-09) ### Fixed * documentation site build ([#1042](https://github.com/fastly/js-compute-runtime/issues/1042)) ([3211ff9](https://github.com/fastly/js-compute-runtime/commit/3211ff989658a4c00bd2198ed32b723d13e7a19c)) ## 3.27.0 (2024-11-07) ### Added * \--enable-aot AOT compilation flag; no longer experimental. ([#1033](https://github.com/fastly/js-compute-runtime/issues/1033)) ([8128c4d](https://github.com/fastly/js-compute-runtime/commit/8128c4dd4b64b5a9979d7dc690d02b2c7bbcc1f7)) ### Fixed * ensure headers are set on first commit ([#1036](https://github.com/fastly/js-compute-runtime/issues/1036)) ([d622799](https://github.com/fastly/js-compute-runtime/commit/d6227994b896b3e31592231db955ddef3e8356bc)) * fixup compute-file-server-cli dependency build ([#1037](https://github.com/fastly/js-compute-runtime/issues/1037)) ([206a60e](https://github.com/fastly/js-compute-runtime/commit/206a60ed49ebb209df04c9337d9703f1c12a3153)) ## 3.26.0 (2024-10-31) ### Added * document AOT optimization flag ([#1023](https://github.com/fastly/js-compute-runtime/issues/1023)) ([9ba14cd](https://github.com/fastly/js-compute-runtime/commit/9ba14cdb263341d80476233424c9c2c7d5276c2c)) * KV Store v2 ([#1004](https://github.com/fastly/js-compute-runtime/issues/1004)) ([fda97cc](https://github.com/fastly/js-compute-runtime/commit/fda97cc423a9eb96bd11ac5a5b9a5d4b6f93b081)) * module mode ([#1021](https://github.com/fastly/js-compute-runtime/issues/1021)) ([9e47649](https://github.com/fastly/js-compute-runtime/commit/9e4764919c678701accd9cef039de5ff2761f7cc)) ### Fixed * typing file for compute builtin ([#1028](https://github.com/fastly/js-compute-runtime/issues/1028)) ([b328546](https://github.com/fastly/js-compute-runtime/commit/b3285467f0e5fedcca6bd23ee414db1e8d92a83a)) ## 3.25.0 (2024-10-22) ### Added * support backend property on both Request and Response, as a Backend instance ([#1019](https://github.com/fastly/js-compute-runtime/issues/1019)) ([4e3b93d](https://github.com/fastly/js-compute-runtime/commit/4e3b93d9de1f0af9eed7c900eedb8a509d7723da)) ### Fixed * set SSL properly for created dynamic backends ([#1016](https://github.com/fastly/js-compute-runtime/issues/1016)) ([616e898](https://github.com/fastly/js-compute-runtime/commit/616e89827087623b8180665591127143532dc309)) ## 3.24.3 (2024-10-16) ### Fixed * docs build, dependency updates ([#1013](https://github.com/fastly/js-compute-runtime/issues/1013)) ([59dc069](https://github.com/fastly/js-compute-runtime/commit/59dc069b97d5b1ef6fba049d592d727dcc409c97)) ## 3.24.2 (2024-10-16) ### Fixed * doc links for deploy ([#1011](https://github.com/fastly/js-compute-runtime/issues/1011)) ([1c55c91](https://github.com/fastly/js-compute-runtime/commit/1c55c91169611a09517bbeecaaa4a55ae9676503)) ## 3.24.1 (2024-10-16) ### Fixed * release workflow versioning ([#1009](https://github.com/fastly/js-compute-runtime/issues/1009)) ([1922c8a](https://github.com/fastly/js-compute-runtime/commit/1922c8affa3085dedf44e7f8adada3be50649118)) ## 3.24.0 (2024-10-15) ### Added * default enable allowDynamicBackends with better unsupported errors ([#995](https://github.com/fastly/js-compute-runtime/issues/995)) ([bb858fe](https://github.com/fastly/js-compute-runtime/commit/bb858fe71ffa20a6be256fa27c1bfa9e44a503e5)) * setDefaultDynamicBackendConfig with all backend configuration options ([#993](https://github.com/fastly/js-compute-runtime/issues/993)) ([1847924](https://github.com/fastly/js-compute-runtime/commit/1847924e223f01679017d7f79658b7601ad5bd7a)) * support backend property hostcalls ([#1002](https://github.com/fastly/js-compute-runtime/issues/1002)) ([1d9f91a](https://github.com/fastly/js-compute-runtime/commit/1d9f91a2cba2b5d2dad8ae03094ed9452fcb0a42)) ## 3.23.0 (2024-09-18) ### Added * grpc backend option ([#971](https://github.com/fastly/js-compute-runtime/issues/971)) ([e10829d](https://github.com/fastly/js-compute-runtime/commit/e10829d73aa0e0ccee20f19ad4c27b79f3c0723e)) ### Fixed * never error for missing client data, return null instead ([#979](https://github.com/fastly/js-compute-runtime/issues/979)) ([7068321](https://github.com/fastly/js-compute-runtime/commit/706832106fce165c5857f9671cb004ce33537225)) * null return instead of an error for missing geo data ([d4c9b69](https://github.com/fastly/js-compute-runtime/commit/d4c9b699a115b5475b5a06b2ba66e259c8d4e952)) * simple cache getOrSet inner rejections to reject outer promise ([#981](https://github.com/fastly/js-compute-runtime/issues/981)) ([c1fdc49](https://github.com/fastly/js-compute-runtime/commit/c1fdc49211b88dbf17a195782ac34a5c226f3f9f)) ## 3.22.4 (2024-09-13) ### Fixed * docs build ([#968](https://github.com/fastly/js-compute-runtime/issues/968)) ([796cdc0](https://github.com/fastly/js-compute-runtime/commit/796cdc03b4a123f2edc9d8fdeb21246cc63669ee)) ## 3.22.3 (2024-09-12) ### Fixed * docs version include ([#966](https://github.com/fastly/js-compute-runtime/issues/966)) ([9be970d](https://github.com/fastly/js-compute-runtime/commit/9be970dc68010e7ee292c0383a0ef58100e384cd)) ## 3.22.2 (2024-09-12) ### Fixed * docs deployment ([#964](https://github.com/fastly/js-compute-runtime/issues/964)) ([510c246](https://github.com/fastly/js-compute-runtime/commit/510c246315cfb247485aed05442be93981e965f2)) ## 3.22.1 (2024-09-12) ### Fixed * fastly:compute type index ([#960](https://github.com/fastly/js-compute-runtime/issues/960)) ([9bd25fd](https://github.com/fastly/js-compute-runtime/commit/9bd25fd5481693394669d814738fb3d05fdf2312)) * windows support & windows ci ([#962](https://github.com/fastly/js-compute-runtime/issues/962)) ([d8e9c5e](https://github.com/fastly/js-compute-runtime/commit/d8e9c5e5a7ec6972ad6018b66a4eb454bef4c8f0)) ## 3.22.0 (2024-09-11) ### Added * Add support for vcpu ms hostcall ([#950](https://github.com/fastly/js-compute-runtime/issues/950)) ([aea826f](https://github.com/fastly/js-compute-runtime/commit/aea826feb65c680f627b9e3b01152bb0534d9fd6)) * expose purgeSurrogateKey hostcall ([#953](https://github.com/fastly/js-compute-runtime/issues/953)) ([4468e3c](https://github.com/fastly/js-compute-runtime/commit/4468e3c2a70d97b3efd1e76a7053b9d1a01227e0)) ### Fixed * passing direct response body to requests in streaming ([#954](https://github.com/fastly/js-compute-runtime/issues/954)) ([6bf90b9](https://github.com/fastly/js-compute-runtime/commit/6bf90b915379ddab5257672b4778c0b81a5523e4)) ## 3.21.4 (2024-09-05) ### Fixed * \--experimental-top-level-await support ([#945](https://github.com/fastly/js-compute-runtime/issues/945)) ([edd8ada](https://github.com/fastly/js-compute-runtime/commit/edd8ada770ae3cd2763ee30bfb15a7a6709a1f37)) ## 3.21.3 (2024-09-04) ### Fixed * Device.toJSON() properties ([#937](https://github.com/fastly/js-compute-runtime/issues/937)) ([c4182d3](https://github.com/fastly/js-compute-runtime/commit/c4182d30e8d22d7720acb9d51bd59763ab8b83e5)) * event loop stall error no longer a panic ([#934](https://github.com/fastly/js-compute-runtime/issues/934)) ([08c9934](https://github.com/fastly/js-compute-runtime/commit/08c9934c59bd00ddd2dde252f6529ee8322be809)) ## 3.21.2 (2024-08-27) ### Fixed * revert documentation website refactoring ([#915](https://github.com/fastly/js-compute-runtime/issues/915)) ([ba1eb66](https://github.com/fastly/js-compute-runtime/commit/ba1eb667cb136c6cdd09938e397ee5cf334561d7)) ## 3.21.1 (2024-08-27) ### Fixed * missing publish file, parallel publish build ([#912](https://github.com/fastly/js-compute-runtime/issues/912)) ([91ae54c](https://github.com/fastly/js-compute-runtime/commit/91ae54cbbd92d83fa9c1896df006b1008a5f8291)) ## 3.21.0 (2024-08-27) ### Added * ship --debug-build CLI flag as public ([#907](https://github.com/fastly/js-compute-runtime/issues/907)) ([2728141](https://github.com/fastly/js-compute-runtime/commit/27281413db682f5e2e87928937456bc1b8345dd7)) * support getSetCookie on new StarlingMonkey headers implementation ([#844](https://github.com/fastly/js-compute-runtime/issues/844)) ([c102521](https://github.com/fastly/js-compute-runtime/commit/c1025210a591fc99fae9c3b921504a6189552a74)) ## 3.20.0 (2024-08-08) ### Added * Add new CLI name of `js-compute` which matches the published package name `@fastly/js-compute` ([#869](https://github.com/fastly/js-compute-runtime/issues/869)) ([60d1d20](https://github.com/fastly/js-compute-runtime/commit/60d1d2067d846aa15a76820e666004cf56d1df99)) ### Fixed * core-cache headers case ([#889](https://github.com/fastly/js-compute-runtime/issues/889)) ([3f2db5c](https://github.com/fastly/js-compute-runtime/commit/3f2db5c466151efddf1731c6be080c2a2875a43d)) * ensure we throw an error if FastlyBody.prototype.read is called with a value which is not coercible to a finite positive integer ([#877](https://github.com/fastly/js-compute-runtime/issues/877)) ([1633e02](https://github.com/fastly/js-compute-runtime/commit/1633e025d92be3a1f8b0616685b48e27dc913841)) * perf: Use wasm-opt -O3 when making a release build ([#870](https://github.com/fastly/js-compute-runtime/issues/870)) ([dd91fa5](https://github.com/fastly/js-compute-runtime/commit/dd91fa506b74487b70dc5bec510e89de95e1c569)) * When constructing an EdgeRateLimiter, retrieve the PenaltyBox instance's name using PenaltyBox::get\_name ([#866](https://github.com/fastly/js-compute-runtime/issues/866)) ([9222f1d](https://github.com/fastly/js-compute-runtime/commit/9222f1d16a9c17b080be575affffbb83c461dd81)) ### Changed * only time the fetch event when debug logging is enabled ([#873](https://github.com/fastly/js-compute-runtime/issues/873)) ([e4ddf8a](https://github.com/fastly/js-compute-runtime/commit/e4ddf8ac3c78bea753e8d9418715d1e703e7e7bc)) * re-order the http methods so the most often requested is first and the least requested is last ([#874](https://github.com/fastly/js-compute-runtime/issues/874)) ([6af7626](https://github.com/fastly/js-compute-runtime/commit/6af7626085af62a14520f14f69a0e64a515fd5ef)) * Use MOZ\_ASSERT instead of MOZ\_RELEASE\_ASSERT as these methods are already guarded correctly where they are being called ([#876](https://github.com/fastly/js-compute-runtime/issues/876)) ([f089616](https://github.com/fastly/js-compute-runtime/commit/f089616e8febc783cc96363f5ce65fc6f1acafb1)) ## 3.19.0 (2024-07-29) ### Added * Add FetchEvent.server object which contains information about the server which received the incoming HTTP request from the client. ([#855](https://github.com/fastly/js-compute-runtime/issues/855)) ([538ed9c](https://github.com/fastly/js-compute-runtime/commit/538ed9c436105caf4bf906355fcf110752870b2b)) * use StarlingMonkey by default, --disable-starlingmonkey flag ([#861](https://github.com/fastly/js-compute-runtime/issues/861)) ([475cdf9](https://github.com/fastly/js-compute-runtime/commit/475cdf910d5690d74ff96dccd14dfefc209ea944)) ### Fixed * Correct Class name for the ClientInfo class ([#854](https://github.com/fastly/js-compute-runtime/issues/854)) ([efb5694](https://github.com/fastly/js-compute-runtime/commit/efb569475a285bdeb2dcc1346d718eb26be4fed9)) * correct spelling in CLI error message ([#849](https://github.com/fastly/js-compute-runtime/issues/849)) ([38b558c](https://github.com/fastly/js-compute-runtime/commit/38b558c3ad7c6871243823a207485ba9cc6282dd)) ## 3.18.1 (2024-07-18) ### Fixed * add type definitions of Performance APIs ([#841](https://github.com/fastly/js-compute-runtime/issues/841)) ([fd95aae](https://github.com/fastly/js-compute-runtime/commit/fd95aaecc5a264860845740a3b60d4a7aa75c578)) ## 3.18.0 (2024-07-16) ### Added * support for Response.prototype.ip and port via get\_addr\_dest\_ip & get\_addr\_dest\_port ([#817](https://github.com/fastly/js-compute-runtime/issues/817)) ([391b3d8](https://github.com/fastly/js-compute-runtime/commit/391b3d8386defe5e1b4ce3c1fb70347a9f0802ca)) * Update to SpiderMonkey v127.0.2 ([#826](https://github.com/fastly/js-compute-runtime/issues/826)) ([5341f67](https://github.com/fastly/js-compute-runtime/commit/5341f674fe0da5ac5057d3415f59ac807d2f96f7)) ## 3.17.3 (2024-07-16) ### Fixed * Remove accidentally commited debug messages which write to stderr ([#838](https://github.com/fastly/js-compute-runtime/issues/838)) ([040ea8b](https://github.com/fastly/js-compute-runtime/commit/040ea8be352884c3536ac7e786663b4596617e6e)) ## 3.17.2 (2024-07-13) ### Fixed * add documentation for the sdkVersion property ([29361ad](https://github.com/fastly/js-compute-runtime/commit/29361ad65965a7a36cb2ced434af7898844dcab7)) * correct the documentation for the fastly:logger module ([#834](https://github.com/fastly/js-compute-runtime/issues/834)) ([2790cb9](https://github.com/fastly/js-compute-runtime/commit/2790cb93f5f298b021f46b9030d0e6e795003a51)) ## 3.17.1 (2024-07-11) ### Fixed * documentation site build ([#831](https://github.com/fastly/js-compute-runtime/issues/831)) ([110f1ff](https://github.com/fastly/js-compute-runtime/commit/110f1ffb4e1b80772b9f9541a58456bedfd4ddec)) ## 3.17.0 (2024-07-11) ### Added * Include in the wasm metadata whether we are using StarlingMonkey and/or PBL ([#828](https://github.com/fastly/js-compute-runtime/issues/828)) ([00b971b](https://github.com/fastly/js-compute-runtime/commit/00b971b857e9c35a08e6fc5c0a84fb3c3bc7984e)) ### Fixed * keep sdkVersion property always up-to-date with the correct version of the SDK ([#829](https://github.com/fastly/js-compute-runtime/issues/829)) ([ae42634](https://github.com/fastly/js-compute-runtime/commit/ae4263418a52dfb62fe240584314948072ff30e7)) ## 3.16.2 (2024-07-10) ### Fixed * use same rust version that StarlingMonkey uses so that we can publish ([#823](https://github.com/fastly/js-compute-runtime/issues/823)) ([f0d9ab0](https://github.com/fastly/js-compute-runtime/commit/f0d9ab07ed5a5470322a3b457cc91e308e3e289f)) ## 3.16.1 (2024-07-09) ### Fixed * CLI to allow commands/args in spawnSync() to contain whitespace ([#821](https://github.com/fastly/js-compute-runtime/issues/821)) ([68d77fb](https://github.com/fastly/js-compute-runtime/commit/68d77fbff9f695f53b30ee63d53b41fd8db87424)) * debug build & tests ([#818](https://github.com/fastly/js-compute-runtime/issues/818)) ([3d9a8da](https://github.com/fastly/js-compute-runtime/commit/3d9a8da2898fffa6b43d005eba3342df4ff67036)) ## 3.16.0 (2024-06-21) ### Added * add out-of-memory callback with stderr log ([#805](https://github.com/fastly/js-compute-runtime/issues/805)) ([a1bd16c](https://github.com/fastly/js-compute-runtime/commit/a1bd16c06924ea1748846d2b8159b9b2939ae61d)) * Allow early logger initialization ([#804](https://github.com/fastly/js-compute-runtime/issues/804)) ([514d014](https://github.com/fastly/js-compute-runtime/commit/514d0145ba88de3a7114e957457a7f9570e17019)) ### Fixed * Fix string formatting for limit-exceeded errors ([#802](https://github.com/fastly/js-compute-runtime/issues/802)) ([56f5214](https://github.com/fastly/js-compute-runtime/commit/56f5214ad9f431845f6b06cb92e0b98169ceffbe)) * Fix uses of cabi\_realloc that were discarding their results ([#811](https://github.com/fastly/js-compute-runtime/issues/811)) ([4e16641](https://github.com/fastly/js-compute-runtime/commit/4e16641ef4e159c4a11b500ac861b8fa8d9ff5d3)) ## 3.15.0 (2024-06-03) ### Added * dynamic backends clientCertificate with SecretStore fromBytes, rawbytes ([#796](https://github.com/fastly/js-compute-runtime/issues/796)) ([7d2b7b7](https://github.com/fastly/js-compute-runtime/commit/7d2b7b781ed808d9bcf1fe9584aa31f788b980a2)) * support default timeout configurations for dynamic backends ([#792](https://github.com/fastly/js-compute-runtime/issues/792)) ([4dfa8d7](https://github.com/fastly/js-compute-runtime/commit/4dfa8d76aeb4364ed5267ed22de0b9a891781589)) ## 3.14.2 (2024-05-21) ### Fixed * changelog formatting ([1473a87](https://github.com/fastly/js-compute-runtime/commit/1473a87092c6c02e37378897eb0a4042da2f90c8)) * revert changelog heading changes ([#784](https://github.com/fastly/js-compute-runtime/issues/784)) ([59195b6](https://github.com/fastly/js-compute-runtime/commit/59195b6aec1353adc6f6ad8322f7414d90adc518)) ## 3.14.1 (2024-05-17) ### Fixed * fix documentation build ([#781](https://github.com/fastly/js-compute-runtime/issues/781)) ([864864e](https://github.com/fastly/js-compute-runtime/commit/864864e05ca3cf286f049d2c692401e708008052)) ## 3.14.0 (2024-05-16) ### Added * fastly.sdkVersion implementation ([#776](https://github.com/fastly/js-compute-runtime/issues/776)) ([3eb5a8f](https://github.com/fastly/js-compute-runtime/commit/3eb5a8ff9aaad279dc17deee1c2e8760fea28a49)) ### Fixed * support cacheKey in Request init ([#770](https://github.com/fastly/js-compute-runtime/issues/770)) ([b64b22e](https://github.com/fastly/js-compute-runtime/commit/b64b22e988d8e3ca20c42c13f6cb89be871a5d61)) ## 3.13.1 (2024-04-12) ### Fixed * remove debugging message which got commited ([4219a0a](https://github.com/fastly/js-compute-runtime/commit/4219a0ac87d68d9a9fc57aaea43994a867f5dd0e)) ## 3.13.0 (2024-04-11) ### Added * Add KVStore.prototype.delete method ([578d858](https://github.com/fastly/js-compute-runtime/commit/578d858b6678c27116ead213f58d2f4fe80f1355)) ### Changed * Update to SpiderMonkey 124.0.2 ([e32632e](https://github.com/fastly/js-compute-runtime/commit/e32632e16ba822770dd9b0637185f7266a7952e2)) This release includes: \- An optimization for functions that only use `arguments.length` to avoid allocating the `arguments` object. \- An optimization for `Object.HasOwn` which for small numbers of atoms just unrolls the loop. ### Fixed * Correct type definition for the global BackendConfiguration type - there is no `checkCertificate` field ([62fd0ea](https://github.com/fastly/js-compute-runtime/commit/62fd0ea36e6aefd4a3cb281a09716a901f111485)) * Improve our console.log output for functions ([9a97fc1](https://github.com/fastly/js-compute-runtime/commit/9a97fc1352926ecad8377d72eca1e18e28aa2173)) * Refactor our async task implementation to be a generic AsyncTask class instead of separate implementations for each async operation ([68dfec7](https://github.com/fastly/js-compute-runtime/commit/68dfec75a0c9c583dc4be39a17cbbf9b70ff8b40)) ## 3.12.1 (2024-04-05) ### Changed * declare support for npm 10 ([#747](https://github.com/fastly/js-compute-runtime/issues/747)) ([1365ee9](https://github.com/fastly/js-compute-runtime/commit/1365ee9b1aa4e830677c840ea43df55bbf19d660)) ## 3.12.0 (2024-03-28) ### Changed * update to SpiderMonkey 123.0.1 ([#744](https://github.com/fastly/js-compute-runtime/issues/744)) ([32bf617](https://github.com/fastly/js-compute-runtime/commit/32bf61707f1133d4a2656913d726d66523398fb1)) This update brings with it the below changes: * Performance improvements for `JSON.stringify()` * An optimisation for `Object.keys()` to take advantage of cached for-in iterators if available. * Optimisations for `Object.assign()` * RegExp `v` flag support * Improved JSON parsing to help avoid garbage collection time when parsing very large files * The `String.prototype.isWellFormed()` and `String.prototype.toWellFormed()` methods respectively can be used to check if a string contains well-formed Unicode text (i.e. contains no lone surrogates) and sanitise an ill-formed string to well-formed Unicode text. * The `Object.groupBy()` and `Map.groupBy()` static methods for grouping the elements of an iterable are now supported * `Date.parse()` now accepts several additional date formats: * Year > 9999 for `YYYY-MMM-DD` format (e.g. `19999-Jan-01`) * `MMM-DD-YYYY` (e.g. `Jan-01-1970`) * Milliseconds for non-ISO date formats (e.g. `Jan 1 1970 10:00:00.050`) * Day of week at the beginning of formats which were being rejected, such as: * `Wed, 1970-01-01` * `Wed, 1970-Jan-01` * The day of week does not need to be correct, or a day of week at all; for example, `foo 1970-01-01` works. * Numeric dashed dates which do not meet the formal ISO standard are now accepted, including: * `"01-12-1999"` (month first) * `"1999-1-5"` (single-digit month or day) * `"10000-01-12"` (year > 9999) * `"99-01-05"` or `"01-05-99"` (2-digit year, year must be >31 if it comes first) * `"1999-01-05 10:00:00"` (space between date and time). These dates will be parsed with behavior typical of other non-ISO dates, such as local time zone and month rollover (April 31 rolls over to May 1 since April 31 doesn’t exist). * Requirements for characters directly following numbers have been loosened to accept new formats, including: * `"DDMonYYYY"` * `"Mon.DD.YYYY"` * `"DD.Mon.YYYY"` * `"YYYY.MM.DD"` * `"Mon DD YYYY hh:mmXm"` (`am`/`pm` directly following time) * Timezone `'Z'` is now accepted for non-ISO formats (e.g. `Jan 1 1970 10:00Z`) * Other `Date.parse()` fixes: * `YYYY-M-DD` and `YYYY-MM-D` are no longer assumed GMT as an ISO date `YYYY-MM-DD` would be. * Milliseconds for all formats are truncated after 3 digits, rather than being rounded. * The `Promise.withResolvers()` static method is now supported. This exposes the `resolve` and `reject` callback functions in the same scope as the returned `Promise`, allowing code that resolves or rejects the promise to be defined after its construction. * The `ArrayBuffer.prototype.transfer()` and `ArrayBuffer.prototype.transferToFixedLength()` methods can now be used to transfer ownership of memory from one ArrayBuffer to another. After transfer, the original buffer is detached from its original memory and hence unusable; the state can be checked using `ArrayBuffer.prototype.detached`. ## 3.11.0 (2024-03-14) ### Added * add new flag --experimental-enable-top-level-await ([#742](https://github.com/fastly/js-compute-runtime/issues/742)) ([437a20d](https://github.com/fastly/js-compute-runtime/commit/437a20d5f970c00d382673dbf223149b5b20ed37)) ### Fixed * correct type definition of Headers.prototype.values() to indicate it returns an IterableIterator\ ([#740](https://github.com/fastly/js-compute-runtime/issues/740)) ([8959e79](https://github.com/fastly/js-compute-runtime/commit/8959e79a9a7856b0ecc74b33264042c54ac8f867)) ## 3.10.0 (2024-03-09) ### Added * add fastly:device module which allows applications to detect a device based on a user-agent ([#738](https://github.com/fastly/js-compute-runtime/issues/738)) ([5274fd5](https://github.com/fastly/js-compute-runtime/commit/5274fd5280d80b276e6f13d4acbdefc435af6c57)) ### Fixed * correct title for the CoreCache.transactionLookup documentation page ([9892d90](https://github.com/fastly/js-compute-runtime/commit/9892d9074d9a1bd25b9b5db28c12a940f2aac028)) ## 3.9.1 (2024-03-04) ### Fixed * ensure we associate correct memory for the user\_metadata attached to a cache item ([#734](https://github.com/fastly/js-compute-runtime/issues/734)) ([550c4f5](https://github.com/fastly/js-compute-runtime/commit/550c4f5502e710f0b7cf11d0132270bcc91e7235)) ## 3.9.0 (2024-03-02) ### Added * Add a EdgeRateLimiter JavaScript Class which enables edge-rate-limiting by utilising a RateCounter and a PenaltyBox instance ([#732](https://github.com/fastly/js-compute-runtime/issues/732)) ([4e81fc7](https://github.com/fastly/js-compute-runtime/commit/4e81fc7dbec33a5a90743e389642e0ced5294ff1)) * Add a PenaltyBox JavaScript Class which can be used standalone for adding and checking if an entry is in the penalty-box ([#731](https://github.com/fastly/js-compute-runtime/issues/731)) ([bfe1e15](https://github.com/fastly/js-compute-runtime/commit/bfe1e15460cb2aa0da3cfa356fbf23d38f5af5ba)) * Add a RateCounter JavaScript Class which can be used standalone for counting and rate calculations ([#730](https://github.com/fastly/js-compute-runtime/issues/730)) ([0f6036f](https://github.com/fastly/js-compute-runtime/commit/0f6036f02f497345df01dbce731eb502fd406d27)) * implement and expose JavaScript classes for Fastly's Compute Core Cache feature set ([#566](https://github.com/fastly/js-compute-runtime/issues/566)) ([94f4038](https://github.com/fastly/js-compute-runtime/commit/94f4038df7ca2bfd8beef964865eb7f900b1bc04)) ### Fixed * disable the portable-baseline-tier for async functions for now ([#733](https://github.com/fastly/js-compute-runtime/issues/733)) ([4928243](https://github.com/fastly/js-compute-runtime/commit/4928243a380adfb6073a909e41ab7eb4c0d569b4)) ## 3.8.3 (2024-02-21) ### Fixed * do not use colon character in types for windows support ([#726](https://github.com/fastly/js-compute-runtime/issues/726)) ([25bf1a2](https://github.com/fastly/js-compute-runtime/commit/25bf1a2bb40528bf02e0773e6bc624560a12869a)) ## 3.8.2 (2024-01-25) ### Fixed * ensure we honor first-byte-timeout and between-bytes-timeout for dynamically registered backends ([#719](https://github.com/fastly/js-compute-runtime/issues/719)) ([2851507](https://github.com/fastly/js-compute-runtime/commit/2851507f9ca00a3f272a13c174a2906163f95c40)) * If request does not have a static backend defined, return `undefined` for the Request.prototype.backend getter ([#722](https://github.com/fastly/js-compute-runtime/issues/722)) ([251c037](https://github.com/fastly/js-compute-runtime/commit/251c037f424ace09e87ec0a47d7579d7b90626a1)) ## 3.8.1 (2024-01-17) ### Fixed * parse latin-1 encoded field values correctly ([#715](https://github.com/fastly/js-compute-runtime/issues/715)) ([9ebb524](https://github.com/fastly/js-compute-runtime/commit/9ebb524d4eef97ba71ae19ee1c2b1e61f3fd391c)) ## 3.8.0 (2024-01-11) ### Added * Add `manualFramingHeaders` on `RequestInit` and `ResponseInit`, and add `Request.prototype.setManualFramingHeaders` and `Response.prototype.setManualFramingHeaders` ([#705](https://github.com/fastly/js-compute-runtime/pull/705)) * Add `Request.prototype.backend` getter to return the name of the backend assigned to the request ([9c750e5](https://github.com/fastly/js-compute-runtime/commit/9c750e5697bb02676762225e4fdc7589d23e13d9)) * Allow URL as input on fetch() on TypeScript typings for compat with Node.js ([#707](https://github.com/fastly/js-compute-runtime/issues/707)) ([4f39943](https://github.com/fastly/js-compute-runtime/commit/4f399434c0959e902df03262dfceefdc16592afe)) ## 3.7.3 (2023-11-02) ### Fixed * Make the underlying KVStore.prototype.get implementation be async ([a6a5035](https://github.com/fastly/js-compute-runtime/commit/a6a5035fc932be0e47c7c737bd9060d27c18ab05)) ## 3.7.2 (2023-10-25) ### Fixed * Make Response.redirect headers be immutable ([3527eaf](https://github.com/fastly/js-compute-runtime/commit/3527eaf62266a3cf7ea8ea4020bb5980bb7fa615)) * Return correct error type (TypeError or RangeError instead of Error) in Request and Response methods ([4ea7de7](https://github.com/fastly/js-compute-runtime/commit/4ea7de71301d841fdc99f45a3251f85c61710fd6)) ## 3.7.1 (2023-10-24) ### Added * Add type defintions for the recently added Backend methods ([#698](https://github.com/fastly/js-compute-runtime/issues/698)) ([24f1ba7](https://github.com/fastly/js-compute-runtime/commit/24f1ba70e68f35205104eaf583c29d4af9b5039c)) ## 3.7.0 (2023-10-14) ### Added This release of `@fastly/js-compute` includes 4 new methods to the Backend class, which enable the Fastly Service to retrieve information about any backend, this is particularly useful for checking if the backend is “healthy”. ([#523](https://github.com/fastly/js-compute-runtime/issues/523)) ([08f816a](https://github.com/fastly/js-compute-runtime/commit/08f816ae4465316a2316467338e0d33ffbd20e7a)) The new methods are: * Backend.exists(name) - Check whether a backend with the given name exists for the Fastly Service. * Backend.fromName(name) - Check whether a backend with the given name exists for the Fastly Service and if it does, then returns an instance of Backend for the given name. * Backend.health(name) - Returns the health of the backend with the given name. * Backend.prototype.toName() - Return the name for the Backend instance. ### Fixed * bring back support for build-time env vars ([#691](https://github.com/fastly/js-compute-runtime/issues/691)) ([c044ac4](https://github.com/fastly/js-compute-runtime/commit/c044ac4bbbd5629bfc879b7593a0bfa9c5e3cfcb)) * raise an error during wizening for async functions given to addEventListener ([#689](https://github.com/fastly/js-compute-runtime/issues/689)) ([e6747a2](https://github.com/fastly/js-compute-runtime/commit/e6747a28d70d71bc71da77c9b6e44848b95ea387)) ## 3.6.2 (2023-10-05) ### Fixed * improve fetch error messages ([58ddb20](https://github.com/fastly/js-compute-runtime/commit/58ddb2012f9bff5ad59fb6420bfa31051109a108)) ## 3.6.1 (2023-09-27) ### Fixed * ensure we throw an error when trying to base64 decode \_ via `atob` ([1b2b2f9](https://github.com/fastly/js-compute-runtime/commit/1b2b2f9d807780cf03964a30801644c8bc3b698b)) ## 3.6.0 (2023-09-22) ### Added * add support for ECDSA keys to be used with SubtleCrypto.prototype.sign and SubtleCrypto.prototype.verify ([#667](https://github.com/fastly/js-compute-runtime/issues/667)) ([51bb170](https://github.com/fastly/js-compute-runtime/commit/51bb1703fb81fddac24b152fc7b1e0f32f976de5)) ## 3.5.0 (2023-09-19) ### Added * implement the "fastly" condition ([#660](https://github.com/fastly/js-compute-runtime/issues/660)) ([db7db46](https://github.com/fastly/js-compute-runtime/commit/db7db46266b022afffd351421f56d5d5f7b98a53)) JavaScript dependencies can now target our JavaScript runtime for Fastly Compute explicitly via the recently added “fastly” WinterCG Runtime Key This release updates our internal bundling system to include this functionality Note: If you are using a custom bundling system for your JavaScript projects and want this functionality, you will need to update/configure your bundling system ## 3.4.0 (2023-09-13) ### Added * add ability to import ECDSA JWK keys via crypto.subtle.importKey ([#639](https://github.com/fastly/js-compute-runtime/issues/639)) ([c16b001](https://github.com/fastly/js-compute-runtime/commit/c16b001bddc2dc122c26837023ab9c53664adf8a)) ## 3.3.5 (2023-09-11) ### Changed * use new host\_api implementation for transactional lookups and inserts ([#651](https://github.com/fastly/js-compute-runtime/issues/651)) ([8c29246](https://github.com/fastly/js-compute-runtime/commit/8c292466e1fef61673ad3d46b747a6c54ed71ddb)) ## 3.3.4 (2023-09-07) ### Fixed * Fix SimpleCache API by reverting host\_api implementation of the underlying cache apis ([4340375](https://github.com/fastly/js-compute-runtime/commit/4340375409be382c2faec657615c187d99d1fc7e)) ## 3.3.3 (2023-09-05) ### Fixed * remove unused lines of code from docs for SimpleCache/get.mdx ([51fd4af](https://github.com/fastly/js-compute-runtime/commit/51fd4af94f72dd9ae112a967ef05bc67d02f202c)) * update to latest version of gecko-dev which fixes a bug with the default ecma262 sorting algorithm ([#643](https://github.com/fastly/js-compute-runtime/issues/643)) ([64323e3](https://github.com/fastly/js-compute-runtime/commit/64323e344bc61d4cc52e34710ab7ae208d56e321)) ## 3.3.2 (2023-08-31) ### Added * Add documentation for Request.prototype.clone() ([9d12321](https://github.com/fastly/js-compute-runtime/commit/9d12321bf3da019f6383389098625ca1314d9fb8)) ## 3.3.1 (2023-08-24) ### Changed * update to spidermonkey which includes async resume support when using pbl ([#634](https://github.com/fastly/js-compute-runtime/issues/634)) ([1dea60f](https://github.com/fastly/js-compute-runtime/commit/1dea60f79fc07828785b12fd8a5bf13b3602f88b)) ## 3.3.0 (2023-08-22) ### Added * Add option to enable PBL. ([#628](https://github.com/fastly/js-compute-runtime/issues/628)) ([6ecda6e](https://github.com/fastly/js-compute-runtime/commit/6ecda6e89971f178f623e242d8dd6a8fd25ab63f)) ## 3.2.1 (2023-08-16) ### Fixed * Add documentation and type definitions for the new event.client.\* fields ([#625](https://github.com/fastly/js-compute-runtime/issues/625)) ([a6f557b](https://github.com/fastly/js-compute-runtime/commit/a6f557ba1b03035869e4c4fb3d9679fb3e28fd1f)) ## 3.2.0 (2023-08-10) ### Added * add ability to automatically decompress gzip responses returned from `fetch` ([#497](https://github.com/fastly/js-compute-runtime/issues/497)) ([e08d060](https://github.com/fastly/js-compute-runtime/commit/e08d060535160b8c934f60f37d8f4a71f412f0c4)) ### Changed * use spidermonkey version 115 ([4a4716d](https://github.com/fastly/js-compute-runtime/commit/4a4716d99fa1e263eae9cf5d7fcc96999519c7fe)) * reduce memory usage by caching client getters when they are first called ([87ee0cb](https://github.com/fastly/js-compute-runtime/commit/87ee0cb54edab82c0b2f6b986458d2552a8dbcba)) * update to latest url crate which passes some more wpt url tests ([f0a42fd](https://github.com/fastly/js-compute-runtime/commit/f0a42fd07821190e1ebf66c95762cb8e26b69e8b)) ## 3.1.1 (2023-07-14) ### Fixed * Request.prototype.clone - Do not create a body on the new request if the request instance being cloned does not contain a body ([5debe80](https://github.com/fastly/js-compute-runtime/commit/5debe806a4a40e0d3b07bdd6b71489aa7d739cff)) ## 3.1.0 (2023-07-12) ### Added * Add ability to disable connection-pooling behavior for Dynamic Backends ([#574](https://github.com/fastly/js-compute-runtime/issues/574)) ([718bea8](https://github.com/fastly/js-compute-runtime/commit/718bea8e2b950bc00c43187e479a7a7de41eaa70)) ### Changed * Deprecate SimpleCache.set and recommend SimpleCache.getOrSet as the alternative ([bff1bf5](https://github.com/fastly/js-compute-runtime/commit/bff1bf587c7de6012c617745b059dea24e6299ad)) ## 3.0.0 (2023-07-08) ### Changed *⚠ BREAKING CHANGE* * Rename SimpleCache.delete to SimpleCache.purge and require purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using SimpleCache.delete to SimpleCache.purge with the same behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ### Added * add event.client.tlsCipherOpensslName ([49b0c99](https://github.com/fastly/js-compute-runtime/commit/49b0c99523147998304dc559b836bcc79008e8b0)) * add event.client.tlsClientCertificate ([cf93b62](https://github.com/fastly/js-compute-runtime/commit/cf93b6226b01ca653688571ed0db27e0f6d39bc2)) * add event.client.tlsClientHello ([3d87cb2](https://github.com/fastly/js-compute-runtime/commit/3d87cb28a670735441a0d8c6d16291867c8f2244)) * add event.client.tlsJA3MD5 ([2ecf4af](https://github.com/fastly/js-compute-runtime/commit/2ecf4afcc503e60a1aa972c88d47149b22dbf70c)) * add event.client.tlsProtocol ([4c91142](https://github.com/fastly/js-compute-runtime/commit/4c9114213343d4dea2a1ac2955980e19540a4463)) * Rename SimpleCache.delete to SimpleCache.purge and require purge options to be supplied as the second parameter ([20113c1](https://github.com/fastly/js-compute-runtime/commit/20113c1df6ad57a98c5b8c27b06d67117d2029ef)) ## 2.5.0 (2023-07-05) ### Added * add DOMException class ([58b8086](https://github.com/fastly/js-compute-runtime/commit/58b8086edce2d93928743aec462843df369d458b)) * Add support for HMAC within SubtleCrypto implementation ([96ac02d](https://github.com/fastly/js-compute-runtime/commit/96ac02d1e62b6d34f73a18ba3be30266a4b0f27e)) ### Changed * update types for SubtleCrypto to show we support a subset of importKey/sign/verify ([#568](https://github.com/fastly/js-compute-runtime/issues/568)) ([329b733](https://github.com/fastly/js-compute-runtime/commit/329b733e77d4bcb2b341eb1e1b36a5d6a7c999cc)) ## 2.4.0 (2023-06-22) ### Changed * Update to SpiderMonkey version 114.0.1 ([#563](https://github.com/fastly/js-compute-runtime/issues/563)) ([03e2254](https://github.com/fastly/js-compute-runtime/commit/03e22542cd439990ad530eb1958a12ce8ab85120)) ## 2.3.0 (2023-06-12) ### Added * implement web performance api ([ddfe11e](https://github.com/fastly/js-compute-runtime/commit/ddfe11ec92a48495edd920e48ffad3d20e69c159)) ## 2.2.1 (2023-06-09) ### Fixed * only apply our pipeTo/pipeThrough optimisations to TransformStreams who have no transformers (IdentityStreams). ([#556](https://github.com/fastly/js-compute-runtime/issues/556)) ([a88616c](https://github.com/fastly/js-compute-runtime/commit/a88616c7a5aa4e13d3f1eeef259ba7480416f3f0)) ## 2.2.0 (2023-06-08) ### Added * Implement SimpleCache.getOrSet method ([a1f4517](https://github.com/fastly/js-compute-runtime/commit/a1f4517e5e377354254ee2a635f97a562c87e13c)) ## 2.1.0 (2023-06-02) ### Added * Implement a SimpleCache Class ([#548](https://github.com/fastly/js-compute-runtime/issues/548)) ([865382d](https://github.com/fastly/js-compute-runtime/commit/865382df3a74832abce1f0d40e3627d8339b4aeb)) ## 2.0.2 (2023-06-01) ### Fixed * add fastly:secret-store types ([3805238](https://github.com/fastly/js-compute-runtime/commit/38052381331999d00b6f2cc878ae41c51068ff94)) * update to the latest wizer which brings support for prebuilt linux s390x and aarch64 wizer binaries ([69484c2](https://github.com/fastly/js-compute-runtime/commit/69484c25465a2674513f83f8c9674e1857e01cb9)) ## 2.0.1 (2023-05-24) ### Fixed * When using implicit backends with https protocol, use the hostname for the sni hostname value to match `fetch` behaviour in browsers and other runtimes ([84fb6a2](https://github.com/fastly/js-compute-runtime/commit/84fb6a2fa57408fb13e9319da91d6de3533f1e3c)) ## 2.0.0 (2023-05-15) ### Changed * Object Store renamed to KV Store ([#476](https://github.com/fastly/js-compute-runtime/issues/476)) We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ## 1.13.0 (2023-05-11) ### Added * Implement all the web console methods ([#522](https://github.com/fastly/js-compute-runtime/issues/522)) ([a12a1d3](https://github.com/fastly/js-compute-runtime/commit/a12a1d35f0b68c549d802ea2df87eb5bd5a1cd31)) ## 1.12.0 (2023-05-11) ### Added * Implement Fanout for JS SDK ([5198884](https://github.com/fastly/js-compute-runtime/commit/5198884d35c616785399d1702efa2454f9303421)) ## 1.11.2 (2023-04-27) ### Fixed * Add TypeScript definitions for Response.redirect() and Response.json() ([#512](https://github.com/fastly/js-compute-runtime/issues/512)) ([ebe429f](https://github.com/fastly/js-compute-runtime/commit/ebe429fc895f8da837e47393ebc35fe6dec5159a)) ## 1.11.1 (2023-04-26) ### Fixed * **TextDecoder:** add (nearly) full support for TextDecoder and TextEncoder ([#501](https://github.com/fastly/js-compute-runtime/issues/501)) ([a4c312e](https://github.com/fastly/js-compute-runtime/commit/a4c312e62284147da73d82323ac095670d41cdf3)) ## 1.11.0 (2023-04-25) ### Added * implement Response.json static method ([#499](https://github.com/fastly/js-compute-runtime/issues/499)) ([780067d](https://github.com/fastly/js-compute-runtime/commit/780067d429dbd90bd529f42169c2c1af6c139bb7)) ## 1.10.1 (2023-04-24) ### Fixed * Fix for `ReferenceError: pattern is not defined` ([#506](https://github.com/fastly/js-compute-runtime/issues/506)) ([107c9be](https://github.com/fastly/js-compute-runtime/commit/107c9be4c0b0c41c4d630ba556a10b697a1508f4)) ## 1.10.0 (2023-04-21) ### Added * Add MD5 support into crypto.subtle.digest ([9c8efab](https://github.com/fastly/js-compute-runtime/commit/9c8efabc89c20e5e20f8ef429b555c1d85fe0db1)) * implement Response.redirect static method and Response.prototype.redirected getter ([1623d74](https://github.com/fastly/js-compute-runtime/commit/1623d740405dcaaa5a8c946981c6840ab611c36a)) ## 1.9.0 (2023-04-15) ### Added * Implement subset of crypto.subtle.importKey which can import a JSONWebKey using RSASSA-PKCS1-v1\_5 ([b66bf50](https://github.com/fastly/js-compute-runtime/commit/b66bf506a9bf25cf251f7c58a34ba2e1a0e68c5d)) * Implement subset of crypto.subtle.sign which can sign data with a JSONWebKey using RSASSA-PKCS1-v1\_5 ([800fb66](https://github.com/fastly/js-compute-runtime/commit/800fb666aca957a62d79dbf4fefa35aad8212de5)) * Implement subset of crypto.subtle.verify which can verify a signature with a JSONWebKey using RSASSA-PKCS1-v1\_5 ([077adfd](https://github.com/fastly/js-compute-runtime/commit/077adfd16f870564e945d14e4caf0c21762c64f1)) ### Fixed * free `buf` if an error has occured ([bfa84cc](https://github.com/fastly/js-compute-runtime/commit/bfa84cc4fa22c1d2ea860cad597dd25878a24e20)) ## 1.8.1 (2023-04-12) ### Fixed * Mark NodeJS 19 and 20 as supported ([#492](https://github.com/fastly/js-compute-runtime/issues/492)) ([27b3428](https://github.com/fastly/js-compute-runtime/commit/27b34289988b6ef55ea3ce703b878dbd1da68d7a)) ## 1.8.0 (2023-04-12) ### Added * Add high-resolution timing function "fastly.now()" behind feature flag "--enable-experimental-high-resolution-time-methods" ([f090838](https://github.com/fastly/js-compute-runtime/commit/f0908384d48d0bc2e5c29083e8a20bed041d47ed)) ### Changed * replace tree-sitter with acorn + magic string ([08a0695](https://github.com/fastly/js-compute-runtime/commit/08a0695a00088fe51c289ea783a771b4f3b993f8)) ## 1.7.1 (2023-04-11) ### Fixed * Lower the supported NodeJS version from 18 or greater to only 18 ([5cc1cd6](https://github.com/fastly/js-compute-runtime/commit/5cc1cd6e5bfb8926944457e81c045682b0a37e4c)) * When converting a URL to a string, do not add a `?` if there are no query string parameters ([73cdc27](https://github.com/fastly/js-compute-runtime/commit/73cdc279fa8c038a012c050000960577dda21280)) ## 1.7.0 (2023-04-11) ### Added * BYOB streams, basic usage, *pending WPT* ([ab97e75](https://github.com/fastly/js-compute-runtime/commit/ab97e75e3b595911432327b35fcf4716675a0dd0)) * Implement subset of crypto.subtle.importKey which can import a JSONWebKey using RSASSA-PKCS1-v1\_5 ([#472](https://github.com/fastly/js-compute-runtime/issues/472)) ([110e7f4](https://github.com/fastly/js-compute-runtime/commit/110e7f42c1a86c4b4b722ea4b6780bb68f7f4523)) ## 1.6.0 (2023-03-28) ### Added * Implement JS CryptoKey Interface ([adb31f7](https://github.com/fastly/js-compute-runtime/commit/adb31f7197acf869af1852c0656847e4ab240089)) ## 1.5.2 (2023-03-23) ### Fixed * Add documentation for FetchEvent, FetchEvent.prototype.respondWith, and FetchEvent.prototype.waitUntil ([78e6d92](https://github.com/fastly/js-compute-runtime/commit/78e6d925d1ec6cdedd4f2678997e333aba9ebae6)) * fix typo in geolocation example ([f53a06e](https://github.com/fastly/js-compute-runtime/commit/f53a06ecb46c5ad1f91806c1c13ce6215a254192)) ## 1.5.1 (2023-03-10) ### Fixed * handle fallthrough of regex parser bugs ([#447](https://github.com/fastly/js-compute-runtime/issues/447)) ([8f38980](https://github.com/fastly/js-compute-runtime/commit/8f389805d6a88e476f0281df974cb971d7e78896)) ## 1.5.0 (2023-03-10) ### Added * support unicode patterns via precompilation ([87a0dce](https://github.com/fastly/js-compute-runtime/commit/87a0dce62115cfd6d665f1d2aa617cf53a8b6b01)) ## 1.4.2 (2023-03-09) ### Fixed * console logging support improvements ([#434](https://github.com/fastly/js-compute-runtime/issues/434)) ([7a74d76](https://github.com/fastly/js-compute-runtime/commit/7a74d76ed1d03c1c588caf664f471eab226c10a6)) ## 1.4.1 (2023-03-01) ### Changed * modular builtin separation ([#426](https://github.com/fastly/js-compute-runtime/issues/426)) ([c5933ea](https://github.com/fastly/js-compute-runtime/commit/c5933ea2599c0f0952d7314ecbbe93faa8ec9acb)) ## 1.4.0 (2023-02-27) ### Added * implement fastly:secret-store package ([cde22e3](https://github.com/fastly/js-compute-runtime/commit/cde22e3fa232b50e96222301ba40dda5b424bb60)) ### Changed * Bump to spidermonkey 110, and viceroy 0.3.5 ([#420](https://github.com/fastly/js-compute-runtime/issues/420)) ([e17cdfd](https://github.com/fastly/js-compute-runtime/commit/e17cdfda1878fe23a7f331fb20d33c52d580003b)) ## 1.3.4 (2023-02-09) ### Changed * add custom error message when making a request to a backend which does not exist ([#412](https://github.com/fastly/js-compute-runtime/issues/412)) ([486aed1](https://github.com/fastly/js-compute-runtime/commit/486aed1415151a2bba40b736c14555c692bd095a)) ## 1.3.3 (2023-02-08) ### Changed * Remove error codes from external error messaging as these codes are not documented anywhere and subject to change ([8f8f0ef](https://github.com/fastly/js-compute-runtime/commit/8f8f0eff871597b8453fac08b6b114ee5c188ef6)) ## 1.3.2 (2023-01-30) ### Changed * allow a downstream response to contain lots of headers with the same name without crashing ([ba1f0e6](https://github.com/fastly/js-compute-runtime/commit/ba1f0e6699bd0f218fa581b9aad0fdda89a674fc)) ## 1.3.1 (2023-01-26) ### Changed * ensure CacheOverride bitflags are the same value as defined in c-at-e ([#386](https://github.com/fastly/js-compute-runtime/issues/386)) ([8a1c215](https://github.com/fastly/js-compute-runtime/commit/8a1c2158505e8ed1ebb424fc97866da155601d1f)) ## 1.3.0 (2023-01-24) ### Added * implement SubtleCrypto.prototype.digest method ([#372](https://github.com/fastly/js-compute-runtime/issues/372)) ([bbe1754](https://github.com/fastly/js-compute-runtime/commit/bbe1754f0a8018f2124b9a5859a35fde5c4cbb97)) ## 1.2.0 (2023-01-17) ### Added * implement Request.prototype.clone ([3f3a671](https://github.com/fastly/js-compute-runtime/commit/3f3a67199c27ea4500fa861a993163e5d376aafd)) ## 1.1.0 (2023-01-06) ### Added * add crypto.randomUUID function ([2c32b42](https://github.com/fastly/js-compute-runtime/commit/2c32b42d29a1cd2de961a0cef175b96eaab4ae7d)) ### Changed * check that setTimeout/setInterval handler is an object before casting to an object ([62476f5](https://github.com/fastly/js-compute-runtime/commit/62476f5324425c4f4a12ebf4f8ceddb093b753de)) * ensure retrieving the property definitions of ObjectStoreEntry.prototype.body and ObjectStoreEntry.bodyUsed do not cause panics by ensuring we have a valid entry in their Slots ([311b84c](https://github.com/fastly/js-compute-runtime/commit/311b84c80cbc99cf534ed43f4499a291716068fd)) * error message is latin1, we need to use JS\_ReportErrorLatin1 to convert the message from latin1 to UTF8CharsZ, otherwise a panic occurs ([f1a22a4](https://github.com/fastly/js-compute-runtime/commit/f1a22a42c75aea99f47f5f6b44920275735c91e1)) ## 1.0.1 (2022-12-16) ### Changed * do not free the method\_str.ptr as we still require the memory ([17c5049](https://github.com/fastly/js-compute-runtime/commit/17c50492d6247e746daeb65ab1b7fdeeaec0ae91)), closes [#352](https://github.com/fastly/js-compute-runtime/issues/352) ## 1.0.0 (2022-12-14) ### Added * implement validation for backend cipher definitions ([157be64](https://github.com/fastly/js-compute-runtime/commit/157be64e84956d24259003331cb51a8c5acec040)) ## 0.7.0 (2022-12-10) ### Added * compute runtime component build ([#326](https://github.com/fastly/js-compute-runtime/issues/326)) ([197504c](https://github.com/fastly/js-compute-runtime/commit/197504c4192e019264011d732a7009786a7a38d0)) #### BREAKING CHANGES * compute runtime component build ([#326](https://github.com/fastly/js-compute-runtime/issues/326)) ### Changed * Limit to node 16/17/18 as some dependencies do not work on node19 yet ([0d48f77](https://github.com/fastly/js-compute-runtime/commit/0d48f77467fc0c85c837c36b2e3991a2f6b35bcf)) ## 0.6.0 (2022-12-09) ### Added * Disable JS iterator helpers as the feature is at Stage 3 and we should only enable by default Stage 4 features ([c90c145](https://github.com/fastly/js-compute-runtime/commit/c90c14570a0375692da62eb11811e01babe28de8)) ### Changed * Throw TypeErrors in config-store if supplied with invalid parameters or the config-store does not exist ([6b70180](https://github.com/fastly/js-compute-runtime/commit/6b70180560b0c28bbc009af49fa7b25bd890d4a2)) ### Removed * Disable JS iterator helpers as the feature is at Stage 3 and we should only enable by default Stage 4 features ## 0.5.15 (2022-12-08) ### Added * add `allowDynamicBackends` function to `fastly:experimental` module ([83a003e](https://github.com/fastly/js-compute-runtime/commit/83a003e17307c01876751686620a6a1effbfaa99)) * upgrade from SpiderMonkey 96 to SpiderMonkey 107 ([#330](https://github.com/fastly/js-compute-runtime/pull/330)) ## 0.5.14 (2022-12-07) ### Changed * when appending headers, if the set-cookie header is set then make sure that each cookie value is sent as a separate set-cookie header to the host ([f6cf559](https://github.com/fastly/js-compute-runtime/commit/f6cf5597ec646717534b59a1002b6a6364a81065)) ## 0.5.13 (2022-12-02) ### Changed * implement validation for Dictionary names and keys ([c0b0822](https://github.com/fastly/js-compute-runtime/commit/c0b082245d9585d8c3cdbc83c6f8ebf1844e8741)) * fix: When streaming a response to the host, do not close the response body if an error occurs ([8402ecf](https://github.com/fastly/js-compute-runtime/commit/8402ecf93c91bee66217c401a5cc5954e2e71de6)) ## 0.5.12 (2022-11-30) ### Added * add fastly:experimental module which contains all our experimental functions such as includeBytes and enableDebugLogging ([5c6a5d7](https://github.com/fastly/js-compute-runtime/commit/5c6a5d7cf13274f4752fa398d9bc92de658004b8)) ## 0.5.11 (2022-11-30) ### Changed * update nodejs supported versions to 16 - 19 and npm supported version to only 8 ([5ec70b9](https://github.com/fastly/js-compute-runtime/commit/5ec70b95b0d4d3677a522120c9ae5f9a2cea4db6)) ## 0.5.10 (2022-11-30) ### Changed * ensure custom cache keys are uppercased ([f37920d](https://github.com/fastly/js-compute-runtime/commit/f37920d01f5fb9a172ae82a1d6191159be59f561)), closes [#318](https://github.com/fastly/js-compute-runtime/issues/318) ## 0.5.9 (2022-11-29) ### Added * add fastly:cache-override module ([f433464](https://github.com/fastly/js-compute-runtime/commit/f433464928e70a8f38ecb4dd293cb2ce40098c34)) * add geo ip lookup function to fastly:geolocation ([24601e5](https://github.com/fastly/js-compute-runtime/commit/24601e5738816ce1597f80d054d312c1a95e4398)) * Add Logger constructor to "fastly:logger" module ([b4818a2](https://github.com/fastly/js-compute-runtime/commit/b4818a2623caaab0fe568c35f7636d0d3d9e8bc7)) * expose fastly loggers via fastly:logger module ([2d0bcfe](https://github.com/fastly/js-compute-runtime/commit/2d0bcfe4f4e0fd855f589205eee4316d829fd28c)) * expose the fastly features via 'fastly:' namespaced modules ([c06cd16](https://github.com/fastly/js-compute-runtime/commit/c06cd1677cd96b383284ea6ab6dbcbbc4f6dfcf4)) * move env function into fastly:env ([327b344](https://github.com/fastly/js-compute-runtime/commit/327b344dc943a53ca4a74aeb16207f02cd6d0b3c)) ### Changed * Add types for setTimeout, clearTimeout, setInterval, clearInterval ([c1ed00c](https://github.com/fastly/js-compute-runtime/commit/c1ed00c8933bc45c9ba8dc84e515d31167596aa6)) ## 0.5.8 (2022-11-28) ### Changed * Allow process.execPath to contain whitespace ([caefe51](https://github.com/fastly/js-compute-runtime/commit/caefe512413675f10a7f1e6501249b3ebe7f5d21)) ## 0.5.7 (2022-11-24) ### Changed * add missing shebang and executable bit to the binary file ([3f0cd69](https://github.com/fastly/js-compute-runtime/commit/3f0cd69e3ec39633f747f0346ae3eda5eb3f3685)) ## 0.5.6 (2022-11-24) ### Added * implement setTimeout, setInterval, clearTimeout, and clearInterval ([128bca9](https://github.com/fastly/js-compute-runtime/commit/128bca901c9ad4b6d6c1084bf13c5c474ef63a41)) ## 0.5.5 (2022-11-23) ### Added * implement Request.prototype.setCacheKey ([457eabe](https://github.com/fastly/js-compute-runtime/commit/457eabe392f44eb296ce593bcabebffb68c57371)) * implement support in Response.json/text/arrayBuffer methods for guest provided streams ([50cdc44](https://github.com/fastly/js-compute-runtime/commit/50cdc443d38e53f029fbcc1ad19ee56b5849dff0)) ### Changed * respond with 500 Internal Server Error when an unhandled error has occured and no response has already been sent to the client ([e5982d8](https://github.com/fastly/js-compute-runtime/commit/e5982d879223a8e5940717ab74c9f01a64b35ce2)) ## 0.5.4 (2022-09-28) ### Added * Add ConfigStore class ([#270](https://github.com/fastly/js-compute-runtime/pull/270)) * Add Dynamic Backends support ([#250](https://github.com/fastly/js-compute-runtime/issues/250)) * Improved performance when constructing a ObjectStore instance ([#272](https://github.com/fastly/js-compute-runtime/pull/272) #### Dynamic Backend support Note: This feature is disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. This feature makes it possible to use the standard `fetch` within JavaScript applications. Dynamic Backends is a new feature which enables JavaScript applications to dynamically create new backend server definitions without having to deploy a new version of their Fastly Service. These backends function exactly the same as existing backends, and can be configured in all the same ways as existing backends can via the Fastly Service configuration. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. To enable Dynamic Backends the application will need to set `fastly.allowDynamicBackends` is to `true`. There are two ways to make use of Dynamic Backends within JavaScript projects: The first way is by omitting the `backend` property definition on the Request instance. The JavaScript Runtime will then create a Dynamic Backend definition using default configuration options. This approach is useful for JavaScript applications as it means that a standard `fetch` call will now be possible, which means libraries that use the standard `fetch` will begin to work for applications deployed to Fastly. Below is as an example JavaScript application using the default Dynamic Backend option: ```js // Enable dynamic backends -- warning, this is potentially dangerous as third-party dependencies could make requests to their own backends, potentially including your sensitive/secret data fastly.allowDynamicBackends = true; // For any request, return the fastly homepage -- without defining a backend! addEventListener("fetch", event => { event.respondWith(fetch('https://www.fastly.com/')); }); ``` The second way is by creating a new Dynamic Backend using the new `Backend` class. This approach is useful for JavaScript applications that want to have full control over the configuration of the new backend defintion, such as only allowing TLS 1.3 and disallowing older versions of TLS for requests made to the new backend. E.G. ```js // Enable dynamic backends -- warning, this is potentially dangerous as third-party dependencies could make requests to their own backends, potentially including your sensitive/secret data fastly.allowDynamicBackends = true; // For any request, return the fastly homepage -- without defining a backend! addEventListener("fetch", event => { // We are not defining all the possible fields here, the ones which are not defined will use their default value instead. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", sslMinVersion: 1.3, sslMaxVersion: 1.3, sniHostname: "www.fastly.com", }); event.respondWith(fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the newly defined backend from above. })); }); ``` #### Config-store support and Dictionary deprecated We have renamed the `Dictionary` class to `ConfigStore`, the old name `Dictionary` still exists but is now deprecated. We recommend replacing `Dictionary` with `ConfigStore` in your code to avoid having to migrate in the future when `Dictionary` is fully removed. Below is an example application using the `ConfigStore` class: ```js async function app(event) { const store = new ConfigStore('example') // Retrieve the contents of the 'hello' key const hello = await store.get('hello') return new Response(hello) } addEventListener("fetch", event => { event.respondWith(app(event)) }) ``` ## 0.5.3 (2022-09-16) ### Security * [CVE-2022-39218](https://github.com/fastly/js-compute-runtime/security/advisories/GHSA-cmr8-5w4c-44v8): Fixed `Math.random` and `crypto.getRandomValues` methods to always use sufficiently random values. The previous versions would use a PRNG (pseudorandom number generator) which we would seed with a random value however due to our use of [Wizer](https://github.com/bytecodealliance/wizer), the initial value to seed the PRNG was baked-in to the final WebAssembly module meaning the sequence of numbers generated was predictable for that specific WebAssembly module. The new implementations of both `Math.random` and `crypto.getRandomValues` do not use a PRNG and instead pull random values from WASI (WebAssembly System Interface) libc’s `random_get` function, which is always a sufficiently random value. An attacker with access to the same WebAssembly module that calls the affected methods could use the fixed seed to predict random numbers generated by these functions. This information could be used to bypass cryptographic security controls, for example to disclose sensitive data encrypted by functions that use these generators. Developers should update affected modules after applying this patch. Any secrets generated using affected versions should be rotated. Any sensitive ciphertext generated using affected versions should be considered unsafe, e.g. and be deleted or re-generated. ### Fixed * Updated the Typescript definitions for the `console` methods to indicate that they now accept any number of objects. ([#258](https://github.com/fastly/js-compute-runtime/pull/258)) * Store the Object-Store key string into a native object to avoid it becoming garbage collected before being used within `ObjectStore.prototype.get` or `ObjectStore.prototype.put` (([381242](https://github.com/fastly/js-compute-runtime/commit/3812425a955e52c2fd7229e762ef3e691cb78745)) ## 0.5.2 (2022-09-02) ### Fixed * Explicitly declare void as the return type for functions which return nothing - this allows our package to work with typescript's `strict:true` option ([#253](https://github.com/fastly/js-compute-runtime/pull/253)) * Declare ambient types for our npm package instead of exports as we do not yet export anything from the package ([#252](https://github.com/fastly/js-compute-runtime/pull/252)) ## 0.5.1 (2022-08-31) ### Fixed * Removed `type: "module"` from the @fastly/js-compute package.json file as the package still uses `require` ## 0.5.0 (2022-08-30) ### Added * Implemented ObjectStore and ObjectStoreEntry classes for interacting with Fastly ObjectStore ([#110](https://github.com/fastly/js-compute-runtime/issues/110)) * add btoa and atob native implementations ([#227](https://github.com/fastly/js-compute-runtime/issues/227)) ([8b8c31f](https://github.com/fastly/js-compute-runtime/commit/8b8c31fa9ad70337b1060a3242b8e3495ae47df3)) #### Object-store support This release adds support for Fastly [Object-store](https://developer.fastly.com/reference/api/services/resources/kv-store/), which is globally consistent key-value storage accessible across the Fastly Network. This makes it possible for your Fastly Compute application to read and write from Object-stores. We've added two classes, `ObjectStore`, and `ObjectStoreEntry`. `ObjectStore` is used to interact with a particular Object-store and `ObjectStoreEntry` is a particular value within an Object-store. We've made `ObjectStoreEntry` have a similar API as `Response` to make it simpler to read and write from Object-stores. I.e. `ObjectStoreEntry` has a `body` property which is a `ReadableStream` and has `arrayBuffer`/`json`/`text` methods - just like `Response`. The way to use these classes is best shown with an example: ```js async function app(event) { // Create a connection the the Object-store named 'example-store' const store = new ObjectStore('example-store') // Create or update the 'hello' key with the contents 'world' await store.put('hello', 'world') // Retrieve the contents of the 'hello' key // Note: Object-stores are eventually consistent, this means that the updated contents associated may not be available to read from all // Fastly edge locations immediately and some edge locations may continue returning the previous contents associated with the key. const hello = await store.get('hello') // Read the contents of the `hello` key into a string const hellotext = await hello.text() return new Response(hellotext) } addEventListener("fetch", event => { event.respondWith(app(event)) }) ``` #### Added `btoa` and `atob` global functions These two functions enable you to encode to ([btoa](https://developer.mozilla.org/en-US/docs/Web/API/btoa)) and decode from ([atob](https://developer.mozilla.org/en-US/docs/Web/API/atob)) Base64 strings. They follow the same specification as the `atob` and `btoa` functions that exist in web-browsers. ```js addEventListener("fetch", event => { event.respondWith(new Response(atob(btoa('hello from fastly')))) }) ``` #### Improved Console Support Previously our console methods only supported a single argument and would convert the argument to a string via `String(argument)`, this unfortunately made it difficult to log out complex objects such as Request objects or similar. We've updated our console methods and they now support any number of arguments. As well as supporting any number of arguments, we've also changed the implementation to have better support for logging out complex objects. This is a before and after example of what happens when logging a Request with our console methods. Before: ```js const request = new Request('https://www.fastly.com', {body:'I am the body', method: 'POST'}); console.log(request); // outputs `[object Object]`. ``` After: ```js const request = new Request('https://www.fastly.com', {body:'I am the body', method: 'POST'}); console.log(request); // outputs `Request: {method: POST, url: https://www.fastly.com/, version: 2, headers: {}, body: null, bodyUsed: false}`. ``` ### Changed * Improved console output for all types ([#204](https://github.com/fastly/js-compute-runtime/issues/204)) ## 0.4.0 (2022-07-28) ### Added * Implement the DecompressionStream builtin [`#160`](https://github.com/fastly/js-compute-runtime/pull/160) * Improve performace of Regular Expression literals via precompilation [`#146`](https://github.com/fastly/js-compute-runtime/pull/146) ### Fixed * Calling `tee` on the client request no longer causes the application to hang [`#156`](https://github.com/fastly/js-compute-runtime/pull/156) ## 0.3.0 (2022-06-29) ### Added * Implement the CompressionStream builtin [#84](https://github.com/fastly/js-compute-runtime/pull/84) ### Changed * Removed the requirement for a fastly.toml file to be present when using js-compute-runtimes CLI to compile a WASM file * **Breaking change:** Removed --skip-pkg argument from js-compute-runtime's CLI [#108](https://github.com/fastly/js-compute-runtime/pull/108) * **Breaking change:** Removed `console.trace` method ### Fixed * Fix the response error message text * Throw an error if constructors are called as plain functions * Fix the behavior of `console.debug` * Allow builtin classes to be extended ## 0.2.5 (2022-04-20) ### Changed * Updated the js-compute-runtime to 0.2.5 : Increased max uri length to 8k, and properly forwards http headers to upstream requests even if the headers aren't ever read from ## 0.2.4 (2022-02-09) ### Changed * Support streaming upstream request bodies ## 0.2.2 (2022-02-03) ### Added * Add full support for TransformStreams * Support directly piping Request/Response bodies to other Requests/Responses instead of manually copying every chunk * Add support for the `queueMicrotask` global function * Add support for the `structuredClone` global function * Add support for the `location` global object as an instance of `WorkerLocation` * Support BigUint64Array and BigInt64Array in crypto.getRandomValues * Enable class static blocks syntax * Returned the exit code from the JS Compute Runtime, by passing it up through our CLI ### Changed * Increase max supported header size from 4096 bytes to 69000 bytes * Update to SpiderMonkey 96 beta ### Fixed * Avoid waiting for async tasks that weren't passed to `FetchEvent#waitUntil` * Significantly improve spec-compliance of Request and Response builtins ## 0.2.1 (2021-11-10) ### Added * Updated the js-compute-runtime to `0.2.2` (Which includes fixes to geoip, a way to get environment variables, improves debugging of exceptions in the request handler, and other updates) * Added the `Env` namespace for accessing Fastly Compute environment variables. ## 0.2.0 (2021-08-31) ### Added * Implement the WHATWG URL and URLSearchParam classes * Enable private class fields and methods, plus ergonomic brand checks * Breaking change: Implement FetchEvent#waitUntil * Mark builtins that rely on hostcalls as request-handler-only * Add support for including binary files, and for using typed arrays as Response bodies * Improve handling of hostcall errors ### Fixed * Breaking change: Make FetchEvent handling more spec-compliant * Normalize HTTP method names when constructing Requests * Don't trap when trying to delete a non-existent header * Properly support `base` argument in `URL` constructor ## 0.1.0 (2021-07-28) ### Added * Initial Release * Includes TypeScript type definitions for Fastly Compute flavored ServiceWorkers APIs * Also includes the `js-compute-runtime` CLI for bundling JavaScript applications ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [oss@fastly.com](mailto:oss@fastly.com). All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to the JS Compute Runtime First off thank you for wanting to contribute to making the JS Compute Runtime better! We appreciate you taking time to improve the Fastly Compute experience for developers everywhere. There are many ways you can contribute that include but aren't limited to documentation, opening issues, issue triage, and code contributions. We'll cover some of the ways you can contribute below, but if you don't see instructions for what you want to do, open up an issue and ask us! ## Table of Contents 1. Documentation 1. Feature Requests 1. Bugs 1. Issue Triage 1. Code Contributions ## Documentation Was something in our documentation unclear? Does something have no documentation, but should? This is a perfect way to make an easy contribution to the JS Compute Runtime. If you're not sure what the documentation should contain, please open up an issue! We're happy to guide you with the correct information needed or if you already know what needs to be done, open up a PR and we'll review it for you before merging your changes. ## Feature Requests Do you think there's something the JS Compute Runtime should have that would make the experience better? Feature requests are a great way to let us know. Before opening up a feature request on the issue tracker first make sure that there is no currently open issue asking for the same thing. If there's not, open up an issue asking for what you want and the motivation behind the change. ## Bugs Sometimes you run into issues and the code is not working properly. If you do run into a bug and you can't figure it out or if you do figure out the bug, open up an issue on the issue tracker. Just make sure it's not already an issue that has been filed yet. If you do open up an issue let us know what you expected to happen, what actually happened, what your operating system is, as well as a case we can use to reproduce the issue if you have one! ## Issue Triage Sometimes issues get stale and are no longer an issue, need to be updated, or have been fixed by a PR and were never closed. While we try to stay on top of issues and keep the backlog groomed, we are only human and can miss out on things. If you find that an issue can be closed, ## Code Contributions If you want to contribute code to the JS Compute Runtime thank you! A few things before you do get started adding a change and open up a PR 1. Make sure there's a tracking issue for your code change. We don't want you to do a lot of work only for us to reject the PR because it's a feature change we won't accept for instance. 1. Before opening your PR make sure things are working locally. You can test your resulting `.wasm` files locally using [Fastly's local testing server](https://developer.fastly.com/learning/compute/testing/#running-a-local-testing-server). It also helps to understand how we structure the JS Compute Runtime code base. - Under `src` is the code related to bulding a JS file and the JS runtime iself into a `.wasm` file. - Under `runtime/js-compute-runtime` is the code for the actual JS runtime itself. See below for building the runtime. - The main logic for initializing the JS runtime, reading the JS source code from `stdin`, and evaluating the JS top-level code is in `js-compute-runtime.cpp`. - The various builtins the JS Compute Runtime adds to JS are defined in `js-compute-builtins.cpp`. Thanks again for contributing to the JS Compute Runtime. We really do appreciate you wanting to help out and make it better! ================================================ FILE: DEVELOPMENT.md ================================================ # Fastly Compute JS Runtime The JS Compute Runtime for Fastly's [Compute platform](https://www.fastly.com/products/edge-compute/serverless) provides the environment JavaScript is executed in when using the [Fastly Compute JavaScript SDK](https://www.npmjs.com/package/@fastly/js-compute). **Note**: If you just want to use JavaScript on the Fastly Compute Platform, we recommend using the JavaScript Starter Kits provided by the Fastly CLI tool. For more information please see the [JavaScript documentation on the Fastly Developer Hub](https://developer.fastly.com/learning/compute/javascript/). ## Working with the JS Compute Runtime source Note that this repository uses Git submodules, so you will need to run ```sh git submodule update --recursive --init ``` to pull down or update submodules. ### Building the JS Compute Runtime To build from source, you need to have the following tools installed to successfully build, depending on your system. #### Linux - Build tools ```sh sudo apt install build-essential ``` - Rust ``` curl -so rust.sh https://sh.rustup.rs && sh rust.sh -y restart shell or run source $HOME/.cargo/env ``` - binaryen ```sh sudo apt install binaryen ``` - rust target wasm32-wasip1 ```sh rustup target add wasm32-wasip1 ``` - [cbindgen](https://github.com/eqrion/cbindgen#quick-start) ```sh cargo install cbindgen ``` - [wasi-sdk, version 20](https://github.com/WebAssembly/wasi-sdk/releases/tag/wasi-sdk-20), with alternate [install instructions](https://github.com/WebAssembly/wasi-sdk#install) ```sh curl -sS -L -O https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-20/wasi-sdk-20.0-linux.tar.gz tar xf wasi-sdk-20.0-linux.tar.gz sudo mkdir -p /opt/wasi-sdk sudo mv wasi-sdk-20.0/* /opt/wasi-sdk/ ``` Build the runtime using npm: ```sh npm run build ``` #### macOS (Apple silicon) - Build tools ```sh # First, install Xcode from the Mac App Store. Then: sudo xcode-select --switch /Applications/Xcode.app sudo xcodebuild -license ``` - Homebrew ```sh # From homebrew.sh /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` - wget ```sh brew install wget ``` - binaryen ```sh brew install binaryen ``` - Python ```sh brew install python@3 ``` - Rust ```sh curl -so rust.sh https://sh.rustup.rs && sh rust.sh -y # then, restart shell or run: source $HOME/.cargo/env ``` - rust target wasm32-wasip1 ```sh rustup target add wasm32-wasip1 ``` - [cbindgen](https://github.com/eqrion/cbindgen#quick-start) ```sh cargo install --locked cbindgen ``` - [wasm-tools](https://github.com/bytecodealliance/wasm-tools) ```sh cargo install --locked wasm-tools ``` - [wasi-sdk, version 20](https://github.com/WebAssembly/wasi-sdk/releases/tag/wasi-sdk-20), with alternate [install instructions](https://github.com/WebAssembly/wasi-sdk#install) ```sh curl -sS -L -O https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-20/wasi-sdk-20.0-macos.tar.gz tar xf wasi-sdk-20.0-macos.tar.gz sudo mkdir -p /opt/wasi-sdk sudo mv wasi-sdk-20.0/* /opt/wasi-sdk/ ``` Build the runtime using npm: ```sh npm run build ``` ## Testing a Local build in a Compute application :warning: **You should not use this for production workloads!!!!!!!!** You can test a local build of the JS Compute runtime by installing it in your JavaScript Compute application and running that locally or by uploading it to your Fastly service. 1. First, follow the directions in [Building the JS Compute Runtime](#building-the-js-compute-runtime) for your platform to obtain a local build. The build outputs are the following files: - `fastly.wasm` - `fastly.debug.wasm` - `fastly-weval.wasm` - `fastly-ics.wevalcache` 2. Create a local tarball using npm. ```shell npm pack ``` The resulting tarball will have a filename such as `fastly-js-compute-.tgz`. 3. In your Compute application, install the tarball using `npm`: ```shell npm install /path/to/fastly-js-compute-.tgz ``` 4. Build and test or deploy your application as usual, using `fastly compute serve` or `fastly compute publish`, or an appropriate npm script. ## Testing a Dev Release in a Compute application :warning: **You should not use this for production workloads!!!!!!!!** Dev builds are released before production releases to allow for further testing. These are not released upstream to NPM, however you can acquire them from the [Releases](https://github.com/fastly/js-compute-runtime/releases/) section. Download the runtime for your platform, extract the executable and place it in the /node_modules/@fastly/js-compute/bin/PLATFORM folder of your Fastly Compute project. Then you can use the normal [Fastly CLI](https://github.com/fastly/cli) to build your service. Please submit an [issue](https://github.com/fastly/js-compute-runtime/issues) if you find any problems during testing. ## Tests All tests are automatically run on pull requests via CI. ### Unit Testing Unit tests are run via `npm run test`, currently including: - CLI tests (`npm run test:cli`) - Typing tests (`npm run test:types`) ### Integration Tests Complete test applications are tested from the `./integration-tests/js-compute/fixtures/app/src` and `./integration-tests/js-compute/fixtures/module-mode/src` directories. Tests themselves are listed in the `./integration-tests/js-compute/fixtures/app/tests.json` and `./integration-tests/js-compute/fixtures/module-mode/tests.json` files. Integration tests can be run via `npm run test:integration`, which defaults to the release build. In addition the following flags can be added after the command (passed via `npm run test:debug -- ...` after the `--`): - `--local`: Test locally using Viceroy, instead of publishing to a staging Compute service. - `--bail`: Immediately stop testing on the first failure, and report the failure. - `--verbose`: Adds verbose logging to `fastly compute publish` and Viceroy (which provides hostcall logging as well). - `--debug-build`: Use the debug build - `--debug-log`: Enable debug logging for the tests (engine-level DEBUG_LOG) - `--fixture=module-mode`: Run the module mode test suite (`fixtures/module-mode` instead of `fixtures/app`). - `--fixture=reusable-sandboxes`: Run the reusable sandboxes test suite (`fixtures/reusable-sandboxes`) - `--http-cache`: Run the HTTP cache test suite - `--serial`: Run tests serially rather than in concurrent batches (mostly useful for reusable sandbox tests) - `[...args]`: Additional arguments allow for filtering tests A typical development test command is therefore something like: ``` npm run build:cli && npm run build:debug && npm run test:integration -- --debug-build --debug-log --local --bail /crypto ``` Which would build the CLI TypeScript to JavaScript, run a debug build, enable debugging logging, and then that build against all the crypto tests locally on Viceroy, throwing an error as soon as one is found. Some tests can only be run on Compute and not Viceroy and will be automatically skipped. A green tick is always shown for a test that ran successfully - if it is missing that means it did not run. ### Web Platform Tests The Web Platform tests are included as a submodule, and can be run via `npm run test:wpt` or `npm run test:wpt:debug`. The WPT test runner supports the following options (passed via `npm run test:wpt -- ...` after the `--`): - `--update-expectations`: Update the WPT test expectations JSON files based on the current PASS/FAIL test statuses, instead of throwing an error when the current PASS/FAIL lists are not matched. - `[...args]`: Filter to apply to WPT tests to run Run `./tests/wpt-harness/run-wpt.mjs --help` for further options information. ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2020 Fastly, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- LLVM Exceptions to the Apache 2.0 License ---- As an exception, if, as a result of your compiling your source code, portions of this Software are embedded into an Object form of such source code, you may redistribute such embedded portions in such Object form without complying with the conditions of Sections 4(a), 4(b) and 4(d) of the License. In addition, if you combine or link compiled forms of this Software with software that is licensed under the GPLv2 ("Combined Software") and if a court of competent jurisdiction determines that the patent provision (Section 3), the indemnity provision (Section 9) or other Section of the License conflicts with the conditions of the GPLv2, you may retroactively and prospectively choose to deem waived or otherwise exclude such Section(s) of the License, but only in their entirety and only with respect to the Combined Software. ================================================ FILE: README.md ================================================ # @fastly/js-compute JavaScript SDK and CLI for building JavaScript applications on [Fastly Compute](https://www.fastly.com/products/edge-compute/serverless). ![npm version](https://img.shields.io/npm/v/@fastly/js-compute) ![npm downloads per month](https://img.shields.io/npm/dm/@fastly/js-compute) ## Getting Started We recommend using the [Fastly CLI](https://github.com/fastly/cli) to create, build, and deploy JavaScript Fastly Compute services, as [described on the Fastly Developer Hub](https://developer.fastly.com/learning/compute/). [Detailed documentation for JavaScript Fastly Compute services](https://developer.fastly.com/learning/compute/javascript/) is also available on Fastly Developer Hub. ## Usage ### JavaScript Examples The Fastly Developer Hub has a collection of [example JavaScript applications](https://developer.fastly.com/solutions/examples/javascript/). Here is a small example application: ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` ### CLI Flags and configuration The CLI is typically invoked by the `build` script defined in your project's `package.json` scripts. ```json { "scripts": { "build": "js-compute-runtime src/index.js bin/main.wasm" } } ``` The CLI is invoked as follows: ```sh js-compute-runtime [OPTIONS] ``` Options can be specified on the command line or added to a persistent configuration file for the project. The CLI will search for a configuration starting from the current directory in the following order: * A `fastlycompute` property in `package.json` * `.fastlycomputerc.json` * `fastlycompute.config.js`
Click here to see full list The CLI will search for a configuration starting from the current directory in the following order: - A `fastlycompute` property in `package.json` - `.fastlycomputerc` (JSON or YAML) - `.fastlycomputerc.json`, `.fastlycomputerc.yaml`, `.fastlycomputerc.yml` - `.fastlycomputerc.js`, `.fastlycomputerc.mjs` - `fastlycompute.config.js`, `fastlycompute.config.mjs`
If an option is defined in both the command line and the configuration file, the command line option takes precedence. #### Supported Options | Config Key | CLI Flag | Type | Description | |:----------------------------------------------|:-----------------------------------------------------|:----------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------| | `enableAOT` | `--enable-aot` | `boolean` | Enable AOT compilation for performance | | `aotCache` | `--aot-cache` | `string` (path) | Specify a path to the AOT cache file | | `enableHttpCache` | `--enable-http-cache` | `boolean` | Enable the [HTTP cache hook API](https://www.fastly.com/documentation/guides/concepts/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) | | `enableExperimentalHighResolutionTimeMethods` | `--enable-experimental-high-resolution-time-methods` | `boolean` | Enable experimental fastly.now() method | | `enableExperimentalTopLevelAwait` | `--enable-experimental-top-level-await` | `boolean` | Enable experimental top level await | | `enableStackTraces` | `--enable-stack-traces` | `boolean` | Enable stack traces | | `excludeSources` | `--exclude-sources` | `boolean` | Don't include sources in stack traces | | `debugIntermediateFiles` | `--debug-intermediate-files` | `string` (path) | Output intermediate files in directory | | `debugBuild` | `--debug-build` | `boolean` | Use debug build of the SDK runtime | | `engineWasm` | `--engine-wasm` | `string` (path) | Specify a custom Wasm engine (advanced) | | `wevalBin` | `--weval-bin` | `string` (path) | Specify a custom weval binary (advanced) | | `env` | `--env` | `string \| object \| array` | Set environment variables, possibly inheriting from the current environment. Multiple variables can be comma-separated (e.g., --env ENV_VAR,OVERRIDE=val) | NOTE: The `env` field is additive. Values defined on the command-line values append to, rather than replace, the values defined in any configuration file. #### Example command-line options ```sh js-compute-runtime --enable-aot --enable-stack-traces --enable-top-level-await --env=LOG_LEVEL=debug ./src/index.js ./bin/main.wasm ``` #### Example `.fastlycomputerc.json` ```json { "enableAOT": true, "enableStackTraces": true, "enableTopLevelAwait": true, "env": { "LOG_LEVEL": "debug" } } ``` #### Example `package.json` ```json { "name": "my-fastly-service", "type": "module", "dependencies": { "@fastly/cli": "^13.0.0" }, "scripts": { "build": "js-compute-runtime ./src/index.js ./bin/main.wasm", "dev": "fastly compute serve", "deploy": "fastly compute publish" }, "fastlycompute": { "enableAOT": true, "enableStackTraces": true, "enableTopLevelAwait": true, "env": { "LOG_LEVEL": "debug" } } } ``` ### API documentation The API documentation for the JavaScript SDK is located at [https://js-compute-reference-docs.edgecompute.app](https://js-compute-reference-docs.edgecompute.app). ## Security If you find any security issues, see the [Fastly Security Reporting Page](https://www.fastly.com/security/report-security-issue) or send an email to: `security@fastly.com` We plan to disclose any found security vulnerabilities per the [GitHub security vulnerability guidance](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/about-coordinated-disclosure-of-security-vulnerabilities#best-practices-for-maintainers). Note that communications related to security issues in Fastly-maintained OSS as described here are distinct from [Fastly security advisories](https://www.fastly.com/security-advisories). ## Changelog The changelog can be found [here](https://github.com/fastly/js-compute-runtime/blob/main/CHANGELOG.md). ## License [Apache-2.0 WITH LLVM-exception](./LICENSE) ================================================ FILE: SECURITY.md ================================================ ## Report a security issue The js-compute-runtime project team welcomes security reports and is committed to providing prompt attention to security issues. Security issues should be reported privately via [Fastly’s security issue reporting process](https://www.fastly.com/security/report-security-issue). ## Security advisories Remediation of security vulnerabilities is prioritized by the project team. The project team endeavors to coordinate remediation with third-party stakeholders, and is committed to transparency in the disclosure process. The team announces security issues via the [Fastly Developer Hub Starter Kits](https://developer.fastly.com/solutions/starters/) site on a best-effort basis. Note that communications related to security issues in Fastly-maintained OSS as described here are distinct from [Fastly Security Advisories](https://www.fastly.com/security-advisories). ================================================ FILE: ci/build-tarballs.sh ================================================ #!/usr/bin/env bash # A small shell script invoked from CI on the final Linux builder which actually # assembles the release artifacts for a particular platform. This will take the # binary artifacts of previous builders and create associated tarballs to # publish to GitHub. # # The first argument of this is the "platform" name to put into the tarball, and # the second argument is the name of the github actions platform which is where # we source binaries from. The final third argument is ".exe" on Windows to # handle executable extensions right. # # Usage: build-tarballs.sh PLATFORM [.exe] # where PLATFORM is e.g. x86_64-linux, aarch64-linux, ... set -euo pipefail set -x platform="$1" exe="${2:-}" rm -rf tmp mkdir tmp mkdir -p dist mktarball() { dir="$1" if [ "$exe" = "" ]; then tar -cJf "dist/$dir.tar.xz" -C tmp "$dir" else (cd tmp && zip -r "../dist/$dir.zip" "$dir") fi } # Create the main tarball of binaries bin_pkgname="js-compute-runtime-$TAG-$platform" mkdir "tmp/$bin_pkgname" cp README.md "tmp/$bin_pkgname" mv "bins-$platform/js-compute-runtime$exe" "tmp/$bin_pkgname" chmod +x "tmp/$bin_pkgname/js-compute-runtime$exe" mktarball "$bin_pkgname" ================================================ FILE: ci/clang-format.ignore ================================================ runtime/js-compute-runtime/third_party/wizer.h runtime/js-compute-runtime/rust-url/rust-url.h runtime/js-compute-runtime/rust-encoding/rust-encoding.h runtime/js-compute-runtime/host_interface/component/fastly_world.h ================================================ FILE: ci/clang-format.sh ================================================ #!/usr/bin/env bash set -euo pipefail usage() { cat < /dev/null; then continue fi formatted="${file}.formatted" /opt/wasi-sdk/bin/clang-format "$file" > "$formatted" if ! cmp -s "$file" "$formatted"; then if [ -z "$fix" ]; then rm "$formatted" echo "${file} needs formatting" failure=1 else echo "${file} formatted" mv "$formatted" "$file" fi fi rm -f "$formatted" done if [ -n "$failure" ]; then exit 1 fi ================================================ FILE: ci/format-changelog.js ================================================ #!/usr/bin/env node import { readFileSync, writeFileSync } from "node:fs"; import path from "node:path"; import process from "node:process"; import { unified } from "unified"; import remarkParse from "remark-parse"; import remarkStringify from "remark-stringify"; let markdownString; const fileFromArgs = process.argv[2]; const filePath = path.join(process.cwd(), fileFromArgs); try { markdownString = readFileSync(filePath, "utf-8"); } catch (err) { console.log( `Could not read or maybe even find your markdown file. \nCheck your file path, name, extension. \nMake sure you type 'npm run check -- pathtofile.md'\nError from Node.js: ${err}` ); process.exit(1); } let ast; try { ast = getAst(markdownString); } catch (err) { console.log(`Could not parse the markdown into a syntax tree: ${err}`); process.exit(1); } try { const result = format(ast, filePath); if (result.changed) { console.log("Updated markdown"); } if (result.correct) { console.log("Looks like the markdown was good enough"); process.exit(0); } else { console.log(`There was a problem with the markdown...\n ${result.reason}`); process.exit(1); } } catch (err) { console.log( `I must have made a mistake or not handled an error, soz\n${err}` ); process.exit(1); } function getAst(markdownString) { const tree = unified().use(remarkParse).parse(markdownString); return tree; } function format(ast, path) { try { let changed = false; const content = ast.children; if (!content.length) { return { correct: false, reason: "Empty file maybeee", }; } // heading 1 is optional so if it's there just get rid of it and check the rest if (content[0].type === "heading" && content[0].depth === 1) { content.splice(0, 1); } // now we may have removed the h1, the new 'first' item should be a h2 // check first item is a heading if (content[0].type !== "heading" || content[0].depth !== 2) { return { correct: false, reason: "There should be a level 2 heading at the top, or immediately after the level 1 heading if you have one. If you have a level 1 heading, make sure there is no text between that and the level 2 heading", }; } let changedIdx = -1; for (let i = 0; i < content.length; i++) { // checks on all ## headings const item = content[i]; if (item.type === "heading" && item.depth === 2) { changedIdx = -1; // check correct amount of text is at heading 2 if ( item.children.length === 2 && item.children[0].type === "link" && item.children[0].children.length === 1 && item.children[0].children[0].type === "text" && item.children[1].type === "text" ) { const link = item.children[0]; item.children = [item.children[1]]; item.children[0].value = link.children[0].value + item.children[0].value; changed = true; } else if (item.children.length !== 1) { console.log( `${path}:${item.position.start.line}:${item.position.start.column}` ); return { correct: false, reason: "Level 2 headings should say version and date, e.g. 1.9.2 (2023-02-10) and contain no other markdown", }; } const heading2 = item.children[0]; const heading2Text = heading2.value; // check heading 2 text can be split into exactly 2 parts at the point of a space let textParts; try { textParts = heading2Text.split(" "); } catch (err) { console.log( `${path}:${heading2.position.start.line}:${heading2.position.start.column}` ); return { correct: false, reason: `Level 2 headings should contain a space. We expect one between the semantic version number and the date. Error message: ${err}`, }; } if (textParts.length > 2) { console.log( `${path}:${heading2.position.start.line}:${heading2.position.start.column}` ); return { correct: false, reason: "Level 2 headings should only contain one space. We expect one between the semantic version number and the date", }; } // check first part of header 2 is a semantic version number const expectedSemanticVersion = textParts[0]; if ( !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/.test( expectedSemanticVersion ) ) { console.log( `${path}:${heading2.position.start.line}:${heading2.position.start.column}` ); return { correct: false, reason: "First part of level 2 headings should be a semantic version, e.g. 1.9.2", }; } // check second part of header 2 is a date in format YYYY-MM-DD const expectedDate = textParts[1]; if ( !/^\((\d{4,5}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])\))$/.test( expectedDate ) ) { console.log( `${path}:${heading2.position.start.line}:${heading2.position.start.column}` ); return { correct: false, reason: "Second part of level 2 headings should be a hypen-separated date in the format YYYY-MM-DD", }; } // check it is followed by at least one level 3 heading if ( !content[i + 1] || content[i + 1].type !== "heading" || content[i + 1].depth !== 3 ) { console.log( `${path}:${item.position.start.line}:${item.position.start.column}` ); return { correct: false, reason: "Level 2 headings must be followed by at least one level 3 heading", }; } } // checks on all ### headings if (item.type === "heading" && item.depth === 3) { // check it only uses one of the fixed options for change types if (item.children.length === 1 && item.children[0].type === "text") { const val = item.children[0].value; if (val.toLowerCase().endsWith("breaking changes")) { item.children[0].value = "Changed"; changed = true; } else if (val.includes("Bug Fixes")) { item.children[0].value = "Fixed"; changed = true; } else if (val.includes("Features")) { item.children[0].value = "Added"; changed = true; } } if (item.children.length !== 1 || item.children[0].type !== "text") { console.log( `${path}:${item.children[0].position.start.line}:${item.children[0].position.start.column}` ); return { correct: false, reason: `Level 3 headings should only be text`, }; } if (item.children[0].value === 'Performance Improvements') { if (i + 1 < content.length && (content[i + 1].type !== 'list' || content[i + 2].type !== 'heading')) { console.log( `${path}:${item.children[0].position.start.line}:${item.children[0].position.start.column}` ); return { correct: false, reason: `Performance improvements section must be a single list to fix it`, }; } if (changedIdx === -1) { for (let j = i + 1; j < content.length; j++) { const curItem = content[j]; if (curItem.type === 'heading') { if (curItem.depth < 3) break; if (curItem.depth === 3 && curItem.children.length === 1 && curItem.children[0].type === 'text' && curItem.children[0].value === 'Changed') { changedIdx = j; break; } } } } if (changedIdx !== -1) { // Merge it into any already-seen changed section const toMerge = content[i + 1]; content.splice(i, 2); content.splice(changedIdx + 1, 0, toMerge); changed = true; } else { // Otherwise rename to Changed item.children[0].value = 'Changed'; changed = true; } continue; } if (![ "Added", "Changed", "Deprecated", "Removed", "Fixed", "Security", ].includes(item.children[0].value) ) { console.log( `${path}:${item.children[0].position.start.line}:${item.children[0].position.start.column}` ); return { correct: false, reason: `Level 3 headings should only be one of 'Added', 'Changed', 'Deprecated', 'Removed', 'Fixed', 'Security'`, }; } if (item.children[0].value === 'Changed') changedIdx = i; // check that there is something other than a heading following it, which we have to presume describes the change if (!content[i + 1] || content[i + 1].type === "heading") { console.log( `${path}:${item.position.start.line}:${item.position.start.column}` ); return { correct: false, reason: "Level 3 headings must be followed by something other than a heading to describe the change", }; } } } if (changed) { // ...work around convoluted API... const wat = { data() {} }; remarkStringify.call(wat); const output = wat.compiler(ast); writeFileSync(path, `# Changelog\n\n${output}`, "utf8"); } return { correct: true, changed }; } catch (err) { console.error("Must be an error in my checks: ", err); process.exit(1); } } ================================================ FILE: ci/rustfmt.sh ================================================ #!/usr/bin/env bash set -euo pipefail cd "$(dirname "${BASH_SOURCE[0]}")/.." failed=0 for manifest in $(git ls-files | grep Cargo.toml); do if ! cargo fmt --manifest-path="$manifest" -- --check; then failed=1 fi done exit "$failed" ================================================ FILE: ci/shellcheck.sh ================================================ #!/usr/bin/env bash set -euo pipefail cd "$(dirname "${BASH_SOURCE[0]}")/.." failed= for file in $(git ls-files | grep '\.sh$'); do if ! shellcheck "${file}"; then failed=1 fi done if [ -n "${failed}" ]; then exit 1 fi ================================================ FILE: compute-file-server-cli/.gitignore ================================================ /target ================================================ FILE: compute-file-server-cli/Cargo.toml ================================================ [package] name = "compute-file-server-cli" version = "1.1.0" edition = "2021" description = "Uploads files to Fastly for serving directly from within Fastly Compute applications. Upload any type of file: images, text, video etc and serve directly from Fastly. It is ideal for serving files built from a static site generator such as 11ty." license = "MIT" license-file = "LICENSE" repository = "https://github.com/jakeChampion/compute-file-server" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] clap = "=4.0.10" walkdir = "=2.3.2" reqwest = { version = "=0.11", features = ["json", "stream"] } openssl = { version = "=0.10.72", features = ["vendored"] } tokio = { version = "=1", features = ["full"] } simple-error = "=0.2.3" serde_derive = "=1.0.145" serde = "=1.0.145" phf = { version = "=0.11", features = ["macros"] } fastly-api = "=1.0.0-beta.0" indicatif = "=0.17.1" futures = "=0.3.24" percent-encoding = "=2.2.0" toml_edit = "=0.14.4" httpdate = "=1.0.2" serde_json = "=1.0.86" sha2 = "=0.10.6" base64 = "=0.13.0" ================================================ FILE: compute-file-server-cli/LICENSE ================================================ MIT License Copyright (c) 2022 Jake Daniel Champion 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. ================================================ FILE: compute-file-server-cli/README.md ================================================ # compute-file-server Fastly File Server uploads files to Fastly for serving directly from within Fastly Compute applications. Upload any type of file: images, text, video etc and serve directly from Fastly. It is ideal for serving files built from a static site generator such as 11ty. ## Install ### Cargo Compile and install via `cargo` ```sh git clone https://github.com/JakeChampion/compute-file-server cd compute-file-server/cli cargo install --path . ``` ## Commands ### Upload Upload files to a Fastly Object Store, creating the Object Store if it does not exist. Example: `compute-file-server upload --name website-static-files -- ./folder/of/files` ```sh compute-file-server upload Upload files Usage: compute-file-server upload [OPTIONS] --name -- Arguments: Options: --name --token -h, --help Print help information ``` ### Link Connect a Fastly Object Store to a Fastly Service. Example: `compute-file-server link --name website-static-files --link-name files --service-id xxyyzz` ```sh Usage: compute-file-server link [OPTIONS] --name --link-name --service-id Options: --name --token --link-name --service-id -h, --help Print help information ``` ### Local Update `fastly.toml` to contain a local Object Store containing the specified files. Example: `compute-file-server local --name files --toml fastly.toml -- ./folder/of/files` ```sh Usage: compute-file-server local --toml --name -- Arguments: Options: --toml --name -h, --help Print help information ``` ================================================ FILE: compute-file-server-cli/rust-toolchain.toml ================================================ [toolchain] channel = "1.83.0" targets = ["wasm32-wasi"] profile = "minimal" ================================================ FILE: compute-file-server-cli/src/main.rs ================================================ use base64; use clap::{arg, Command}; use fastly_api::apis::configuration::{ApiKey, Configuration}; use fastly_api::apis::version_api::{ activate_service_version, clone_service_version, list_service_versions, ActivateServiceVersionParams, CloneServiceVersionParams, ListServiceVersionsParams, }; use futures::{stream, StreamExt}; use httpdate::fmt_http_date; use reqwest::Client; use sha2::{Digest, Sha256}; use simple_error::bail; use std::error::Error; use std::path::PathBuf; use tokio; use tokio::fs::File; use toml_edit; use walkdir::WalkDir; const PARALLEL_REQUESTS: usize = 10; const RETRY_REQUESTS: usize = 5; use phf::phf_map; static MIMES: phf::Map<&'static str, &'static str> = phf_map! { "ez"=> "application/andrew-inset", "aw"=> "application/applixware", "atom"=> "application/atom+xml", "atomcat"=> "application/atomcat+xml", "atomdeleted"=> "application/atomdeleted+xml", "atomsvc"=> "application/atomsvc+xml", "dwd"=> "application/atsc-dwd+xml", "held"=> "application/atsc-held+xml", "rsat"=> "application/atsc-rsat+xml", "bdoc"=> "application/bdoc", "xcs"=> "application/calendar+xml", "ccxml"=> "application/ccxml+xml", "cdfx"=> "application/cdfx+xml", "cdmia"=> "application/cdmi-capability", "cdmic"=> "application/cdmi-container", "cdmid"=> "application/cdmi-domain", "cdmio"=> "application/cdmi-object", "cdmiq"=> "application/cdmi-queue", "cu"=> "application/cu-seeme", "mpd"=> "application/dash+xml", "davmount"=> "application/davmount+xml", "dbk"=> "application/docbook+xml", "dssc"=> "application/dssc+der", "xdssc"=> "application/dssc+xml", "es"=> "application/ecmascript", "ecma"=> "application/ecmascript", "emma"=> "application/emma+xml", "emotionml"=> "application/emotionml+xml", "epub"=> "application/epub+zip", "exi"=> "application/exi", "fdt"=> "application/fdt+xml", "pfr"=> "application/font-tdpfr", "geojson"=> "application/geo+json", "gml"=> "application/gml+xml", "gpx"=> "application/gpx+xml", "gxf"=> "application/gxf", "gz"=> "application/gzip", "hjson"=> "application/hjson", "stk"=> "application/hyperstudio", "ink"=> "application/inkml+xml", "inkml"=> "application/inkml+xml", "ipfix"=> "application/ipfix", "its"=> "application/its+xml", "jar"=> "application/java-archive", "war"=> "application/java-archive", "ear"=> "application/java-archive", "ser"=> "application/java-serialized-object", "class"=> "application/java-vm", "js"=> "application/javascript", "mjs"=> "application/javascript", "json"=> "application/json", "map"=> "application/json", "json5"=> "application/json5", "jsonml"=> "application/jsonml+json", "jsonld"=> "application/ld+json", "lgr"=> "application/lgr+xml", "lostxml"=> "application/lost+xml", "hqx"=> "application/mac-binhex40", "cpt"=> "application/mac-compactpro", "mads"=> "application/mads+xml", "webmanifest"=> "application/manifest+json", "mrc"=> "application/marc", "mrcx"=> "application/marcxml+xml", "ma"=> "application/mathematica", "nb"=> "application/mathematica", "mb"=> "application/mathematica", "mathml"=> "application/mathml+xml", "mbox"=> "application/mbox", "mscml"=> "application/mediaservercontrol+xml", "metalink"=> "application/metalink+xml", "meta4"=> "application/metalink4+xml", "mets"=> "application/mets+xml", "maei"=> "application/mmt-aei+xml", "musd"=> "application/mmt-usd+xml", "mods"=> "application/mods+xml", "m21"=> "application/mp21", "mp21"=> "application/mp21", "mp4s"=> "application/mp4", "m4p"=> "application/mp4", "doc"=> "application/msword", "dot"=> "application/msword", "mxf"=> "application/mxf", "nq"=> "application/n-quads", "nt"=> "application/n-triples", "cjs"=> "application/node", "bin"=> "application/octet-stream", "dms"=> "application/octet-stream", "lrf"=> "application/octet-stream", "mar"=> "application/octet-stream", "so"=> "application/octet-stream", "dist"=> "application/octet-stream", "distz"=> "application/octet-stream", "pkg"=> "application/octet-stream", "bpk"=> "application/octet-stream", "dump"=> "application/octet-stream", "elc"=> "application/octet-stream", "deploy"=> "application/octet-stream", "exe"=> "application/octet-stream", "dll"=> "application/octet-stream", "deb"=> "application/octet-stream", "dmg"=> "application/octet-stream", "iso"=> "application/octet-stream", "img"=> "application/octet-stream", "msi"=> "application/octet-stream", "msp"=> "application/octet-stream", "msm"=> "application/octet-stream", "buffer"=> "application/octet-stream", "oda"=> "application/oda", "opf"=> "application/oebps-package+xml", "ogx"=> "application/ogg", "omdoc"=> "application/omdoc+xml", "onetoc"=> "application/onenote", "onetoc2"=> "application/onenote", "onetmp"=> "application/onenote", "onepkg"=> "application/onenote", "oxps"=> "application/oxps", "relo"=> "application/p2p-overlay+xml", "xer"=> "application/patch-ops-error+xml", "pdf"=> "application/pdf", "pgp"=> "application/pgp-encrypted", "asc"=> "application/pgp-signature", "sig"=> "application/pgp-signature", "prf"=> "application/pics-rules", "p10"=> "application/pkcs10", "p7m"=> "application/pkcs7-mime", "p7c"=> "application/pkcs7-mime", "p7s"=> "application/pkcs7-signature", "p8"=> "application/pkcs8", "ac"=> "application/pkix-attr-cert", "cer"=> "application/pkix-cert", "crl"=> "application/pkix-crl", "pkipath"=> "application/pkix-pkipath", "pki"=> "application/pkixcmp", "pls"=> "application/pls+xml", "ai"=> "application/postscript", "eps"=> "application/postscript", "ps"=> "application/postscript", "provx"=> "application/provenance+xml", "cww"=> "application/prs.cww", "pskcxml"=> "application/pskc+xml", "raml"=> "application/raml+yaml", "rdf"=> "application/rdf+xml", "owl"=> "application/rdf+xml", "rif"=> "application/reginfo+xml", "rnc"=> "application/relax-ng-compact-syntax", "rl"=> "application/resource-lists+xml", "rld"=> "application/resource-lists-diff+xml", "rs"=> "application/rls-services+xml", "rapd"=> "application/route-apd+xml", "sls"=> "application/route-s-tsid+xml", "rusd"=> "application/route-usd+xml", "gbr"=> "application/rpki-ghostbusters", "mft"=> "application/rpki-manifest", "roa"=> "application/rpki-roa", "rsd"=> "application/rsd+xml", "rss"=> "application/rss+xml", "rtf"=> "application/rtf", "sbml"=> "application/sbml+xml", "scq"=> "application/scvp-cv-request", "scs"=> "application/scvp-cv-response", "spq"=> "application/scvp-vp-request", "spp"=> "application/scvp-vp-response", "sdp"=> "application/sdp", "senmlx"=> "application/senml+xml", "sensmlx"=> "application/sensml+xml", "setpay"=> "application/set-payment-initiation", "setreg"=> "application/set-registration-initiation", "shf"=> "application/shf+xml", "siv"=> "application/sieve", "sieve"=> "application/sieve", "smi"=> "application/smil+xml", "smil"=> "application/smil+xml", "rq"=> "application/sparql-query", "srx"=> "application/sparql-results+xml", "gram"=> "application/srgs", "grxml"=> "application/srgs+xml", "sru"=> "application/sru+xml", "ssdl"=> "application/ssdl+xml", "ssml"=> "application/ssml+xml", "swidtag"=> "application/swid+xml", "tei"=> "application/tei+xml", "teicorpus"=> "application/tei+xml", "tfi"=> "application/thraud+xml", "tsd"=> "application/timestamped-data", "toml"=> "application/toml", "trig"=> "application/trig", "ttml"=> "application/ttml+xml", "ubj"=> "application/ubjson", "rsheet"=> "application/urc-ressheet+xml", "td"=> "application/urc-targetdesc+xml", "vxml"=> "application/voicexml+xml", "wasm"=> "application/wasm", "wgt"=> "application/widget", "hlp"=> "application/winhlp", "wsdl"=> "application/wsdl+xml", "wspolicy"=> "application/wspolicy+xml", "xaml"=> "application/xaml+xml", "xav"=> "application/xcap-att+xml", "xca"=> "application/xcap-caps+xml", "xdf"=> "application/xcap-diff+xml", "xel"=> "application/xcap-el+xml", "xns"=> "application/xcap-ns+xml", "xenc"=> "application/xenc+xml", "xhtml"=> "application/xhtml+xml", "xht"=> "application/xhtml+xml", "xlf"=> "application/xliff+xml", "xml"=> "application/xml", "xsl"=> "application/xml", "xsd"=> "application/xml", "rng"=> "application/xml", "dtd"=> "application/xml-dtd", "xop"=> "application/xop+xml", "xpl"=> "application/xproc+xml", "xslt"=> "application/xml", "xspf"=> "application/xspf+xml", "mxml"=> "application/xv+xml", "xhvml"=> "application/xv+xml", "xvml"=> "application/xv+xml", "xvm"=> "application/xv+xml", "yang"=> "application/yang", "yin"=> "application/yin+xml", "zip"=> "application/zip", "3gpp"=> "video/3gpp", "adp"=> "audio/adpcm", "amr"=> "audio/amr", "au"=> "audio/basic", "snd"=> "audio/basic", "mid"=> "audio/midi", "midi"=> "audio/midi", "kar"=> "audio/midi", "rmi"=> "audio/midi", "mxmf"=> "audio/mobile-xmf", "mp3"=> "audio/mpeg", "m4a"=> "audio/mp4", "mp4a"=> "audio/mp4", "mpga"=> "audio/mpeg", "mp2"=> "audio/mpeg", "mp2a"=> "audio/mpeg", "m2a"=> "audio/mpeg", "m3a"=> "audio/mpeg", "oga"=> "audio/ogg", "ogg"=> "audio/ogg", "spx"=> "audio/ogg", "opus"=> "audio/ogg", "s3m"=> "audio/s3m", "sil"=> "audio/silk", "wav"=> "audio/wav", "weba"=> "audio/webm", "xm"=> "audio/xm", "ttc"=> "font/collection", "otf"=> "font/otf", "ttf"=> "font/ttf", "woff"=> "font/woff", "woff2"=> "font/woff2", "exr"=> "image/aces", "apng"=> "image/apng", "avif"=> "image/avif", "bmp"=> "image/bmp", "cgm"=> "image/cgm", "drle"=> "image/dicom-rle", "emf"=> "image/emf", "fits"=> "image/fits", "g3"=> "image/g3fax", "gif"=> "image/gif", "heic"=> "image/heic", "heics"=> "image/heic-sequence", "heif"=> "image/heif", "heifs"=> "image/heif-sequence", "hej2"=> "image/hej2k", "hsj2"=> "image/hsj2", "ief"=> "image/ief", "jls"=> "image/jls", "jp2"=> "image/jp2", "jpg2"=> "image/jp2", "jpeg"=> "image/jpeg", "jpg"=> "image/jpeg", "jpe"=> "image/jpeg", "jph"=> "image/jph", "jhc"=> "image/jphc", "jpm"=> "image/jpm", "jpx"=> "image/jpx", "jpf"=> "image/jpx", "jxr"=> "image/jxr", "jxra"=> "image/jxra", "jxrs"=> "image/jxrs", "jxs"=> "image/jxs", "jxsc"=> "image/jxsc", "jxsi"=> "image/jxsi", "jxss"=> "image/jxss", "ktx"=> "image/ktx", "ktx2"=> "image/ktx2", "png"=> "image/png", "btif"=> "image/prs.btif", "pti"=> "image/prs.pti", "sgi"=> "image/sgi", "svg"=> "image/svg+xml", "svgz"=> "image/svg+xml", "t38"=> "image/t38", "tif"=> "image/tiff", "tiff"=> "image/tiff", "tfx"=> "image/tiff-fx", "webp"=> "image/webp", "wmf"=> "image/wmf", "disposition-notification"=> "message/disposition-notification", "u8msg"=> "message/global", "u8dsn"=> "message/global-delivery-status", "u8mdn"=> "message/global-disposition-notification", "u8hdr"=> "message/global-headers", "eml"=> "message/rfc822", "mime"=> "message/rfc822", "3mf"=> "model/3mf", "gltf"=> "model/gltf+json", "glb"=> "model/gltf-binary", "igs"=> "model/iges", "iges"=> "model/iges", "msh"=> "model/mesh", "mesh"=> "model/mesh", "silo"=> "model/mesh", "mtl"=> "model/mtl", "obj"=> "model/obj", "stpz"=> "model/step+zip", "stpxz"=> "model/step-xml+zip", "stl"=> "model/stl", "wrl"=> "model/vrml", "vrml"=> "model/vrml", "x3db"=> "model/x3d+fastinfoset", "x3dbz"=> "model/x3d+binary", "x3dv"=> "model/x3d-vrml", "x3dvz"=> "model/x3d+vrml", "x3d"=> "model/x3d+xml", "x3dz"=> "model/x3d+xml", "appcache"=> "text/cache-manifest", "manifest"=> "text/cache-manifest", "ics"=> "text/calendar", "ifb"=> "text/calendar", "coffee"=> "text/coffeescript", "litcoffee"=> "text/coffeescript", "css"=> "text/css", "csv"=> "text/csv", "html"=> "text/html", "htm"=> "text/html", "shtml"=> "text/html", "jade"=> "text/jade", "jsx"=> "text/jsx", "less"=> "text/less", "markdown"=> "text/markdown", "md"=> "text/markdown", "mml"=> "text/mathml", "mdx"=> "text/mdx", "n3"=> "text/n3", "txt"=> "text/plain", "text"=> "text/plain", "conf"=> "text/plain", "def"=> "text/plain", "list"=> "text/plain", "log"=> "text/plain", "in"=> "text/plain", "ini"=> "text/plain", "dsc"=> "text/prs.lines.tag", "rtx"=> "text/richtext", "sgml"=> "text/sgml", "sgm"=> "text/sgml", "shex"=> "text/shex", "slim"=> "text/slim", "slm"=> "text/slim", "spdx"=> "text/spdx", "stylus"=> "text/stylus", "styl"=> "text/stylus", "tsv"=> "text/tab-separated-values", "t"=> "text/troff", "tr"=> "text/troff", "roff"=> "text/troff", "man"=> "text/troff", "me"=> "text/troff", "ms"=> "text/troff", "ttl"=> "text/turtle", "uri"=> "text/uri-list", "uris"=> "text/uri-list", "urls"=> "text/uri-list", "vcard"=> "text/vcard", "vtt"=> "text/vtt", "yaml"=> "text/yaml", "yml"=> "text/yaml", "3gp"=> "video/3gpp", "3g2"=> "video/3gpp2", "h261"=> "video/h261", "h263"=> "video/h263", "h264"=> "video/h264", "m4s"=> "video/iso.segment", "jpgv"=> "video/jpeg", "jpgm"=> "image/jpm", "mj2"=> "video/mj2", "mjp2"=> "video/mj2", "ts"=> "video/mp2t", "mp4"=> "video/mp4", "mp4v"=> "video/mp4", "mpg4"=> "video/mp4", "mpeg"=> "video/mpeg", "mpg"=> "video/mpeg", "mpe"=> "video/mpeg", "m1v"=> "video/mpeg", "m2v"=> "video/mpeg", "ogv"=> "video/ogg", "qt"=> "video/quicktime", "mov"=> "video/quicktime", "webm"=> "video/webm" }; fn lookup(extn: &str) -> Option<&&str> { let extn = extn.trim().to_lowercase(); MIMES.get(&extn) } use serde_derive::Deserialize; use serde_derive::Serialize; #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Metadata { #[serde(rename = "ETag")] etag: String, #[serde(rename = "Last-Modified")] last_modified: String, #[serde(rename = "Content-Type")] content_type: Option, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct KVStores { data: Vec, meta: Meta, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct KVStore { id: String, name: String, #[serde(rename = "created_at")] created_at: String, #[serde(rename = "updated_at")] updated_at: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Meta { limit: i64, total: i64, } async fn create_store(name: &str, token: &str) -> Result> { let client = reqwest::Client::new(); let res = client .post("https://api.fastly.com/resources/stores/kv") .header("Content-Type", "application/json") .header("Accept", "application/json") .header("Fastly-Key", token) .body(format!("{{\"name\":\"{}\"}}", name)) .send() .await?; if res.status() == 201 { Ok(res.json::().await?.id) } else { bail!(format!( "Failed to create Object Store named `{}`. Response body contained `{}`", name, res.text().await? )) } } async fn get_or_create_store( name: &str, token: &str, ) -> Result> { // get all stores let client = reqwest::Client::new(); let res = client .get("https://api.fastly.com/resources/stores/kv") .header("Content-Type", "application/json") .header("Accept", "application/json") .header("Fastly-Key", token) .send() .await?; // if no stores at all, create store if res.status() == 404 { create_store(name, token).await } else { // check if store already exists let res = res .json::() .await? .data .into_iter() .find_map(|store| { if store.name == name { Some(store.id) } else { None } }); // if store does not exist, create store if res.is_none() { create_store(name, token).await } else { Ok(res.unwrap()) } } } async fn get_active_version_of_service( service_id: &str, token: &str, ) -> Result> { let mut cfg = Configuration { api_key: Some(ApiKey { prefix: None, key: token.to_owned(), }), ..Default::default() }; let params = ListServiceVersionsParams { service_id: service_id.to_owned(), ..Default::default() }; let result = list_service_versions(&mut cfg, params) .await? .into_iter() .find_map(|v| { if v.active.unwrap() { Some(v.number.unwrap()) } else { None } }); return Ok(result.expect("Service should have an active version to clone")); } async fn clone_version_of_service( service_id: &str, token: &str, version: i32, ) -> Result> { let mut cfg = Configuration { api_key: Some(ApiKey { prefix: None, key: token.to_owned(), }), ..Default::default() }; let params = CloneServiceVersionParams { service_id: service_id.to_owned(), version_id: version, ..Default::default() }; Ok(clone_service_version(&mut cfg, params) .await? .number .unwrap()) } async fn activate_version_of_service( service_id: &str, token: &str, version: i32, ) -> Result> { let mut cfg = Configuration { api_key: Some(ApiKey { prefix: None, key: token.to_owned(), }), ..Default::default() }; let params = ActivateServiceVersionParams { service_id: service_id.to_string(), version_id: version, ..Default::default() }; Ok(activate_service_version(&mut cfg, params) .await? .number .unwrap()) } fn cli() -> Command { Command::new("fastly-file-server") .about("Fastly File Server uploads files to Fastly for serving directly from within Fastly Compute applications. Upload any type of file: images, text, video etc and serve directly from Fastly. It is ideal for serving files built from a static site generator such as 11ty.") .subcommand_required(true) .arg_required_else_help(true) .subcommand( Command::new("upload") .about("Upload files") .arg( arg!(path: [PATH]) .last(true) .required(true) .value_parser(clap::value_parser!(PathBuf)), ) .arg_required_else_help(true) .arg(arg!(--name ).required(true)) .arg(arg!(--token )), ) .subcommand( Command::new("local") .about("Setup files") .arg( arg!(path: [PATH]) .last(true) .required(true) .value_parser(clap::value_parser!(PathBuf)), ) .arg_required_else_help(true) .arg(arg!(--toml ).required(true).value_parser(clap::value_parser!(PathBuf))) .arg(arg!(--name ).required(true)), ) .subcommand( Command::new("link") .about("link store to service") .arg(arg!(--name ).required(true)) .arg(arg!(--token )) .arg(arg!(--"link-name" ).required(true)) .arg(arg!(--"service-id" ).required(true)), ) .subcommand( Command::new("unlink") .about("unlink store to service") .arg(arg!(--name ).required(true)) .arg(arg!(--token )) .arg(arg!(--"link-name" ).required(true)) .arg(arg!(--"service-id" ).required(true)), ) } async fn link(sub_matches: &clap::ArgMatches) -> Result<(), Box> { let service_id = sub_matches .get_one::("service-id") .map(|s| s.as_str()) .expect("required in clap"); let link_name = sub_matches .get_one::("link-name") .map(|s| s.as_str()) .expect("required in clap"); let name = sub_matches .get_one::("name") .map(|s| s.as_str()) .expect("required in clap"); let token = sub_matches .get_one::("token") .map(|s| s.to_owned()) .or_else(|| match std::env::var("FASTLY_API_TOKEN") { Ok(x) => Some(x), Err(_) => None, }); if token.is_none() { bail!("Missing Fastly API token. Please provide an API token via the --token argument or the FASTLY_API_TOKEN environment variable.") } let token = token.unwrap(); let store_id = get_or_create_store(name, &token).await?; let version = get_active_version_of_service(service_id, &token).await?; let version = clone_version_of_service(service_id, &token, version).await?; // link let client = reqwest::Client::new(); let _res = client .post(format!( "https://api.fastly.com/service/{}/version/{}/resource", service_id, version )) .header("Content-Type", "application/x-www-form-urlencoded") .header("Accept", "application/json") .header("Fastly-Key", &token) .body(format!("name={}&resource_id={}", link_name, store_id)) .send() .await?; // activate activate_version_of_service(service_id, &token, version).await?; Ok(()) } async fn upload(sub_matches: &clap::ArgMatches) -> Result<(), Box> { let name = sub_matches .get_one::("name") .map(|s| s.as_str()) .expect("required in clap"); let token = sub_matches .get_one::("token") .map(|s| s.to_owned()) .or_else(|| match std::env::var("FASTLY_API_TOKEN") { Ok(x) => Some(x), Err(_) => None, }); if token.is_none() { bail!("Missing Fastly API token. Please provide an API token via the --token argument or the FASTLY_API_TOKEN environment variable.") } let token = token.unwrap(); let store_id = get_or_create_store(name, &token).await?; let path = sub_matches .get_one::("path") .expect("required in clap"); let entries = WalkDir::new(path) .follow_links(true) .into_iter() .filter_map(Result::ok) .filter(|e| !e.file_type().is_dir()) .collect::>(); let pb = indicatif::ProgressBar::new(entries.len().try_into().unwrap()); let client = Client::new(); let bodies = stream::iter(entries) .map(|entry| -> tokio::task::JoinHandle>> { let path = path.clone(); let store_id = store_id.clone(); let token = token.clone(); let client = client.clone(); tokio::spawn(async move { let extension = entry.path().extension().map(|e| e.to_string_lossy().to_string()).unwrap_or("".to_string()); let normalised_entry = entry.path().strip_prefix(path).unwrap(); let normalised_path = "/".to_owned() + &normalised_entry.to_string_lossy(); let key = percent_encoding::utf8_percent_encode( &normalised_path, percent_encoding::NON_ALPHANUMERIC, ); let metadata_key = normalised_path.to_owned() + "__metadata__"; let metadata_key = percent_encoding::utf8_percent_encode( &metadata_key, percent_encoding::NON_ALPHANUMERIC, ); let file_contents = tokio::fs::read(entry.path()).await?; let file = File::open(entry.path()).await?; let file_metadata = file.metadata().await?; let length = file.metadata().await?.len(); let mut counter = 0; let sha = Sha256::digest(file_contents); let sha = base64::encode(&sha); let metadata = serde_json::to_string(&Metadata { etag: format!("W/\"{}\"", sha), last_modified: fmt_http_date(file_metadata.modified()?), content_type: lookup(&extension).map(|content_type| content_type.to_string()) })?; loop { let res = client .put(format!( "https://api.fastly.com/resources/stores/kv/{}/keys/{}", store_id, metadata_key )) .header("Content-Type", "application/json") .header("Content-Length", metadata.len().to_string()) .header("Accept", "application/json") .header("Fastly-Key", &token) .body(metadata.clone()) .send() .await?; if res.status() != 200 { counter = counter + 1; if counter > RETRY_REQUESTS { bail!( "Error uploading metadata for file named `{}`: Response Status: {} Response Body: {}", normalised_path, res.status(), res.text().await? ); } } else { break; } } let mut counter = 0; loop { let res = client .put(format!( "https://api.fastly.com/resources/stores/kv/{}/keys/{}", store_id, key )) .header("Content-Type", "application/json") .header("Content-Length", length) .header("Accept", "application/json") .header("Fastly-Key", &token) .body(file.try_clone().await?) .send() .await?; if res.status() != 200 { counter = counter + 1; if counter > RETRY_REQUESTS { bail!( "Error uploading file named `{}`: Response Status: {} Response Body: {}", normalised_path, res.status(), res.text().await? ); } } else { return Ok::>( normalised_path, ); } } }) }) .buffer_unordered(PARALLEL_REQUESTS); bodies .for_each(|b| async { match b { Ok(Ok(normalised_entry)) => { pb.println(format!("[+] uploaded {}", normalised_entry)); pb.inc(1); } Ok(Err(e)) => eprintln!("Got a reqwest::Error: {}", e), Err(e) => eprintln!("Got a tokio::JoinError: {}", e), } }) .await; pb.finish_with_message("done"); Ok(()) } async fn local(sub_matches: &clap::ArgMatches) -> Result<(), Box> { let name = sub_matches .get_one::("name") .map(|s| s.as_str()) .expect("required in clap"); let path = sub_matches .get_one::("path") .expect("required in clap"); let toml_path = sub_matches .get_one::("toml") .expect("required in clap"); let entries = WalkDir::new(path) .follow_links(true) .into_iter() .filter_map(Result::ok) .filter(|e| !e.file_type().is_dir()) .collect::>(); let mut toml = std::fs::read_to_string(toml_path)?.parse::()?; let mut local_server = toml .get_key_value("local_server") .map(|a| a.1.to_owned()) .unwrap_or_else(|| toml_edit::table()); let mut object_store = local_server .as_table_mut() .unwrap() .get_key_value(&format!("object_store")) .map(|a| a.1.to_owned()) .unwrap_or_else(|| toml_edit::table()); let mut site = toml_edit::array(); for entry in entries { let path = path.clone(); let entry_path = entry.path().to_string_lossy().to_string(); let extension = entry .path() .extension() .map(|e| e.to_string_lossy().to_string()) .unwrap_or("".to_string()); let normalised_entry = entry.path().strip_prefix(path).unwrap(); let normalised_path = "/".to_owned() + &normalised_entry.to_string_lossy(); let key = &normalised_path; let metadata_key = normalised_path.to_owned() + "__metadata__"; let file_contents = tokio::fs::read(entry.path()).await?; let file = File::open(entry.path()).await?; let file_metadata = file.metadata().await?; let sha = Sha256::digest(file_contents); let sha = base64::encode(&sha); let metadata = serde_json::to_string(&Metadata { etag: format!("W/\"{}\"", sha), last_modified: fmt_http_date(file_metadata.modified()?), content_type: lookup(&extension).map(|content_type| content_type.to_string()), })?; let mut entry = toml_edit::table(); entry .as_table_mut() .unwrap() .insert("key", toml_edit::value(metadata_key)); entry .as_table_mut() .unwrap() .insert("data", toml_edit::value(metadata.clone())); site.as_array_of_tables_mut() .unwrap() .push(entry.as_table().unwrap().to_owned()); let mut entry = toml_edit::table(); entry .as_table_mut() .unwrap() .insert("key", toml_edit::value(key)); entry .as_table_mut() .unwrap() .insert("path", toml_edit::value(entry_path)); site.as_array_of_tables_mut() .unwrap() .push(entry.as_table().unwrap().to_owned()); } object_store.as_table_mut().unwrap().insert(name, site); local_server .as_table_mut() .unwrap() .insert(&"object_store", object_store); toml.as_table_mut().insert("local_server", local_server); std::fs::write(toml_path, toml.to_string())?; Ok(()) } #[tokio::main] async fn main() -> Result<(), Box> { let matches = cli().get_matches(); match matches.subcommand() { Some(("link", sub_matches)) => link(sub_matches).await, Some(("local", sub_matches)) => local(sub_matches).await, Some(("upload", sub_matches)) => upload(sub_matches).await, _ => unreachable!(), } } ================================================ FILE: documentation/.gitignore ================================================ # Dependencies /node_modules # Production /build # Generated files .docusaurus .cache-loader # Misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: documentation/LICENSE.md ================================================ Creative Commons Attribution-ShareAlike 2.5 CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM ITS USE. License THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 1. Definitions a. "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License. b. "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License. c. "Licensor" means the individual or entity that offers the Work under the terms of this License. d. "Original Author" means the individual or entity who created the Work. e. "Work" means the copyrightable work of authorship offered under the terms of this License. f. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. g. "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike. 2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws. 3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: a. to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works; b. to create and reproduce Derivative Works; c. to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works; d. to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works. e. For the avoidance of doubt, where the work is a musical composition: i. Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work. ii. Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions). f. Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions). The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved. 4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: a. You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(c), as requested. b. You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.5 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License. c. If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit. 5. Representations, Warranties and Disclaimer UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. Termination a. This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. b. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 8. Miscellaneous a. Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. b. Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. c. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. d. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. e. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. Creative Commons is not a party to this License, and makes no warranty whatsoever in connection with the Work. Creative Commons will not be liable to You or any party on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection to this license. Notwithstanding the foregoing two (2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder, it shall have all rights and obligations of Licensor. Except for the limited purpose of indicating to the public that the Work is licensed under the CCPL, neither party will use the trademark "Creative Commons" or any related trademark or logo of Creative Commons without the prior written consent of Creative Commons. Any permitted use will be in compliance with Creative Commons' then-current trademark usage guidelines, as may be published on its website or otherwise made available upon request from time to time. Creative Commons may be contacted at http://creativecommons.org/. ================================================ FILE: documentation/README.md ================================================ # [JS Compute Documentation](https://js-compute-reference-docs.edgecompute.app/) This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. ### Installation ``` $ yarn ``` ### Local Development ``` $ yarn start ``` This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. ### Build ``` $ yarn build ``` This command generates static content into the `build` directory and can be served using any static contents hosting service. ### Deployment ``` $ yarn deploy ``` This command will run `yarn build` and then will upload the website to Fastly KV Store and deploy the application to Fastly Compute. ================================================ FILE: documentation/app/.gitignore ================================================ # Dependencies /node_modules # Production /build # Generated files .docusaurus .cache-loader # Misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* /bin /pkg ================================================ FILE: documentation/app/c-at-e-file-server.js ================================================ import parseRange from 'range-parser' import versionRedirects from './version-redirects.json' /** * Check if the request path is for an old minor version and should be redirected * to the latest minor version within the same major version. * @param {Request} request - The incoming request * @returns {Response | null} - Returns a redirect Response if applicable, else null */ function redirectMinorVersions(request) { const url = new URL(request.url); const pathMatch = url.pathname.match(/^\/docs\/([^\/]+)(\/.*)?$/); if (!pathMatch) { return null; } const [, version, restOfPath = ''] = pathMatch; const majorVersion = version.split('.')[0]; const targetVersion = versionRedirects.latestByMajor[majorVersion]; if (targetVersion === null || (targetVersion && targetVersion !== version)) { // Construct the new URL with the latest version const versionPrefix = targetVersion === null ? '' : `/${targetVersion}`; const newPath = `/docs${versionPrefix}${restOfPath}`; const newUrl = new URL(newPath, url.origin); newUrl.search = url.search; // Preserve query parameters // Return a 301 permanent redirect return new Response(null, { status: 301, headers: { 'Location': newUrl.toString(), 'Cache-Control': 'public, max-age=3600' } }); } return null; } /** * Attempt to locate the requested resource from a Fastly KV Store, * If the request is a GET or HEAD request and a resource was found in the KV Store, this will return a `Response`. * If request is not GET or HEAD, or no resource was found in the KV Store, this will return `null` * @param {string} store_name The name of the Fastly KV Store to search within. * @param {Request} request The request to attempt to match against a resource within the KV Store. * @returns {Promise} Returns a `Response` if a resource was found, else returns `null`. */ export async function get(store_name, request) { const isHeadRequest = request.method === 'HEAD' // static files should only respond on HEAD and GET requests if (!isHeadRequest && request.method !== 'GET') { return null } // Check if this request should be redirected to a newer minor version const redirect = redirectMinorVersions(request); if (redirect) { return redirect; } // if path ends in / or does not have an extension // then append /index.html to the end so we can serve a page let path = new URL(request.url).pathname if (path.endsWith('/')) { path += 'index.html' } else if (!path.includes('.')) { path += '/index.html' } const metadataPath = path + '__metadata__' let metadata = await (new KVStore(store_name)).get(metadataPath) if (metadata == null) { return null } metadata = await metadata.json(); const responseHeaders = metadata; responseHeaders['accept-ranges'] = 'bytes' const response = checkPreconditions(request, responseHeaders); if (response) { return response; } const item = await (new KVStore(store_name)).get(path) if (item == null) { return null } let range = request.headers.get("range"); if (range == null) { return new Response(isHeadRequest ? null : item.body, { status: 200, headers: responseHeaders }) } else { return handleRangeRequest(item, range, responseHeaders, isHeadRequest) } } async function handleRangeRequest(item, range, headers, isHeadRequest) { /** * @type {Uint8Array} */ const itemBuffer = new Uint8Array(await item.arrayBuffer()) const total = itemBuffer.byteLength const subranges = parseRange(total, range) // -1 signals an unsatisfiable range if (subranges == -1) { headers['content-range'] = `bytes */${total}` return new Response(null, { status: 416, headers }) } // -2 signals a malformed header string if (subranges == -2) { headers['content-length'] = String(total) return new Response(isHeadRequest ? null : itemBuffer, { status: 200, headers }) } if (subranges.length == 1) { const { start, end } = subranges[0] headers['content-range'] = `bytes ${start}-${end}/${total}` headers['content-length'] = String(end - start + 1) return new Response(isHeadRequest ? null : itemBuffer.slice(start, end), { status: 206, headers }) } else { const mime = headers['Content-Type'] headers['Content-Type'] = 'multipart/byteranges; boundary=3d6b6a416f9b5' const enc = new TextEncoder(); const boundaryString = '--3d6b6a416f9b5'; const type = mime ? enc.encode(`Content-Type: ${mime}\n`) : null const results = [] let bufferLength = 0 let boundary = enc.encode(`\n${boundaryString}\n`) subranges.forEach(function ({ start, end }) { { bufferLength += boundary.byteLength results.push(boundary) } if (type) { results.push(type) bufferLength += type.byteLength } { let content_range = enc.encode(`Content-Range: bytes ${start}-${end}/${total}\n\n`) bufferLength += content_range.byteLength results.push(content_range) } { let content = itemBuffer.slice(start, end) bufferLength += content.byteLength results.push(content) } }) { results.push(boundary) bufferLength += boundary.byteLength } const body = concat(results, bufferLength) const length = body.byteLength headers['content-length'] = String(length) return new Response(isHeadRequest ? null : body, { status: 206, headers }) } } function concat(views, length) { console.log({length}) const buf = new Uint8Array(length) let offset = 0 for (const v of views) { const uint8view = new Uint8Array(v.buffer, v.byteOffset, v.byteLength) buf.set(uint8view, offset) offset += uint8view.byteLength } return buf } function checkPreconditions(request, responseHeaders) { // https://httpwg.org/specs/rfc9110.html#rfc.section.13.2.2 // A recipient cache or origin server MUST evaluate the request preconditions defined by this specification in the following order: // 1. When recipient is the origin server and If-Match is present, evaluate the If-Match precondition: // - if true, continue to step 3 // - if false, respond 412 (Precondition Failed) unless it can be determined that the state-changing request has already succeeded (see Section 13.1.1) let header = request.headers.get("if-match"); if (typeof header === 'string') { console.log("!ifMatch(responseHeaders, header)", !ifMatch(responseHeaders, header)); if (!ifMatch(responseHeaders, header)) { return new Response(null, { status: 412 }); } // } else { // // 2. When recipient is the origin server, If-Match is not present, and If-Unmodified-Since is present, evaluate the If-Unmodified-Since precondition: // // - if true, continue to step 3 // // - if false, respond 412 (Precondition Failed) unless it can be determined that the state-changing request has already succeeded (see Section 13.1.4) // header = request.headers.get("if-unmodified-since"); // if (typeof header === 'string') { // // console.log("!ifUnmodifiedSince(responseHeaders, header)", !ifUnmodifiedSince(responseHeaders, header)); // if (!ifUnmodifiedSince(responseHeaders, header)) { // return new Response(null, { status: 412 }); // } // } } // 3. When If-None-Match is present, evaluate the If-None-Match precondition: // - if true, continue to step 5 // - if false for GET/HEAD, respond 304 (Not Modified) // - if false for other methods, respond 412 (Precondition Failed) header = request.headers.get("if-none-match"); const method = request.method; const get = "GET"; const head = "HEAD"; if (typeof header === 'string') { // console.log("!ifNoneMatch(responseHeaders, header)", !ifNoneMatch(responseHeaders, header)); if (!ifNoneMatch(responseHeaders, header)) { if (method === get || method === head) { return new Response(null, { status: 304, headers: responseHeaders }) } return new Response(null, { status: 412 }); } } else { // 4. When the method is GET or HEAD, If-None-Match is not present, and If-Modified-Since is present, evaluate the If-Modified-Since precondition: // - if true, continue to step 5 // - if false, respond 304 (Not Modified) if (method === get || method === head) { header = request.headers.get("if-modified-since"); if (typeof header === 'string') { // console.log("!ifModifiedSince(responseHeaders, header)", !ifModifiedSince(responseHeaders, header)); if (!ifModifiedSince(responseHeaders, header)) { return new Response(null, { status: 304, headers: responseHeaders }) } } } } // 5. When the method is GET and both Range and If-Range are present, evaluate the If-Range precondition: // - if true and the Range is applicable to the selected representation, respond 206 (Partial Content) // - otherwise, ignore the Range header field and respond 200 (OK) if (method === get) { if (request.headers.get("range")) { header = request.headers.get("if-range"); if (typeof header === 'string') { // console.log("!ifRange(responseHeaders, header)", !ifRange(responseHeaders, header)); if (!ifRange(responseHeaders, header)) { // We delete the range headers so that the `get` function will return the full body request.headers.delete("range") } } } } // 6. Otherwise, // - perform the requested method and respond according to its success or failure. return null; } function isWeak(etag) { return etag.startsWith("W/\""); } function isStrong(etag) { return etag.startsWith("\""); } function opaqueTag(etag) { if (isWeak(etag)) { return etag.substring(2); } return etag; } function weakMatch(a, b) { // https://httpwg.org/specs/rfc9110.html#entity.tag.comparison // two entity tags are equivalent if their opaque-tags match character-by-character, regardless of either or both being tagged as "weak". return opaqueTag(a) === opaqueTag(b); } function strongMatch(a, b) { // https://httpwg.org/specs/rfc9110.html#entity.tag.comparison // two entity tags are equivalent if both are not weak and their opaque-tags match character-by-character. return isStrong(a) && isStrong(b) && a === b; } function splitList(value) { return value.split(",").map(s => s.trim()); } // https://httpwg.org/specs/rfc9110.html#field.if-match function ifMatch(validationFields, header) { if (validationFields.ETag === undefined) { return true; } // 1. If the field value is "*", the condition is true if the origin server has a current representation for the target resource. if (header === "*") { if (validationFields.ETag !== undefined) { return true; } } else { // 2. If the field value is a list of entity tags, the condition is true if any of the listed tags match the entity tag of the selected representation. // An origin server MUST use the strong comparison function when comparing entity tags for If-Match (Section 8.8.3.2), // since the client intends this precondition to prevent the method from being applied if there have been any changes to the representation data. if (splitList(header).some(etag => { console.log(`strongMatch(${etag}, ${validationFields.ETag}) -- ${strongMatch(etag, validationFields.ETag)}`); return strongMatch(etag, validationFields.ETag) })) { return true; } } // 3. Otherwise, the condition is false. return false; } // https://httpwg.org/specs/rfc9110.html#field.if-none-match function ifNoneMatch(validationFields, header) { // 1. If the field value is "*", the condition is false if the origin server has a current representation for the target resource. if (header === "*") { if (validationFields.ETag !== undefined) { return false; } } else { // 2. If the field value is a list of entity tags, the condition is false if one of the listed tags matches the entity tag of the selected representation. // A recipient MUST use the weak comparison function when comparing entity tags for If-None-Match (Section 8.8.3.2), since weak entity tags can be used for cache validation even if there have been changes to the representation data. if (splitList(header).some(etag => weakMatch(etag, validationFields.ETag))) { return false; } } // 3. Otherwise, the condition is true. return true; } // https://httpwg.org/specs/rfc9110.html#field.if-modified-since function ifModifiedSince(validationFields, header) { // A recipient MUST ignore the If-Modified-Since header field if the received field value is not a valid HTTP-date, the field value has more than one member, or if the request method is neither GET nor HEAD. const date = new Date(header); if (isNaN(date)) { return true; } // 1. If the selected representation's last modification date is earlier or equal to the date provided in the field value, the condition is false. if (new Date(validationFields["Last-Modified"]) <= date) { return false; } // 2. Otherwise, the condition is true. return true; } // https://httpwg.org/specs/rfc9110.html#field.if-unmodified-since // function ifUnmodifiedSince(req, validationFields, header) { // // A recipient MUST ignore the If-Unmodified-Since header field if the received field value is not a valid HTTP-date (including when the field value appears to be a list of dates). // const date = new Date(header); // if (isNaN(date)) { // return true; // } // // 1. If the selected representation's last modification date is earlier than or equal to the date provided in the field value, the condition is true. // if (new Date(validationFields["Last-Modified"]) <= date) { // return true; // } // // 2. Otherwise, the condition is false. // return false; // } // https://httpwg.org/specs/rfc9110.html#field.if-range function ifRange(validationFields, header) { const date = new Date(header); console.log(new Date(validationFields["Last-Modified"]), date); console.log(new Date(validationFields["Last-Modified"]).getTime() === date.getTime()); if (!isNaN(date)) { // To evaluate a received If-Range header field containing an HTTP-date: // 1. If the HTTP-date validator provided is not a strong validator in the sense defined by Section 8.8.2.2, the condition is false. // 2. If the HTTP-date validator provided exactly matches the Last-Modified field value for the selected representation, the condition is true. if (new Date(validationFields["Last-Modified"]).getTime() === date.getTime()) { return true; } // 3. Otherwise, the condition is false. return false; } else { // To evaluate a received If-Range header field containing an entity-tag: // 1. If the entity-tag validator provided exactly matches the ETag field value for the selected representation using the strong comparison function (Section 8.8.3.2), the condition is true. if (strongMatch(header, validationFields.ETag)) { return true; } // 2. Otherwise, the condition is false. return false; } } ================================================ FILE: documentation/app/fastly.toml ================================================ # This file describes a Fastly Compute package. To learn more visit: # https://developer.fastly.com/reference/fastly-toml/ authors = ["jchampion@fastly.com"] description = "" language = "javascript" manifest_version = 2 name = "js-compute-reference-docs" service_id = "1B3wrEgiLdTaCjsmK5Jq25" [scripts] build = "yarn build" [local_server] [local_server.object_store] ================================================ FILE: documentation/app/package.json ================================================ { "license": "MIT", "devDependencies": { "@fastly/js-compute": "^3", "range-parser": "^1.2.1" }, "type": "module", "scripts": { "build": "npm run build:app && npm run build:files", "build:app": "js-compute-runtime src/index.js", "build:files": "compute-file-server-cli local --toml fastly.toml --name site -- ../build/", "deploy": "npm run deploy:app && npm run deploy:files", "deploy:app": "fastly compute publish", "deploy:files": "compute-file-server-cli upload --name 'js-docs-site' -- ../build/", "start": "fastly compute serve" } } ================================================ FILE: documentation/app/src/index.js ================================================ /// /* eslint-env serviceworker */ import { get } from "../c-at-e-file-server.js"; import { env } from "fastly:env"; addEventListener("fetch", (event) => event.respondWith(app(event))); async function app(event) { try { console.log(`FASTLY_SERVICE_VERSION: ${env('FASTLY_SERVICE_VERSION')}`) const response = await get('site', event.request) if (response) { response.headers.set("x-compress-hint", "on"); return response } else { return new Response("Not Found", { status: 404 }); } } catch (error) { console.error(error); return new Response(error.message + '\n' + error.stack, { status: 500 }) } } ================================================ FILE: documentation/app/version-redirects.json ================================================ { "latestByMajor": { "1": "1.13.0", "2": "2.5.0", "3": null } } ================================================ FILE: documentation/docs/acl/Acl/open.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.open() Opens the ACL with the given name, returning a new `Acl` instance with the given name on success. ## Syntax ```js Acl.open(name) ``` ### Return value An `Acl` instance. ================================================ FILE: documentation/docs/acl/Acl/prototype/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.prototype.lookup() The **`lookup(ipAddress)`** method returns the name associated with the `Acl` instance. ## Syntax ```js acl.lookup(ipAddress) ``` ### Parameters - `ipAddress` _: string_ - IPv4 or IPv6 address to lookup ### Return value An Object of the form `{ action: 'ALLOW' | 'BlOCK', prefix: string }`, where `prefix` is the IP address prefix that was matched in the ACL. ## Example ```js /// import { Acl } from 'fastly:acl'; addEventListener('fetch', async (evt) => { const myAcl = Acl.open('myacl'); const match = await myAcl.lookup(evt.client.address); evt.respondWith(new Response(match?.action === 'BLOCK' ? 'blocked' : 'allowed')); }); ``` ================================================ FILE: documentation/docs/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. >**Note**: Dynamic backends are by default disabled at the Fastly service level. Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request dynamic backends on Fastly Services. To disable the usage of dynamic backends, see [enforceExplicitBackends](../enforceExplicitBackends.mdx). ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. - `grpc` _: boolean_ _**optional**_ - **_Experimental feature_** - When enabled, sets that this backend is to be used for gRPC traffic. - _Warning: When using this experimental feature, no guarantees are provided for behaviours for backends that do not provide gRPC traffic._ All optional generic options can have their defaults set via [`setDefaultDynamicBackendConfig()`](../setDefaultDynamicBackendConfig.mdx). This includes all configuration options above except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. ### Return value A new `Backend` object. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/backend/Backend/exists.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.exists() The **`Backend.exists()`** method returns a boolean indicating if a Backend with the given name exists or not. ## Syntax ```js exists(name) ``` ### Return value A boolean indicating if a Backend with the given name exists or not. ================================================ FILE: documentation/docs/backend/Backend/fromName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.fromName() Returns the `Backend` instance with the given name, if one exists. If one does not exist, an error is thrown. ## Syntax ```js fromName(name) ``` ### Return value A `Backend` instance. ================================================ FILE: documentation/docs/backend/Backend/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.health() :::info This method is deprecated, use [`Backend.prototype.health`](./prototype/health.mdx) instead. ::: The **`Backend.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js Backend.health(backend) ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/docs/backend/Backend/prototype/betweenBytesTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.betweenBytesTimeout The read-only **`betweenBytesTimeout`** property of a `Backend` instance is an integer number providing the between bytes timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/docs/backend/Backend/prototype/connectTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.connectTimeout The read-only **`connectTimeout`** property of a `Backend` instance is an integer number providing the connect timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/docs/backend/Backend/prototype/firstByteTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.firstByteTimeout The read-only **`firstByteTimeout`** property of a `Backend` instance is an integer number providing the first byte timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/docs/backend/Backend/prototype/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.health() The **`Backend.prototype.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js health() ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/docs/backend/Backend/prototype/hostOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.hostOverride The read-only **`hostOverride`** property of a `Backend` instance is the host header override string used when sending requests to this backend. ## Value A `string`. ================================================ FILE: documentation/docs/backend/Backend/prototype/httpKeepaliveTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.httpKeepaliveTime The read-only **`httpKeepaliveTime`** property of a `Backend` instance is the HTTP keepalive time for this backend in milliseconds, or 0 if no keepalive is set. ## Value A `number`. ================================================ FILE: documentation/docs/backend/Backend/prototype/isDynamic.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isDynamic The read-only **`isDynamic`** property of a `Backend` instance is a boolean indicating if the backend was dynamically created for this service. ## Value A `boolean`. ================================================ FILE: documentation/docs/backend/Backend/prototype/isSSL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isSSL The read-only **`isSSL`** property of a `Backend` instance is a boolean indicating if the backend is using an SSL connection. ## Value A `boolean`. ================================================ FILE: documentation/docs/backend/Backend/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # name The read-only **`name`** property of the backend returns the backend name string. ## Value A `string`. ## Description Provides the name of the backend. ## Examples ### Using name The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/backend/Backend/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.port The read-only **`port`** property of a `Backend` instance is the port number of this backend. ## Value A `number`. ================================================ FILE: documentation/docs/backend/Backend/prototype/target.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.target The read-only **`target`** property of a `Backend` instance is the host string this backend is configured to use. ## Value A `string`. ================================================ FILE: documentation/docs/backend/Backend/prototype/tcpKeepalive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tcpKeepalive The read-only **`tcpKeepalive`** property of a `Backend` instance returns an object providing the TCP keepalive configuration, if any, otherwise returning `null` if TCP keepalive is not enabled. This object has the following properties: - `timeSecs` _: number or null._ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number or null._ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number or null._ - Number of probes to send to the backend before it is considered dead. ## Value A `Object` or `null`. ================================================ FILE: documentation/docs/backend/Backend/prototype/tlsMaxVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMaxVersion The read-only **`tlsMaxVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/docs/backend/Backend/prototype/tlsMinVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMinVersion The read-only **`tlsMinVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/docs/backend/Backend/prototype/toName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.toName() :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toName()`** method returns the name associated with the `Backend` instance. ## Syntax ```js toName() ``` ### Return value A string which contains the name of the Backend. ================================================ FILE: documentation/docs/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toString :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/backend/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends :::info This method is deprecated, and dynamic backends are now always supported when enabled at the service level. See [`enforceExplicitBackends`](./enforceExplicitBackends.mdx) instead. ::: The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: By default, while dynamic backends are allowed in the SDK, they are by default disabled at the Fastly service level. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ================================================ FILE: documentation/docs/backend/enforceExplicitBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enforceExplicitBackends Call this function to enforce the security property of explicitly-defined backends, even when dynamic backends are enabled at the Fastly service level. By default, if dynamic backends are supported for the Fastly service, they will be automatically used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a potential security concern since third-party JavaScript code may send arbitrary requests, including sensitive/secret data, off to destinations that the JavaScript project was not intending. When calling this function, an optional default backend name can be provided. >**Note**: This is a separate option to the service-level dynamic backend support for Fastly services, which is by deault disabled for Fastly services. The **`enforceExplicitBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: Dynamic Backends are disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled or disabled on Fastly Services. ## Syntax ```js enforceExplicitBackends(defaultBackend?) ``` ### Parameters - `defaultBackend` _: string_ _**optional**_ - An optional default backend string name to use in `fetch()` requests. ### Return value `undefined`. ================================================ FILE: documentation/docs/backend/setDefaultDynamicBackendConfig.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setDefaultDynamicBackendConfig() The **`setDefaultDynamicBackendConfig()`** allows setting backend configuration defaults that should apply to any newly created dynamic backends via the `new Backend()` constructor. ### Parameters - `defaultDynamicBackendConfig` - : An Object which contains the generic configuration options to apply to newly created Backends. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. ## Syntax ```js setDefaultDynamicBackendConfig(defaultConfig) ``` ### Return value None. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, with timeouts and TLS options provided from the default backend configuration options. import { allowDynamicBackends } from "fastly:experimental"; import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! // Timeouts and TLS configuration still get set from the default backend configuration above. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/cache/CacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.age The **`age`** method of the `CacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/docs/cache/CacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.body The **`body`** method of the `CacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this `CacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/docs/cache/CacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.close The **`close`** method of the `CacheEntry` interface closes the connection to the cache for this `CacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/docs/cache/CacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.hits The **`hits`** method of the `CacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/docs/cache/CacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.length The **`length`** method of the `CacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/docs/cache/CacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.maxAge The **`maxAge`** method of the `CacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/docs/cache/CacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `CacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/docs/cache/CacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.state The **`state`** method of the `CacheEntry` interface returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `CacheEntry` instance. ================================================ FILE: documentation/docs/cache/CacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.userMetadata The **`userMetadata`** method of the `CacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/docs/cache/CacheState/found.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.found The **`found`** method of the `CacheState` interface returns `true` if a cached item was located. Even if an cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. ## Syntax ```js found() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item was located or not. ================================================ FILE: documentation/docs/cache/CacheState/mustInsertOrUpdate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.mustInsertOrUpdate The **`mustInsertOrUpdate`** method of the `CacheState` interface returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. ## Syntax ```js mustInsertOrUpdate() ``` ### Parameters None. ### Return value A `boolean` which represents whether a fresh cached item was found not. ================================================ FILE: documentation/docs/cache/CacheState/stale.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.stale The **`stale`** method of the `CacheState` interface returns `true` if the cached item is stale. A cached item is stale if its age is greater than its `maxAge` period. ## Syntax ```js stale() ``` ### Parameters None. ### Return value A `boolean` which represents whether the cached item is stale or not. ================================================ FILE: documentation/docs/cache/CacheState/usable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.usable The **`usable`** method of the `CacheState` interface returns `true` if the cached item is usable. A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. ## Syntax ```js usable() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item is usable or not. ================================================ FILE: documentation/docs/cache/CoreCache/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.insert Performs a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. ## Syntax ```js insert(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item’s contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters ================================================ FILE: documentation/docs/cache/CoreCache/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.lookup Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. ## Syntax ```js lookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns `CacheEntry` if a usable cached item was found, otherwise returns `null`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/docs/cache/CoreCache/transactionLookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.transactionLookup Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. Request Collapsing: If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, just one of the callers will be instructed to insert the item into the cache as part of the transaction. The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. Revalidation: Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. ## Syntax ```js transactionLookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns an instance of `TransactionCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/docs/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/docs/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, and return a message stating whether the entry was in the Fastly Cache or not. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); return new Response(page ? `${path} is in the cache` : `${path} is not in the cache`, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } ``` ================================================ FILE: documentation/docs/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key`. If no entry is found (or has expired), the supplied `set` function is executed and its result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - The function to execute if and only if the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The maximum number of seconds to store the supplied entry in the cache. - `length` _: number_ __optional__ - The length of the value being stored within the cache. This is only used when the `value` is a `ReadableStream`. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/docs/cache/SimpleCache/purge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.purge purge the entry associated with the key `key` from the cache. ## Syntax ```js purge(key, options) ``` ### Parameters - `key` _: string_ - The key to purge from within the cache. - `options` _: object_ - `scope` _: string_ - : Where to purge the content from. - Possible values are: - "global" - This will remove the content from all of Fastly. - "pop" - This will remove the content from the POP that contains the currently executing instance. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `purge` querystring parameter, we purge the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('purge')) { SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/docs/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/docs/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/docs/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/docs/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/docs/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.age The **`age`** method of the `TransactionCacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.body The **`body`** method of the `TransactionCacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `TransactionCacheEntry`. An error will be thrown if a stream is already active for this `TransactionCacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.cancel The **`cancel`** method of the `TransactionCacheEntry` interface cancels an obligation to provide an object to the cache. ## Syntax ```js cancel() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.close The **`close`** method of the `TransactionCacheEntry` interface closes the connection to the cache for this `TransactionCacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.hits The **`hits`** method of the `TransactionCacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insert Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. ## Syntax ```js insert(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/insertAndStreamBack.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insertAndStreamBack Perform a transaction cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. ## Syntax ```js insertAndStreamBack(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns an array where the first item is a `FastlyBody` instance and the second item is a `CacheEntry` instance. ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.length The **`length`** method of the `TransactionCacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.maxAge The **`maxAge`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.state The **`state`** method of the `TransactionCacheEntry` interface returns a `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/update.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.update Perform an update of the cache item's metadata. ## Syntax ```js update(options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. ### Return value `undefined` ================================================ FILE: documentation/docs/cache/TransactionCacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.userMetadata The **`userMetadata`** method of the `TransactionCacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/docs/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) new CacheOverride(init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. This options is also the default when providing an init object directly as the first argument. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. - `beforeSend` _:Function_ _**optional**_ - `(request: Request) => void | PromiseLike` - Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. - See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) in the Fastly cache interfaces documentation for details. - `afterSend` _: Function_ _**optional**_ - `(response: Response) => void | CacheOptions | PromiseLike` - Callback to be invoked after a response has been sent, but before it is stored into the cache. - Where `CacheOptions` contains: - `cache` _: boolean | 'uncacheable'_ _**optional**_ - Whether to cache this response. By default, leaving this field empty, responses will be cached based on their cache header information. - Setting this to true or false will override this default cache behaviour, setting in the cache or not setting in the cache, even if the default behaviour would have been otherwise. - Setting to 'uncacheable' the response will not only not be cached, but the cache will record that the originating request led to an uncacheable response, so that future cache lookups will result in immediately going to the backend, rather than attempting to coordinate concurrent requests to reduce backend traffic. - See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) for more details on the mechanism that `uncacheable` disables. - `bodyTransformFn` _: Function_ _**optional**_ - `(body: Uint8Array) => Uint8Array | PromiseLike` - Provide a function to be used for transforming the response body prior to caching. - Body transformations are performed by specifying a transform, rather than by directly working with the body during the onAfterSend callback function, because not every response contains a fresh body: 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because they do not retransmit the body. - For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will be applied to it. The original backend body is passed in to the transform function, and the function is expected to return the new body. - See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) in the Fastly cache interfaces documentation for details. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/compute/purgeSurrogateKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # purgeSurrogateKey The **`purgeSurrogateKey()`** function is used to purge the given surrogate key string from Fastly's cache. There are two purge modes: soft purge and hard purge, with hard purge as the default which clears all items from the cache immediately. When using a soft purge, stale entries are maintained in the cache, reducing orgin load, while also enabling stale revalidations. See the [Fastly Purge Documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) for more information on caching and purge operations. ## Syntax ```js purgeSurrogateKey(surrogateKey, soft?) ``` ### Parameters - `surrogateKey` _: string_ - The surrogate key string - `soft?` _: boolean_ - Enables a soft purge, retaining stale entries in the cache. Default is a hard purge. ### Return value `undefined`. ================================================ FILE: documentation/docs/compute/vCpuTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # vCpuTime The **`vCpuTime()`** function provides the vCPU time used by the current request handler in milliseconds. ## Syntax ```js vCpuTime() ``` ### Parameters None. ### Return value `number`. ================================================ FILE: documentation/docs/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Defines a config store instance using the resource link name. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have a resource link named "animals" (which is linked to a config store) and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/device/Device/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.lookup() Look up the data associated with a particular User-Agent string. ## Syntax ```js lookup(userAgent) ``` ### Return value If there is data associated with the User-Agent, a `Device` instance is returned. Otherwise, `null` is returned. ================================================ FILE: documentation/docs/device/Device/prototype/brand.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.brand The read-only **`brand`** property of the `Device` interface is either a string stating the brand of the device, which can be different from the manufacturer of that device. If no brand is known, the value will be `null`. ## Value Either a string value if a brand is known, otherwise `null`. ================================================ FILE: documentation/docs/device/Device/prototype/hardwareType.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.hardwareType The read-only **`hardwareType`** property of the `Device` interface is either a string stating the hardware type of the device, or `null` if the hardware type is not known. A string representation of the device's primary platform hardware. The most commonly used device types are also identified via boolean variables. Because a device may have multiple device types and this variable only has the primary type, we recommend using the boolean variables for logic and using this string representation for logging. ## Value Either a string value if a hardware type is known, otherwise `null`. ================================================ FILE: documentation/docs/device/Device/prototype/isBot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isBot The read-only **`isBot`** property of the `Device` interface is either a boolean stating if the device is a bot, or `null` if the this is not known. ## Value Either a boolean stating if the device is a bot, or `null` if the this is not known. ================================================ FILE: documentation/docs/device/Device/prototype/isDesktop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isDesktop The read-only **`isDesktop`** property of the `Device` interface is either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ## Value Either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ================================================ FILE: documentation/docs/device/Device/prototype/isGameConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isGameConsole The read-only **`isGameConsole`** property of the `Device` interface is either a boolean stating if the device is a video game console, or `null` if the this is not known. ## Value Either a boolean stating if the device is a video game console, or `null` if the this is not known. ================================================ FILE: documentation/docs/device/Device/prototype/isMediaPlayer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMediaPlayer The read-only **`isMediaPlayer`** property of the `Device` interface is either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ## Value Either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ================================================ FILE: documentation/docs/device/Device/prototype/isMobile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMobile The read-only **`isMobile`** property of the `Device` interface is either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ## Value Either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ================================================ FILE: documentation/docs/device/Device/prototype/isSmartTV.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isSmartTV The read-only **`isSmartTV`** property of the `Device` interface is either a boolean stating if the device is a smart TV, or `null` if the this is not known. ## Value Either a boolean stating if the device is a smart TV, or `null` if the this is not known. ================================================ FILE: documentation/docs/device/Device/prototype/isTablet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTablet The read-only **`isTablet`** property of the `Device` interface is either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ## Value Either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ================================================ FILE: documentation/docs/device/Device/prototype/isTouchscreen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTouchscreen The read-only **`isTouchscreen`** property of the `Device` interface is either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ## Value Either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ================================================ FILE: documentation/docs/device/Device/prototype/model.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.model The read-only **`model`** property of the `Device` interface is either a string stating the model of the device, or `null` if the model is not known. ## Value Either a string value if a model is known, otherwise `null`. ================================================ FILE: documentation/docs/device/Device/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.name The read-only **`name`** property of the `Device` interface is either a string stating the name of the device, or `null` if the name is not known. ## Value Either a string value if a name is known, otherwise `null`. ================================================ FILE: documentation/docs/device/Device/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toJSON The `toJSON()` method of the Device interface is a serializer; it returns a JSON representation of the Device object. To get a JSON string, you can use `JSON.stringify(device)` directly; it will call `toJSON()` automatically. ## Syntax ```js toJSON() ``` ### Return value A JSON object that is the serialization of the Device object. ================================================ FILE: documentation/docs/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Dictionary()` :::info This Class is deprecated ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/edge-rate-limiter/EdgeRateLimiter/EdgeRateLimiter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `EdgeRateLimiter()` The **`EdgeRateLimiter` constructor** lets you open an epen a [ERL](https://docs.fastly.com/products/edge-rate-limiting) with the given ratecounter and penaltybox. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new EdgeRateLimiter(rateCounter, penaltyBox) ``` > **Note:** `EdgeRateLimiter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `rateCounter` _: RateCounter_ - The RateCounter instance to associate with this EdgeRateLimiter instance - `penaltyBox` _: PenaltyBox_ - The PenaltyBox instance which should be associated with this EdgeRateLimiter instance ### Return value A new `EdgeRateLimiter` object. ### Exceptions - `TypeError` - Thrown if the provided rateCounter value is not an instance of RateCounter - Thrown if the provided penaltyBox value is not an instance of PenaltyBox ================================================ FILE: documentation/docs/edge-rate-limiter/EdgeRateLimiter/prototype/checkRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EdgeRateLimiter.prototype.checkRate Increment an entry in the rate counter and check if the entry has exceeded some average number of requests per second (RPS) over the given window. If the entry is over the RPS limit for the window, add to the penaltybox for the given `timeToLive`. Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ## Syntax ```js checkRate(entry, delta, window, limit, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to increment and check - `delta` _: number_ - The amount to increment the `entry` by - `window` _: number_ - The time period to check across, has to be either 1 second, 10 seconds, or 60 seconds - `limit` _: number_ - The requests-per-second limit - `timeToLive` _: number_ - In minutes, how long the entry should be added into the penalty-box - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `true` if the entry has exceeded the average RPS for the window, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive finite number. - Thrown if the provided `window` value is not either, 1, 10, or 60. - Thrown if the provided `limit` value is not a positive finite number. - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/docs/edge-rate-limiter/PenaltyBox/PenaltyBox.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `PenaltyBox()` The **`PenaltyBox` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for adding and checking if some entry is in the dataset. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new PenaltyBox(name) ``` > **Note:** `PenaltyBox()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a PenaltyBox with the given name ### Return value A new `PenaltyBox` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/docs/edge-rate-limiter/PenaltyBox/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.add Add an `entry` into the PenaltyBox for the duration of the given `timeToLive`. ## Syntax ```js add(entry, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `timeToLive` _: number_ - In minutes, how long the entry should be added into the PenaltyBox - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/docs/edge-rate-limiter/PenaltyBox/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.has Check if the given entry is contained in in the PenaltyBox instance. ## Syntax ```js has(entry) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up ### Return value Returns `true` if the entry is contained in the PenaltyBox instance, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string ================================================ FILE: documentation/docs/edge-rate-limiter/RateCounter/RateCounter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `RateCounter()` The **`RateCounter` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for counting and rate calculations. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new RateCounter(name) ``` > **Note:** `RateCounter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a RateCounter with the given name ### Return value A new `RateCounter` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/docs/edge-rate-limiter/RateCounter/prototype/increment.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.increment Increment the given `entry` in the RateCounter instance with the given `delta` value. ## Syntax ```js increment(entry, delta) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `delta` _: number_ - The amount to increment the entry by ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive, finite number. ================================================ FILE: documentation/docs/edge-rate-limiter/RateCounter/prototype/lookupCount.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupCount Look up the current rate for the given `entry` and the given `duration`. ## Syntax ```js lookupCount(entry, duration) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `duration` _: number_ - The duration to lookup alongside the entry, has to be either, 10, 20, 30, 40, 50, or 60 seconds. ### Return value Returns a number which is the count for the given `entry` and `duration` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `duration` value is not either, 10, 20, 30, 40, 50 or 60. ================================================ FILE: documentation/docs/edge-rate-limiter/RateCounter/prototype/lookupRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupRate Look up the current rate for the given `entry` and the given `window`. ## Syntax ```js lookupRate(entry, window) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `window` _: number_ - The window to look up alongside the entry, has to be either 1 second, 10 seconds, or 60 seconds ### Return value Returns a number which is the rate for the given `entry` and `window` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `window` value is not either, 1, 10, or 60. ================================================ FILE: documentation/docs/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabledOrConfig` _: boolean_ - Whether or not to allow Dynamic Backends or - `enabledOrConfig` _: object_ - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to https://www.fastly.com/ and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/experimental/mapAndLogError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapAndLogError The **`mapAndLogError()`** function calls `mapError` on an `Error` object and sends the output to standard error. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapAndLogError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value `undefined`. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { mapAndLogError(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | mapAndLogError(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/docs/experimental/mapError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapError The **`mapError()`** function extracts information from an `Error` object as a human-readable array of strings. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value Returns an array of `string`s. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { console.error(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | console.error(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/docs/experimental/sdkVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sdkVersion The read-only **`sdkVersion`** property is a string whose indicates what JavaScript SDK version is being used. ## Value A string value. ================================================ FILE: documentation/docs/experimental/setReusableSandboxOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setReusableSandboxOptions The **`setReusableSandboxOptions()`** function configures the reuse of the same underlying sandbox for multiple requests, which can improve performance by avoiding the overhead of initializing a new sandbox for each request. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js setReusableSandboxOptions(options) ``` ### Parameters - `options` _: Object_ - The configuration options for the reusable sandbox. - `maxRequests` _: number_ (default: `1`, `0` means unlimited) - The maximum number of requests that can be handled by a single sandbox before it is recycled. - `betweenRequestTimeoutMs` _: number_ (default: not specified) - The amount of time in milliseconds to wait between requests before recycling the sandbox. - `maxMemoryMiB` _: number_ (default: no limit) - The maximum amount of memory in MiB that the sandbox can use before it is recycled. - `sandboxTimeoutMs` _: number_ (default: no timeout) - The maximum amount of time in milliseconds that a sandbox can be active before it is recycled. ================================================ FILE: documentation/docs/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/docs/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object`, or `null` if no geolocation data was found. The object contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/docs/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/docs/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/docs/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/docs/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/docs/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/docs/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/docs/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/docs/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/docs/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/docs/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/docs/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/docs/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/docs/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/docs/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/docs/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/docs/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/docs/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/docs/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/docs/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/docs/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/docs/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/docs/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/docs/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/docs/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/docs/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/docs/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/docs/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/docs/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/docs/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/docs/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/docs/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/docs/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/docs/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/docs/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/docs/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/docs/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/docs/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/Blob/Blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob() The **`Blob()`** constructor creates a `Blob` object, which represents a file-like object of immutable, raw data. ## Syntax ```js new Blob() new Blob(array) new Blob(array, options) ``` > **Note:** `Blob()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `array` _**optional**_ - : An array of values to include in the `Blob`. These can be [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx), [`Blob`](../../globals/Blob/Blob.mdx), or strings. If any of these elements is a [`Blob`](../../globals/Blob/Blob.mdx), its content (and not the object itself) is copied into the Blob being constructed. - `options` _**optional**_ - : An object containing optional attributes for the `Blob`. - `type` - : A string indicating the MIME type of the data. The default value is the empty string `""`. - `endings` - : A string indicating how to handle line endings in the data. This can be either `"transparent"` (default) to keep line endings unchanged, or `"native"` to convert line endings to the platform's native line endings (e.g., `\r\n` on Windows). ### Return value A new `Blob` object containing the specified data. ## Description `Blob` objects represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting its functionality and expanding it to support files on the user's system. To construct a `Blob` from other non-blob objects and data, use the `Blob()` constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](../../globals/Blob/prototype/slice.mdx) method. The `type` property of a `Blob` object will match the MIME type specified in the constructor's `options` parameter, defaulting to an empty string if not specified. ================================================ FILE: documentation/docs/globals/Blob/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.arrayBuffer() The **`arrayBuffer()`** method of the `Blob` interface returns a `Promise` that resolves with an `ArrayBuffer` containing the entire contents of the `Blob` as binary data. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A `Promise` that resolves with an `ArrayBuffer` containing the blob's data. ================================================ FILE: documentation/docs/globals/Blob/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.size The **`size`** read-only property of the `Blob` interface returns the size of the `Blob` in bytes. ## Value A number representing the size of the `Blob` in bytes. ================================================ FILE: documentation/docs/globals/Blob/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.slice() The **`slice()`** method of the `Blob` interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. ## Syntax ```js slice() slice(start) slice(start, end) slice(start, end, contentType) ``` ### Parameters - `start` _**optional**_ - : The 0-based index of the first byte to include in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is 0. - `end` _**optional**_ - : The 0-based index of the first byte that will not be included in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is `size`. - `contentType` _**optional**_ - : A string indicating the content type to assign to the new `Blob`. The default value is an empty string. ### Return value A new `Blob` object containing the specified subset of data. ================================================ FILE: documentation/docs/globals/Blob/prototype/stream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.stream() The **`stream()`** method of the `Blob` interface returns a `ReadableStream` that can be used to read the contents of the `Blob`. ## Syntax ```js stream() ``` ### Parameters None. ### Return value A `ReadableStream` that provides the data contained within the `Blob`. ================================================ FILE: documentation/docs/globals/Blob/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.text() The **`text()`** method of the `Blob` interface returns a `Promise` that resolves with a string containing the contents of the blob, interpreted as UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a string containing the blob's data as a text string. The data is always interpreted as UTF-8. ================================================ FILE: documentation/docs/globals/Blob/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.type The **`type`** read-only property of the `Blob` interface returns the MIME type of the `Blob`. ## Value A string indicating the MIME type of the `Blob`. If the type cannot be determined, this returns an empty string. ================================================ FILE: documentation/docs/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/docs/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/docs/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/docs/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/docs/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/docs/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/docs/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/docs/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/docs/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/docs/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/docs/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/docs/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/docs/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/docs/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/docs/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/docs/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/docs/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/docs/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/docs/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/docs/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/docs/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/docs/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/docs/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/docs/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/docs/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/docs/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/docs/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/docs/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/docs/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/docs/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/docs/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/docs/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/docs/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/docs/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/docs/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/docs/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/docs/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/docs/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/docs/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/docs/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/docs/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/docs/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/docs/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/docs/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/docs/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/docs/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/docs/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/docs/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/docs/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/docs/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/docs/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/docs/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/docs/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/docs/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/docs/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/docs/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/docs/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/docs/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/docs/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/docs/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/docs/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/docs/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/docs/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/docs/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/docs/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/docs/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/docs/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/docs/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/docs/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/docs/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/docs/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/docs/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/docs/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/docs/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/docs/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/docs/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/docs/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/docs/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/docs/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/docs/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/docs/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/docs/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/docs/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/docs/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/docs/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/docs/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/docs/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/docs/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/docs/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/docs/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/docs/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/docs/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/docs/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/docs/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/docs/globals/EcKeyImportParams/EcKeyImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcKeyImportParams The **`EcKeyImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as ECDSA. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ================================================ FILE: documentation/docs/globals/EcdsaParams/EcdsaParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcdsaParams The **`EcdsaParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `hash` - : A string. An identifier for the digest algorithm to use. This should be one of the following: - `SHA-256`: selects the SHA-256 algorithm. - `SHA-384`: selects the SHA-384 algorithm. - `SHA-512`: selects the SHA-512 algorithm. > **Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used. ================================================ FILE: documentation/docs/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/docs/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/docs/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/docs/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/docs/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/docs/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/docs/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. While these fields are always defined on Compute, they may be *null* when not available in testing environments such as Viceroy. - `FetchEvent.client.requestId` _**readonly**_ - : A UUID generated by Compute for each request. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : Either `null`, or a [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. - `FetchEvent.client.tlsJA3MD5` _**readonly**_ - : Either `null` or a string representation of the JA3 hash of the TLS ClientHello message. - `FetchEvent.client.tlsCipherOpensslName` _**readonly**_ - : Either `null` or a string representation of the cipher suite used to secure the client TLS connection. - `FetchEvent.client.tlsProtocol` _**readonly**_ - : Either `null` or a string representation of the TLS protocol version used to secure the client TLS connection. - `FetchEvent.client.tlsClientCertificate` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw client certificate in the mutual TLS handshake message. It is in PEM format. Returns an empty ArrayBuffer if this is not mTLS or available. - `FetchEvent.client.tlsClientHello` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw bytes sent by the client in the TLS ClientHello message. - `FetchEvent.client.tlsJA4` _**readonly**_ - : Either `null` or a string representation of the JA4 fingerprint of the TLS ClientHello message. - `FetchEvent.client.h2Fingerprint` _**readonly**_ - : Either `null` or a string representation of the HTTP/2 fingerprint for HTTP/2 connections. Returns `null` for HTTP/1.1 connections. - `FetchEvent.client.ohFingerprint` _**readonly**_ - : Either `null` or a string representation of the Original Header fingerprint based on the order and presence of request headers. - `FetchEvent.server` _**readonly**_ - : Information about the server receiving the request for the Fastly Compute service. - `FetchEvent.server.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the server which received the request. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.sendEarlyHints()`](./prototype/sendEarlyHints.mdx) - : Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/docs/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/docs/globals/FetchEvent/prototype/sendEarlyHints.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.sendEarlyHints() The **`sendEarlyHints()`** method allows you to send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response back to the client which made the incoming request to your application. ## Syntax ```js sendEarlyHints(headers) ``` ### Parameters - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../Headers/Headers.mdx) object or object literal of [`String`](../../String/String.mdx) key/value pairs. ### Return value Always returns `undefined`. ### Examples ```js event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'] ]); ``` ================================================ FILE: documentation/docs/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/docs/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/docs/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/docs/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/FormData/FormData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData() The **`FormData()`** constructor creates a new `FormData` object. ## Syntax ```js new FormData() new FormData(form) ``` > **Note:** `FormData()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `form` _**optional**_ - : An HTML `
` element — when specified, the `FormData` object will be populated with the form's current key/value pairs using the name property of each element for the keys and their submitted value for the values. File input elements are handled specially: their values are taken from the files selected by the user in the upload control. ### Return value A new `FormData` object, pre-populated with form data if the optional `form` parameter was provided. ## Description The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using methods such as `fetch()`. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also append additional data to the `FormData` object after it's created using its various methods. A `FormData` object can be used in a number of ways with other APIs: 1. It can be sent with the `fetch()` API 2. It works seamlessly with the `Request` and `Response` objects - it can be used directly as the body of a `Request` object 3. It can be obtained from a `Response` object using the `formData()` method 4. It can be passed directly to the `URLSearchParams` constructor The transmitted data is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to `"multipart/form-data"`. ================================================ FILE: documentation/docs/globals/FormData/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.append() The **`append()`** method of the `FormData` interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. ## Syntax ```js append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/docs/globals/FormData/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.delete() The **`delete()`** method of the `FormData` interface removes all key/value pairs with the given name from the `FormData` object. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value `undefined` ================================================ FILE: documentation/docs/globals/FormData/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.entries() The **`entries()`** method of the `FormData` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator yields a new array for each key/value pair, with the first element being the key and the second element being the value. ## Syntax ```js entries() ``` ### Return value An `iterator`. ================================================ FILE: documentation/docs/globals/FormData/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.forEach() The **`forEach()`** method of the `FormData` interface executes the provided callback function once for each key/value pair in the `FormData` object. ## Syntax ```js forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each entry in the object. The function will be passed the following arguments: - `value` - : The value of the current entry. - `key` - : The key of the current entry. - `formData` - : The `FormData` object being traversed. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined` ================================================ FILE: documentation/docs/globals/FormData/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.get() The **`get()`** method of the `FormData` interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the [`getAll()`](../../../globals/FormData/prototype/getAll.mdx) method instead. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value A `FormDataEntryValue` containing the value. If the key does not exist, it returns `null`. ================================================ FILE: documentation/docs/globals/FormData/prototype/getAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.getAll() The **`getAll()`** method of the `FormData` interface returns all the values associated with a given key from within a `FormData` object. ## Syntax ```js getAll(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value An array of `FormDataEntryValue` items containing all values with the given key. If the key doesn't exist, an empty array is returned. ================================================ FILE: documentation/docs/globals/FormData/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.has() The **`has()`** method of the `FormData` interface returns a boolean indicating whether a `FormData` object contains a key/value pair with the given name. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the key you want to test for existence. ### Return value `true` if a key/value pair with the specified name exists; otherwise `false`. ================================================ FILE: documentation/docs/globals/FormData/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.keys() The **`keys()`** method of the `FormData` interface returns an iterator allowing iteration through all keys contained in this object. The iterator yields the key for each value. ## Syntax ```js keys() ``` ### Return value An `iterator`. ================================================ FILE: documentation/docs/globals/FormData/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.set() The **`set()`** method of the `FormData` interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and [`append()`](../../../globals/FormData/prototype/append.mdx) is that if the specified key already exists, `set()` overwrites all existing values with the new one, whereas `append()` appends the new value onto the end of the existing values. ## Syntax ```js set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/docs/globals/FormData/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.values() The **`values()`** method of the `FormData` interface returns an iterator allowing iteration through all values contained in this object. The iterator yields the value for each key/value pair. ## Syntax ```js values() ``` ### Return value An `iterator`. ================================================ FILE: documentation/docs/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/docs/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/docs/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/docs/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/docs/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/docs/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/docs/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/docs/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/docs/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/docs/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/docs/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/docs/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/docs/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/docs/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name doesn't match the [field-name](https://httpwg.org/specs/rfc9110.html#fields.names) production in the HTTP specification, this method throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/docs/globals/Headers/prototype/getSetCookie.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.getSetCookie() The **`getSetCookie()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns an array of all the values of the `Set-Cookie` headers, returning an empty list if none are present. ## Syntax ```js getSetCookie() ``` ### Return value `String[]` representing the list of `Set-Cookie` headers. ================================================ FILE: documentation/docs/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/docs/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/docs/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/docs/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/docs/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/docs/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/docs/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/docs/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/docs/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/docs/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/docs/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/docs/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/docs/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/docs/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/docs/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/docs/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/docs/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/docs/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/docs/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/docs/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/docs/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/docs/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2 or greater than π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/docs/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/docs/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex where x is a number very close to 0, you should get an answer very close to 1 + x, because limx0ex1x=1. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/docs/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/docs/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/docs/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/docs/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/docs/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/docs/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/docs/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/docs/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/docs/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/docs/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/docs/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/docs/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/docs/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/docs/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/docs/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/docs/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/docs/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/docs/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/docs/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/docs/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/docs/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/docs/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/docs/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/docs/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/docs/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/docs/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/docs/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/docs/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/docs/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/docs/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/docs/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/docs/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/docs/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/docs/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/docs/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/docs/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/docs/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/docs/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/docs/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/docs/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/docs/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/docs/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/docs/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/docs/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/docs/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/docs/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/docs/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/docs/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/docs/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/docs/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/docs/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/docs/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/docs/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/docs/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/docs/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/docs/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/docs/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/docs/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/docs/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/docs/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/docs/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/docs/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/docs/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/docs/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/docs/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/docs/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/docs/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/docs/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/docs/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/docs/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/docs/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/docs/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/docs/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/docs/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/docs/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/docs/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/docs/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/docs/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/docs/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/docs/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/docs/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/docs/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/docs/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/docs/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/docs/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/docs/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/docs/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/docs/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/docs/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/docs/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/docs/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/docs/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/docs/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/docs/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/docs/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/docs/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/docs/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/docs/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/docs/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/docs/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/docs/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/docs/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/docs/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/docs/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/docs/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/docs/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/docs/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/docs/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/docs/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/docs/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/docs/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/docs/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/docs/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/docs/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/docs/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/docs/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/docs/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/docs/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/docs/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/docs/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/docs/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/docs/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/docs/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/docs/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/docs/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/docs/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/docs/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/docs/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/docs/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/docs/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/docs/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, a `ReadableStream` object, a [`Blob`](../../globals/Blob/Blob.mdx) object, or a [`FormData`](../../globals/FormData/FormData.mdx) object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_, see [`CacheOverride`](../../fastly:cache-override/CacheOverride/CacheOverride.mdx). - `cacheKey` _**Fastly-specific**_ - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ================================================ FILE: documentation/docs/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/docs/globals/Request/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.blob() The **`blob()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. ================================================ FILE: documentation/docs/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/docs/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/docs/globals/Request/prototype/clone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.clone() The **`clone()`** method of the `Request` interface creates a copy of the current `Request` object. Like the underlying `ReadableStream.tee`` api, the `body` of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Beware when you construct a `Request` from a stream and then `clone` it. `clone()` throws a `TypeError` if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) If you intend to modify the request, you may prefer the `Request` constructor. ## Syntax ```js clone() ``` ### Parameters None. ### Return value A `Request` object, which is an exact copy of the `Request` that `clone()` was called on. ================================================ FILE: documentation/docs/globals/Request/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.formData() The **`formData()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. - `SyntaxError` - : Thrown if the request's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/docs/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/docs/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/docs/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/docs/globals/Request/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Request` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Request instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/docs/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/docs/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - [`Blob`](../../globals/Blob/Blob.mdx) - [`FormData`](../../globals/FormData/FormData.mdx) - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ================================================ FILE: documentation/docs/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/docs/globals/Response/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.blob() The **`blob()`** method of the [`Response`](../Response.mdx) interface takes a [`Response`](../Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. ================================================ FILE: documentation/docs/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/docs/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/docs/globals/Response/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.formData() The **`formData()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. - `SyntaxError` - : Thrown if the response's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/docs/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/docs/globals/Response/prototype/ip.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ip The **`ip`** getter of the `Response` interface returns the IP address associated with the request, as either an IPv6 or IPv4 string. In the case where no IP address is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with an IP, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `string`. ================================================ FILE: documentation/docs/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/docs/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/docs/globals/Response/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.port The **`port`** getter of the `Response` interface returns the port associated with the request, as a number. In the case where no port is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with a port, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `number`. ================================================ FILE: documentation/docs/globals/Response/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Response` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Response instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/docs/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/docs/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/docs/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/docs/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/docs/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/docs/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/docs/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/docs/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/docs/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/docs/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/docs/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/docs/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/docs/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/docs/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/docs/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/docs/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/docs/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/docs/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/docs/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/docs/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/docs/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/docs/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/docs/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/docs/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/docs/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/docs/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/docs/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/docs/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/docs/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/docs/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/docs/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/docs/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/docs/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/docs/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/docs/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/docs/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/docs/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/docs/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/docs/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/docs/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/docs/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/docs/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/docs/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/docs/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/docs/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/docs/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/docs/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/docs/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/docs/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/docs/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/docs/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/docs/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/docs/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/docs/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/docs/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/docs/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/docs/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/docs/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - For ECDSA: Pass an [`EcKeyImportParams`](../../EcKeyImportParams/EcKeyImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/docs/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/docs/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/docs/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/docs/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/docs/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/docs/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/docs/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/docs/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/docs/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/docs/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/docs/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/docs/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/docs/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/docs/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/docs/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/docs/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/docs/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/docs/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/docs/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/docs/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/docs/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/docs/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/docs/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/docs/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/docs/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/docs/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](https://en.wikipedia.org/wiki/HZ_(character_encoding)). ================================================ FILE: documentation/docs/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/docs/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/docs/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/docs/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/docs/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/docs/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/docs/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/docs/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/docs/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/docs/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/docs/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/docs/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/docs/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/docs/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/docs/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/docs/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/docs/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/docs/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/docs/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/docs/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/docs/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/docs/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/docs/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/docs/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/docs/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/docs/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/docs/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/docs/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/docs/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/docs/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/docs/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/docs/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/docs/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/docs/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/docs/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/docs/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/docs/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/docs/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/docs/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/docs/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/docs/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/docs/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/docs/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/docs/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/docs/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/docs/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/docs/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/docs/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/docs/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/docs/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/docs/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/docs/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/docs/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/docs/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/docs/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/docs/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/docs/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/docs/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/docs/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/docs/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/docs/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/docs/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/docs/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/docs/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/docs/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/docs/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/docs/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/docs/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Explicit Backends Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service. This `backend` option is then a special Fastly-specific fetch option that is provided to the `fetch()` call: ```js fetch('https://origin.com/path', { backend: 'origin' }); ``` Backends are configured using the Fastly service backend configuration, see the [Backend documentation](https://developer.fastly.com/reference/api/services/backend/) for more information. ## Dynamic Backends Dynamic backends are a compute feature that allow services to define backends for themselves. If the `backend` option is not provided when making `fetch()` requests, a backend will be automatically created by extracting the protocol, host, and port from the provided URL. In addition, custom backend configuration options can then also be provided through the [`Backend()`](../fastly:backend/Backend/Backend.mdx) constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ - `imageOptimizerOptions` _**Fastly-specific**_, see [`imageOptimizerOptions`](../fastly:image-optimizer/imageOptimizerOptions.mdx). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/docs/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/docs/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/docs/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/docs/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/docs/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/docs/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/docs/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/docs/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/docs/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/docs/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/docs/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/docs/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/docs/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/after.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # after The `after` method inserts content after the closing tag of the element. ## Syntax ```js element.after(content); element.after(content, options); ``` ### Parameters - `content` _: string_ - The content to insert after the element's closing tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.after("World"); // Result:
Hello
World ``` ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # append The `append` method inserts content at the end of the element's content. ## Syntax ```js element.append(content); element.append(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the end of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.append(", World"); // Result:
Hello, World
``` ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/before.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # before The `before` method inserts content before the opening tag of the element. ## Syntax ```js element.before(content); element.before(content, options); ``` ### Parameters - `content` _: string_ - The content to insert before the element's opening tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.before("Well"); // Result: Well
Hello
``` ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/hasAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # hasAttribute The `hasAttribute` method returns a `boolean` value indicating whether the specified attribute is present on the element. ## Syntax ```js element.hasAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to check for. ### Return value A boolean value indicating whether the attribute is present. ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/prepend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # prepend The `prepend` method inserts content at the beginning of the element's content. ## Syntax ```js element.prepend(content); element.prepend(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the beginning of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.prepend("Well, "); // Result:
Well, Hello
``` ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/removeAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # removeAttribute The `removeAttribute` method removes the specified attribute from the element. ## Syntax ```js element.removeAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to remove. ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/replaceChildren.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceChildren The `replaceChildren` method replaces the element's children with new content. ## Syntax ```js element.replaceChildren(content); element.replaceChildren(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element's children with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceChildren("Greetings!"); // Result:
Greetings!
``` ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/replaceWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceWith The `replaceWith` method replaces the element with new content. ## Syntax ```js element.replaceWith(content); element.replaceWith(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceWith("

Greetings!

"); // Result:

Greetings!

``` ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/selector.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # selector The `selector` read-only property is a `string` representing the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) that matches the element. ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/setAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setAttribute The `setAttribute` method sets the value of the specified attribute on the element. If the value already exists, it will be updated; otherwise, a new attribute with the specified name and value will be added to the element. ## Syntax ```js element.setAttribute(attributeName, value); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to set. - `value` _: string_ - The value to assign to the attribute. ================================================ FILE: documentation/docs/html-rewriter/Element/prototype/tag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # tag The `tag` read-only property is a `string` representing the tag name of the element. ================================================ FILE: documentation/docs/html-rewriter/HTMLRewritingStream/HTMLRewritingStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `HTMLRewritingStream()` The **`HTMLRewritingStream`** lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback. This callback can manipulate the attributes of the element, and add or remove content from the immediate context. ## Syntax ```js new HTMLRewritingStream() ``` ### Return value A new `HTMLRewritingStream` object. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/docs/html-rewriter/HTMLRewritingStream/prototype/onElement.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # onElement ▸ **onElement**`(selector: string, handler: (element: Element) => void): this` Registers an element handler with the [`HTMLRewritingStream`] that will be called for each [`Element`] that matches the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) `selector`. Elements added by handlers will not be processed by other handlers. ## Syntax ```js .onElement(selector, handler) ``` ### Parameters - `selector` _: string_ - A CSS selector that determines the elements for which `handler` will be called - The following types of CSS selector are supported: Currently the rewriter supports the following CSS selectors: | Pattern | Description | |----------------------|----------------------------------------------------------------------------| | `*` | Any element | | `E` | All elements of type `E` | | `E F` | `F` elements inside `E` elements | | `E > F` | `F` elements directly inside `E` elements | | `E:nth-child(n)` | The n-th child of type `E` | | `E:first-child` | First child of type `E` | | `E:nth-of-type(n)` | The n-th sibling of type `E` | | `E:first-of-type` | First sibling of type `E` | | `E:not(s)` | Type `E` elements not matching selector `s` | | `E.myclass` | Type `E` elements with class `"myclass"` | | `E#myid` | Type `E` elements with ID `"myid"` | | `E[attr]` | Type `E` elements with attribute `attr` | | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | | `E[attr="val" i]` | Type `E` elements where `attr` is `"val"`, case-insensitive | | `E[attr="val" s]` | Type `E` elements where `attr` is `"val"`, case-sensitive | | `E[attr~="val"]` | Type `E` elements where `attr` contains `"val"` in a space-separated list | | `E[attr`|`;="val"]`| Type `E` elements where `attr` is hyphen-separated and starts with `"val"` | | `E[attr^="val"]` | Type `E` elements where `attr` starts with `"val"` | | `E[attr$="val"]` | Type `E` elements where `attr` ends with `"val"` | | `E[attr*="val"]` | Type `E` elements where `attr` contains `"val"` | - `handler` _: (element: Element) => void_ - A callback function that will be called once for each element that matches `selector` ### Return value The `HTMLRewritingStream`, so multiple calls to `onElement` can be chained. ### Exceptions - `Error` - If the provided `selector` is not a valid CSS selector. - If the provided `handler` is not a function. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/docs/image-optimizer/Auto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Auto` Enumerator options for [`imageOptimizerOptions.auto`](./imageOptimizerOptions.mdx). ## Constants - `AVIF` (`"avif"`) If the browser's Accept header indicates compatibility, deliver an AVIF image. - `WEBP` (`"webp"`) If the browser's Accept header indicates compatibility, deliver a WebP image. ## Examples ```js import { Auto, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, auto: Auto.AVIF }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/BWAlgorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `BWAlgorithm` Enumerator options for [`imageOptimizerOptions.bw`](./imageOptimizerOptions.mdx). ## Constants - `Threshold` (`"threshold"`) Uses a luminance threshold to convert the image to black and white. - `Atkinson` (`"atkinson"`) Uses [Atkinson dithering](https://en.wikipedia.org/wiki/Atkinson_dithering) to convert the image to black and white. ## Examples ```js import { Region, BWAlgorithm } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, bw: BWAlgorithm.Threshold }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/CropMode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CropMode` Enumerator options for [`imageOptimizerOptions.crop.mode`](./imageOptimizerOptions.mdx) and `imageOptimizerOptions.precrop.mode`. ## Constants - `Smart` (`"smart"`) Enables content-aware algorithms to attempt to crop the image to the desired aspect ratio while intelligently focusing on the most important visual content, including the detection of faces. - `Safe` (`"safe"`) Allow cropping out-of-bounds regions. ## Examples ```js import { CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Smart, } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/Disable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Disable` Enumerator options for [`imageOptimizerOptions.disable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Prevent images being resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Disable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, disable: Disable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/Enable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Enable` Enumerator options for [`imageOptimizerOptions.enable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Allow images to be resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Enable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, enable: Enable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/Fit.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Fit` Enumerator options for [`imageOptimizerOptions.fit`](./imageOptimizerOptions.mdx). ## Constants - `Bounds` (`"bounds"`) Resize the image to fit entirely within the specified region, making one dimension smaller if needed. - `Cover` (`"cover"`) Resize the image to entirely cover the specified region, making one dimension larger if needed. - `Crop` (`"crop"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Fit, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 150, height; 150, fit: Fit.Bounds }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/Format.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Format` Enumerator options for [`imageOptimizerOptions.format`](./imageOptimizerOptions.mdx). ## Constants - `Auto` (`"auto"`) Automatically use the best format based on browser support and image/transform characteristics - `AVIF` (`"avif"`) AVIF - `BJPG` (`"bjpg"`) Baseline JPEG - `GIF` (`"gif"`) Graphics Interchange Format - `JPG` (`"jpg"`) JPEG - `JXL` (`"jxl"`) JPEGXL - `MP4` (`"mp4"`) MP4 (H.264) - `PJPG` (`"pjpg"`) Progressive JPEG - `PJXL` (`"pjxl"`) Progressive JPEGXL - `PNG` (`"png"`) Portable Network Graphics - `PNG8` (`"png8"`) Portable Network Graphics palette image with 256 colors and 8-bit transparency - `SVG` (`"svg"`) Scalable Vector Graphics - `WEBP` (`"webp"`) WebP - `WEBPLL` (`"webpll"`) WebP (Lossless) - `WEBPLY` (`"webply"`) WebP (Lossy) ## Examples ```js import { Format, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/Metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Metadata` Enumerator options for [`imageOptimizerOptions.metadata`](./imageOptimizerOptions.mdx). ## Constants - `Copyright` (`"copyright"`) Preserve [copyright notice](https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#copyright-notice), creator, credit line, licensor, and web statement of rights fields. - `C2PA` (`"c2pa"`) Preserve the [C2PA manifest](https://c2pa.org/) and add any transformations performed by Fastly Image Optimizer. - `CopyRightAndC2PA` (`"copyright,c2pa"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Metadata, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, metadata: Metadata.Copyright }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/Optimize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Optimize` Enumerator options for [`imageOptimizerOptions.optimize`](./imageOptimizerOptions.mdx). ## Constants - `Low` (`"low"`) Output image quality will be similar to the input image quality. - `Medium` (`"medium"`) More optimization is allowed. We attempt to preserve the visual quality of the input image. - `High` (`"high"`) Minor visual artifacts may be visible. This produces the smallest file. ## Examples ```js import { Optimize, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, optimize: Optimize.High }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/Orient.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Orient` Enumerator options for [`imageOptimizerOptions.orient`](./imageOptimizerOptions.mdx). ## Constants - `Default` (`"1"`) - `FlipHorizontal` (`"2"`) - `FlipHorizontalAndVertical` (`"3"`) - `FlipVertical` (`"4"`) - `FlipHorizontalOrientLeft` (`"5"`) - `OrientRight` (`"6"`) - `FlipHorizontalOrientRight` (`"7"`) - `OrientLeft` (`"8"`) ## Examples ```js import { Orient, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, orient: Orient.FlipHorizontal }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/Profile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Profile` Enumerator options for [`imageOptimizerOptions.profile`](./imageOptimizerOptions.mdx). ## Constants - `Baseline` (`"baseline"`) The profile recommended for video conferencing and mobile applications. (Default) - `Main` (`"main"`) The profile recommended for standard-definition broadcasts. - `High` (`"high"`) The profile recommended for high-definition broadcasts. ## Examples ```js import { Profile, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, profile: Profile.Main }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/Region.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Region` Enumerator options for [`imageOptimizerOptions.region`](./imageOptimizerOptions.mdx). ## Constants - `UsEast` (`"us_east"`) - `UsCentral` (`"us_central"`) - `UsWest` (`"us_west"`) - `EuCentral` (`"eu_central"`) - `EuWest` (`"eu_west"`) - `Asia` (`"asia"`) - `Australia` (`"australia"`) ## Examples ```js import { Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/ResizeFilter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ResizeFilter` Enumerator options for [`imageOptimizerOptions.resizeFilter`](./imageOptimizerOptions.mdx). ## Constants - `Nearest` (`"nearest"`) Uses the value of nearby translated pixel values. - `Bilinear` (`"bilinear"`) Uses an average of a 2x2 environment of pixels. - `Linear` (`"linear"`) Same as `Bilenear`. - `Bicubic` (`"bicubic"`) Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. - `Cubic` (`"cubic"`) Same as `Bicubic`. - `Lanczos2` (`"lanczos2"`) Uses the Lanczos filter to increase the ability to detect edges and linear features within an image and uses sinc resampling to provide the best possible reconstruction. - `Lanczos3` (`"lanczos3"`) Lanczos3 uses a better approximation of the sinc resampling function. (Default) - `Lanczos` (`"lanczos"`) Same as `Lanczos3`. ## Examples ```js import { ResizeFilter, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, resizeFilter: ResizeFilter.Linear }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/image-optimizer/imageOptimizerOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `imageOptimizerOptions` Options specified in the [`Request`](../globals/Request/Request.mdx) constructor for running the [Fastly Image Optimizer](https://docs.fastly.com/products/image-optimizer). More detailed documentation on all Image Optimizer options is available in the [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/). ## Parameters All parameters other than `region` are optional. - `region`: _[`Region`](./Region.mdx)_ Where image optimizations should occur. - `auto`: _[`Auto`](./Auto.mdx)_ Enable optimization features automatically. - `bgColor`: _[`Color`](#color)_ Set the background color of an image. - `blur`: _`number` (0.5-1000) or [`Percentage`](#percentage)_ Set the blurriness of the output image. - `brightness`: _`number` (-100-100)_ Set the brightness of the output image. - `bw`: _[`BWAlgorithm`](./BWAlgorithm.mdx)_ Convert an image to black and white. - `canvas`: _`Object`_ Increase the size of the canvas around an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `contrast`: _`number` (-100-100)_ Set the contrast of the output image. - `crop`: _`Object`_ Remove pixels from an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `mode` (optional): _[`CropMode`](./CropMode.mdx)_ - `disable`: _[`Disable`](./Disable.mdx)_ Disable functionality that is enabled by default. - `dpr`: `number` Ratio between physical pixels and logical pixels. - `enable`: _[`Enable`](./Enable.mdx)_ Enable functionality that is disabled by default. - `fit`: _[`Fit`](./Fit.mdx)_ Set how the image will fit within the size bounds provided. - `format`: _[`Format`](./Format.mdx)_ Specify the output format to convert the image to. - `frame`: _`number` (must have the value 1)_ Extract the first frame from an animated image sequence. - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the height of the image. - `level`: _`String` containing one of the [allowed values](https://www.fastly.com/documentation/reference/io/level/#allowed-values)_ Specify the level constraints when converting to video. - `metadata`: _[`Metadata`](./Metadata.mdx)_ Control which metadata fields are preserved during transformation. - `optimize`: _[`Optimize`](./Optimize.mdx)_ Automatically apply optimal quality compression. - `orient`: _[`Orient`](./Orient.mdx)_ Change the cardinal orientation of the image. - `pad`: _[`Sides`](#sides)_ Add pixels to the edge of an image. - `precrop`: _`Object`_ Remove pixels from an image before any other transformations occur. - `size`: _[`Size`](#size)_ - `position`: _[`Position`](#position)_ - `mode`: _[`CropMode`](./CropMode.mdx)_ - `profile`: _[`Profile`](./Profile.mdx)_ Specify the profile class of application when converting to video. - `quality`: _`integer` (1-100)_ Optimize the image to the given compression level for lossy file formatted images. - `resizeFilter`: _[`ResizeFilter`](./ResizeFilter.mdx)_ Specify the resize filter used when resizing images. - `saturation`: _`number` (-100-100)_ Set the saturation of the output image. - `sharpen`: _`Object`_ Set the sharpness of the output image. - `amount`: _`number` (0-10)_ - `radius`: _`number` (0.5-1000)_ - `threshold`: _`integer` (0-255)_ - `trim`: _[`Sides`](#sides)_ Remove pixels from the edge of an image. - `viewbox`: _`number` (must have the value 1)_ Remove explicit width and height properties in SVG output. - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the width of the image. ## Types ### Color Either: - a 3 or 6 character hexadecimal string - an `Object` containing: - `r`: _`integer` (0-255)_ Red component - `g`: _`integer` (0-255)_ Green component - `b`: _`integer` (0-255)_ Blue component - `a` (optional): _`number` (0.0-1.0)_ Alpha component ### Percentage A `String` containing a number suffixed with a percent sign (%). ### Position An `Object` containing: - Exactly one of: - `x`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetX`: _`number` (interpreted as a percentage)_ - Exactly one of: - `y`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetY`: _`number` (interpreted as a percentage)_ ### Sides An `Object` containing `top`, `bottom`, `left`, and `right`, all of which are either an `integer` or [`Percentage`](#percentage). ### Size An `Object` containing either: - `absolute`: _`Object`_ - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `ratio`: _`Object`_ - `width`: _`number`_ - `height`: _`number`_ ## Examples ```js import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG, bgColor: { 'r': 100, 'g': 255, 'b': 9, 'a': 0.5 }, blur: '1%', brightness: -20, contrast: -20, height: 600, level: '4.0', orient: Orient.FlipVertical, saturation: 80, sharpen: { 'amount': 5, 'radius': 6, 'threshold': 44 }, canvas: { 'size': { 'absolute': { 'width': 400, 'height': 400 } } }, crop: { size: { absolute: { width: 200, height: 200 }, mode: CropMode.Safe } }, trim: { top: 10, left: 10, right: 10, bottom: 10 }, pad: { top: 30, left: 30, right: "1%", bottom: 30 } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/docs/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/docs/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a KV store instance using the resource link name. ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/docs/kv-store/KVStore/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.delete Deletes the value associated with the key `key` in the KV store. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value Returns `undefined` ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - Does not exist ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then delete the entry. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') await files.delete('hello') const entry = await files.get('hello') if (entry) { return new Response(await entry.text()) } else { return new Response('no file named hello exists') } } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/docs/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/docs/kv-store/KVStore/prototype/list.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.list The **`list()`** can be used to list the keys of a store. ## Syntax ```js list(options?) ``` ### Parameters - `options` _: object_ _**optional**_ - List options supporting properties: - `cursor` _: string_ _**optional**_ - The cursor used to pick up from a previous iteration. - `limit` _: number_ _**optional**_ - The maximum number of keys to return. - `prefix` _: string_ _**optional**_ - List only those keys that start with the given string prefix. - `noSync` _: boolean_ _**optional**_ - Do not sync the key list first, instead provide a possibly out-of-date listing. May be faster but inconsistent. ### Return value Returns a `Promise` which resolves with `{ list: string[], cursor: string | undefined }`. ## Example In this example we list the keys of a KV Store named `'files'`, iterating 10 at a time, counting the total; ```js /// import { KVStore } from 'fastly:kv-store'; async function app(event) { const files = new KVStore('files'); let cursor, list, total = 0; do { ({ cursor, list } = await files.list({ limit: 10, cursor })); total += list?.length; } while (list); return new Response(`Iterated ${total} entries`); } addEventListener('fetch', (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value, options?) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. - `options` _: object_ _**optional**_ - An insert options parameter, supporting: - `metadata` _: ArrayBuffer | TypedArray | DataView_ _**optional**_ - Binary metadata associated with the entry, may be up to 1000 bytes. - `ttl` _: number_ _**optional**_ - TTL for the entry - `mode` _: 'overwrite' | 'add' | 'append' | 'prepend'_ _**optional**_ - Insert mode, defaults to 'overwrite' - `gen` _: number_ _**optional**_ - 'generation' header specific to the version of an entry key ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - `TypeError` - If the provided `gen`: - Is not an number ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/docs/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/docs/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/docs/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/docs/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/docs/kv-store/KVStoreEntry/prototype/metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadata() The `metadata()` method of the `KVStoreEntry` interface provides the binary metadata associated with the `KVStoreEntry`. The metadata binary may be up to 1000 bytes, and is returned as a `Uint8Array` TypedArray buffer, if metadata is set, or null otherwise. ## Syntax ```js metadata() ``` ### Parameters None. ### Return value A `Promise` that resolves to a `Uint8Array` buffer object. ================================================ FILE: documentation/docs/kv-store/KVStoreEntry/prototype/metadataText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadataText() The `metadataText()` method of the `KVStoreEntry` interface provides a String interpretation of binary metadata associated with the `KVStoreEntry`. If the binary data is not a valid string, an encoding error will be thrown. ## Syntax ```js metadataText() ``` ### Parameters None. ### Return value A `Promise` that resolves to a String. ================================================ FILE: documentation/docs/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/docs/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; const logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; let logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/logger/configureConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # configureConsole The **`configureConsole()`** function allows configuring the behaviour of the `console` global JS logger. ## Syntax ```js configureConsole(loggingOptions) ``` ### Parameters - `loggingOptions` _: object_ - - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ## Examples In this example, we disable prefixing for `console.log` and use `stderr` output for `console.error`: ```js import { configureConsole } from "fastly:logger"; configureConsole({ prefixing: false, stderr: true }); async function handleRequest(event) { console.log(JSON.stringify(event.request.headers)); const url = new URL(event.request.url); try { validate(url); } catch (e) { console.error(`Validation error: ${e}`); return new Response('Bad Request', { status: 400 }); } return new Response('OK'); } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/docs/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v2 to v3` ## SimpleCache.delete renamed to SimpleCache.purge and requires purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using `SimpleCache.delete` to `SimpleCache.purge` with the same purging behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/docs/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a Secret Store instance using the resource link name. ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/docs/secret-store/SecretStore/fromBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fromBytes The **`fromBytes()`** function is used to create an in-memory secret from an array buffer. >**Note**: This API should be avoided when possible, by instead using [SecretStore.prototype.get](./prototype/get.mdx) to obtain secure secrets. ## Syntax ```js fromBytes(new Uint8Array([1, 2, 3])) ``` ### Parameters None. ### Return value Returns a `SecretStoreEntry`. ================================================ FILE: documentation/docs/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/docs/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/docs/secret-store/SecretStoreEntry/prototype/rawBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.rawBytes ▸ **rawBytes**(): `Uint8Array` Returns the raw byte contents of the SecretStoreEntry instance as a Uint8Array. ## Syntax ```js rawBytes() ``` ### Parameters None. ### Return value A Uint8Array ### Exceptions The `rawBytes()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ================================================ FILE: documentation/docs/security/inspect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # inspect The **`inspect()`** function inspects a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). ## Syntax ```js inspect(request, config); ``` ### Parameters - `request` _: Request_ - The Request to get a WAF determination for. - `config` _: object_ - `corp` _: string_ - Set a corp name for the configuration. - This parameter is currently required. - `workspace` _: string_ - Set a workspace name for the configuration. - This parameter is currently required. - `overrideClientIp` _: string_ - Specify an explicit client IP address to inspect. - By default, `inspect` will use the IP address that made the request to the running Compute service, but you may want to use a different IP when service chaining or if requests are proxied from outside of Fastly’s network. ### Return value Returns an `Object` with the `inspect` response, with the following fields: - `waf_response` _: number_ - Security status code. - `redirect_url` _: string | null_ - A redirect URL returned from Security. - `tags` _: string[]_ - Tags returned by Security. - `verdict` _: string_ - The outcome of inspecting a request with Security. It can be one of the following: - `"allow"` - Security indicated that this request is allowed. - `"block"` - Security indicated that this request should be blocked. - `"unauthorized"` - Security indicated that this service is not authorized to inspect a request. - Other verdicts may be returned but not currently documented. - `decision_ms` _: number_ - How long Security spent determining its verdict, in milliseconds. ## Examples ```js /// import { inspect } from "fastly:security"; async function app(event) { const res = inspect(event.request, { corp: "mycorp", workspace: "myws" }); switch (res.verdict) { case "allow": return await fetch(event.request); case "block": return new Response("Request Blocked", { status: 400 }); case "unauthorized": return new Response("Unauthorized", { status: 401 }); default: return new Response("idk", { status: 500 }); } } addEventListener("fetch", (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/docs/shielding/Shield/Shield.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Shield()` Load information about the given shield. Returns an object representing the shield if it is active, or throws an exception if the string is malformed or the shield doesn’t exist. Shield names are defined on [this webpage](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations), in the “shield code” column. For example, the string “pdx-or-us” will look up our Portland, OR, USA shield site, while “paris-fr” will look up our Paris site. If you are using a major cloud provider for your primary origin site, consider looking at the “Recommended for” column, to find the Fastly POP most closely located to the given cloud provider. ## Syntax ```js new Shield(name) ``` > **Note:** `Shield()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Exceptions - `TypeError` - Thrown if no Shield exists with the provided name ## Examples In this example, we create a Shield instance for the Sydney, Australia shield POP. If the code is running on that shield POP, it fetches directly from origin. Otherwise, it routes the request through the shield using an encrypted connection. ```js /// import { Shield } from "fastly:shielding"; async function app(event) { const shield = new Shield('wsi-australia-au'); // If running on the shield POP, fetch from the origin directly if (shield.runningOn()) { return await fetch('https://http-me.fastly.com/anything', { backend: 'httpme' }); } // Otherwise, route the request through the shield using an encrypted connection return await fetch(event.request, { backend: shield.encryptedBackend() }); } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/docs/shielding/Shield/prototype/encryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.encryptedBackend ▸ **encryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an encrypted connection to the POP. For reference, this is almost always the backend that you want to use. Only use [`Shield::unencryptedBackend`](./unencryptedBackend.mdx) in situations in which you are 100% sure that all the data you will send and receive over the backend is already encrypted. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/docs/shielding/Shield/prototype/runningOn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.runningOn ▸ **runningOn**(): `boolean` Returns whether we are currently operating on the given shield. Technically, this may also return true in very isolated incidents in which Fastly is routing traffic from the target shield POP to the POP that this code is running on, but in these situations the results should be approximately identical. (For example, it may be the case that you are asking to shield to ‘pdx-or-us’. But, for load balancing, performance, or other reasons, Fastly is temporarily shifting shielding traffic from Portland to Seattle. In that case, this function may return true for hosts running on ‘bfi-wa-us’, our Seattle site, because effectively the shield has moved to that location. This should give you a slightly faster experience than the alternative, in which this function would return false, you would try to forward your traffic to the Portland site, and then that traffic would be caught and redirected back to Seattle.) ================================================ FILE: documentation/docs/shielding/Shield/prototype/unencryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.unencryptedBackend ▸ **unencryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an unencrypted connection to the POP. Generally speaking, we encourage users to use [`Shield::encryptedBackend`](./encryptedBackend.mdx) instead of this function. Data sent over this backend – the unencrypted version – will be sent over the open internet, with no protections. In most cases, this is not what you want. However, in some cases – such as when you want to ship large data blobs that you know are already encrypted — using these backends can prevent a double-encryption performance penalty. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/docs/websocket/createWebsocketHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createWebsocketHandoff The **`createWebsocketHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Websocket, to the declared backend. ## Syntax ```js createWebsocketHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Websocket. - `backend` _: string_ - The name of the backend that Websocket should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Websocket. ```js import { createWebsocketHandoff } from "fastly:websocket"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createWebsocketHandoff(event.request, 'websocket_backend'); } else { return new Response('oopsie, make a request to /stream for some websocket goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/docusaurus.config.js ================================================ // @ts-check // Note: type annotations allow type checking and IDEs autocompletion const {themes} = require('prism-react-renderer'); const lightCodeTheme = themes.github; const darkCodeTheme = themes.dracula; /** @type {import('@docusaurus/types').Config} */ const config = { webpack: { jsLoader: (isServer) => ({ loader: require.resolve('swc-loader'), options: { jsc: { parser: { syntax: 'ecmascript', jsx: true, }, target: 'es2017', transform: { react: { runtime: 'automatic' } } }, module: { type: isServer ? 'commonjs' : 'es6', }, }, }), }, plugins: [ require.resolve("@cmfcmf/docusaurus-search-local"), ], title: '@fastly/js-compute', tagline: 'Javascript SDK and CLI for Fastly Compute', url: 'https://js-compute-reference-docs.edgecompute.app', baseUrl: '/', onBrokenLinks: 'throw', favicon: './fastly-favicon-default.svg', organizationName: 'fastly', projectName: 'js-compute-runtime', i18n: { defaultLocale: 'en', locales: ['en'], }, presets: [ [ 'classic', /** @type {import('@docusaurus/preset-classic').Options} */ ({ docs: { includeCurrentVersion: false, }, theme: { customCss: require.resolve('./src/css/custom.css'), }, }), ], ], staticDirectories: ['static'], scripts: [ '/fiddle.js', ], markdown: { hooks: { onBrokenMarkdownLinks: 'throw'} }, themeConfig: /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ ({ navbar: { title: '@fastly/js-compute', items: [ { type: 'docsVersionDropdown', }, {href: 'https://developer.fastly.com/', label: 'Fastly Developer Hub', position: 'left'}, {href: 'https://developer.fastly.com/solutions/examples/javascript/', label: 'Code Examples', position: 'left'}, {href: 'https://fiddle.fastly.dev', label: 'Fastly Fiddle', position: 'left'}, { href: 'https://twitter.com/FastlyDevs/', label: 'Twitter', position: 'right', }, { href: 'https://github.com/fastly/js-compute-runtime/', label: 'GitHub', position: 'right', }, ], }, footer: { style: 'dark', copyright: `Copyright © ${new Date().getFullYear()} Fastly Inc. All rights reserved. Portions of this content are ©1998–2023 by individual mozilla.org contributors. Content available under a CC-BY-SA 2.5 license.`, }, prism: { theme: lightCodeTheme, darkTheme: darkCodeTheme, }, }), }; module.exports = config; ================================================ FILE: documentation/generate-version-redirects.mjs ================================================ #!/usr/bin/env node import { readFileSync, writeFileSync } from 'fs'; import { join, dirname } from 'path'; import { fileURLToPath } from 'url'; const __dirname = dirname(fileURLToPath(import.meta.url)); const versionsPath = join(__dirname, 'versions.json'); const versions = JSON.parse(readFileSync(versionsPath, 'utf-8')); // Find latest version for each major version (versions.json is already sorted newest first) const latestByMajor = {}; for (const version of versions) { const major = version.split('.')[0]; if (!latestByMajor[major]) { latestByMajor[major] = version; } } // Latest major redirects to /docs/ (no version in path) const latestMajor = Math.max(...Object.keys(latestByMajor).map(Number)); latestByMajor[latestMajor] = null; const outputPath = join(__dirname, 'app', 'version-redirects.json'); writeFileSync(outputPath, JSON.stringify({ latestByMajor }, null, 2)); ================================================ FILE: documentation/package.json ================================================ { "scripts": { "docusaurus": "docusaurus", "start": "docusaurus start", "build": "node --max-old-space-size=8000 node_modules/.bin/docusaurus build && npm run generate-version-redirects", "swizzle": "docusaurus swizzle", "deploy": "npm run build && cd app && npm install && npm run deploy", "clear": "docusaurus clear", "serve": "docusaurus serve", "write-translations": "docusaurus write-translations", "write-heading-ids": "docusaurus write-heading-ids", "remove-fastly-prefix": "node rename-docs.mjs remove-prefix", "add-fastly-prefix": "node rename-docs.mjs add-prefix", "generate-version-redirects": "node generate-version-redirects.mjs" }, "devDependencies": { "@cmfcmf/docusaurus-search-local": "^2.0.1", "@docusaurus/core": "3.9.2", "@docusaurus/module-type-aliases": "3.9.2", "@docusaurus/preset-classic": "3.9.2", "@mdx-js/react": "^3.1.1", "@swc/core": "^1.15.2", "clsx": "^2.1.1", "prism-react-renderer": "^2.4.1", "react": "^19.2.0", "react-dom": "^19.2.0", "swc-loader": "^0.2.6" }, "overrides": { "cheerio": "1.0.0-rc.9" } } ================================================ FILE: documentation/rename-docs.mjs ================================================ /** * The docs site relies on path names like "fastly:backend", which * are not compatible in Windows. * * This script handles renaming the docs site folders to be prefixed with fastly: or not */ import { readdirSync, renameSync } from 'node:fs'; const subsystems = [ 'acl', 'backend', 'cache-override', 'cache', 'compute', 'config-store', 'device', 'dictionary', 'edge-rate-limiter', 'env', 'experimental', 'fanout', 'websocket', 'geolocation', 'kv-store', 'logger', 'object-store', 'secret-store', 'html-rewriter', 'image-optimizer', 'security', 'shielding' ]; const files = readdirSync('docs'); const direction = process.argv[2] || (files.some(f => f.startsWith('fastly:')) ? 'remove-prefix' : 'add-prefix'); for (const file of files) { if (direction === 'remove-prefix' && file.startsWith('fastly:')) { if (!subsystems.includes(file.slice(7))) console.error(`missing subsystem - ${file.slice(7)}`); renameSync(`docs/${file}`, `docs/${file.slice(7)}`); } else if (subsystems.includes(file)) { renameSync(`docs/${file}`, `docs/fastly:${file}`); } } const versions = readdirSync('versioned_docs'); for (const version of versions) { const files = readdirSync(`versioned_docs/${version}`); for (const file of files) { if (direction === 'remove-prefix' && file.startsWith('fastly:')) { if (!subsystems.includes(file.slice(7))) console.error(`missing subsystem - ${file.slice(7)}`); renameSync(`versioned_docs/${version}/${file}`, `versioned_docs/${version}/${file.slice(7)}`); } else if (subsystems.includes(file)) { renameSync(`versioned_docs/${version}/${file}`, `versioned_docs/${version}/fastly:${file}`); } } } if (direction === 'remove-prefix') console.log('Renamed docs to remove prefix (for committing to git)'); else console.log('Renamed docs for building with fastly: prefix'); ================================================ FILE: documentation/sidebars.js ================================================ /** * Creating a sidebar enables you to: - create an ordered group of docs - render a sidebar for each doc of that group - provide next/previous navigation The sidebars can be generated from the filesystem, or explicitly defined here. Create as many sidebars as you want. */ // @ts-check /** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ const sidebars = { // By default, Docusaurus generates a sidebar from the docs folder structure sidebar: [{type: 'autogenerated', dirName: '.'}], // But you can create a sidebar manually /* sidebar: [ 'intro', 'hello', { type: 'category', label: 'Tutorial', items: ['tutorial-basics/create-a-document'], }, ], */ }; module.exports = sidebars; ================================================ FILE: documentation/src/components/HomepageFeatures/index.js ================================================ import React from 'react'; import clsx from 'clsx'; import styles from './styles.module.css'; const FeatureList = [ { title: 'Service Worker API', description: ( <> Applications are written using the same Service Worker API that is used for browsers. Aiming to make it simpler to re-use code across different environments. ), }, { title: 'Powered by SpiderMonkey', description: ( <> Built using the same secure, well-tested, standards-compliant JavaScript engine which powers Mozilla's Firefox. ), }, { title: 'Open source', description: ( <> Want to see behind the curtains?
View the GitHub Repository.
Your contributions are welcomed and appreciated. ), }, ]; function Feature({Svg, title, description}) { return (

{title}

{description}

); } export default function HomepageFeatures() { return (
{FeatureList.map((props, idx) => ( ))}
); } ================================================ FILE: documentation/src/components/HomepageFeatures/styles.module.css ================================================ .features { display: flex; align-items: center; padding: 2rem 0; width: 100%; } ================================================ FILE: documentation/src/components/fiddle/index.js ================================================ import React, { useState, useEffect } from "react"; function hexString(buffer) { return [...(new Uint8Array(buffer))].map(val => val.toString(16).padStart(2, '0')).join(''); } function compat(data) { if (!('requests' in data) || ('reqUrl' in data)) { const { reqUrl, reqMethod, reqHeaders, reqBody, purgeFirst, enableCluster, enableShield, useH2, requests, ...retainedProps } = data; purgeFirst; // Discard this return { ...retainedProps, requests: (requests || []).concat({ path: reqUrl, method: reqMethod, headers: reqHeaders, body: reqBody, enableCluster, enableShield, enableWAF: false, connType: useH2 ? 'h2' : 'h1' }) }; } else if ('requests' in data && data.requests[0] && 'useH2' in data.requests[0]) { const { requests, ...retainedProps } = data; return { ...retainedProps, requests: requests.map(({ useH2, ...retainedProps2 }) => ({ ...retainedProps2, connType: useH2 ? 'h2' : 'h1' })) }; } else { return data; } } async function getFrameUrl(config) { let data = compat(config); const hashInp = JSON.stringify(data); const hashInpBuf = (new TextEncoder()).encode(hashInp); const hash = await globalThis.crypto.subtle.digest('SHA-256', hashInpBuf); const immutID = 'x' + hexString(hash).substr(0, 7); const fiddleHost = 'https://fiddle.fastly.dev'; const fiddleCheck = await fetch(fiddleHost + '/fiddle/' + immutID, { headers: { Accept: 'application/json' } }); if (fiddleCheck.ok) { return fiddleHost + '/fiddle/' + immutID + '/embedded'; } const createRes = await fetch(fiddleHost + '/fiddle', { method: 'POST', body: JSON.stringify({ ...data, immutable: true }), headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); const createData = await createRes.json(); if (createData.fiddle) { return fiddleHost + '/fiddle/' + createData.fiddle.id + '/embedded'; } return false; } let idx = 0; export function Fiddle({config, children}) { const [frameUrl, setFrameUrl] = useState(null); async function fetchFrameUrl(config) { setFrameUrl(await getFrameUrl(config)); } useEffect(() => { fetchFrameUrl(config); }, [config]); if (!frameUrl) { return <>{children} } const embedID = 'embed-' + idx; idx += 1; const queryParams = [`embedID=${embedID}`]; const src = `${frameUrl}?${queryParams.join('&')}`; return
Loading example code...
; } ================================================ FILE: documentation/src/css/custom.css ================================================ /** * Any CSS included here will be global. The classic template * bundles Infima by default. Infima is a CSS framework designed to * work well for content-centric websites. */ /* You can override the default Infima variables here. */ :root { --ifm-color-primary: rgba(46, 133, 85, 1.0); --ifm-color-primary-dark: rgba(41, 120, 76, 1.0); --ifm-color-primary-darker: rgba(39, 113, 72, 1.0); --ifm-color-primary-darkest: rgba(32, 93, 59, 1.0); --ifm-color-primary-light: rgba(51, 146, 93, 1.0); --ifm-color-primary-lighter: rgba(53, 153, 98, 1.0); --ifm-color-primary-lightest: rgba(60, 173, 110, 1.0); --ifm-code-font-size: 95%; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1); } /* For readability concerns, you should choose a lighter palette in dark mode. */ [data-theme='dark'] { --ifm-color-primary: rgb(38, 194, 160); --ifm-color-primary-dark: hsl(167, 68%, 41%); --ifm-color-primary-darker: hsl(167, 68%, 38%); --ifm-color-primary-darkest: hsl(167, 68%, 32%); --ifm-color-primary-light: hsl(167, 68%, 50%); --ifm-color-primary-lighter: hsl(167, 68%, 52%); --ifm-color-primary-lightest: hsl(167, 68%, 59%); --docusaurus-highlighted-code-line-bg: hsla(0, 0%, 0%, 0.3); --ifm-color-content: var(--ifm-color-emphasis-900); --ifm-color-content-inverse: var(--ifm-color-white); --ifm-color-content-secondary: #525860; --ifm-background-color: transparent; /* Body's background. */ --ifm-background-surface-color: var(--ifm-color-content-inverse); --ifm-global-border-width: 1px; --ifm-global-radius: 0.4rem; --aa-muted-color-rgb: 38, 194, 160 !important; --aa-icon-color-rgb: 38, 194, 160 !important; --aa-text-color-rgb: 38, 194, 160 !important; --aa-primary-color-rgb: 38, 194, 160 !important; --aa-muted-color-rgb: 38, 194, 160 !important; --aa-panel-border-color-rgb: 38, 194, 160 !important; --aa-input-border-color-rgb: 38, 194, 160 !important; --aa-background-color-rgb: 255, 255, 255; --aa-input-background-color-rgb: 255, 255, 255; --aa-selected-color-rgb: 179, 173, 214; --aa-description-highlight-background-color-rgb: 245, 223, 77; --aa-overlay-color-rgb: 115, 114, 129; --aa-panel-shadow: 0 0 0 1px rgba(35, 38, 59, 0.1), 0 6px 16px -4px rgba(35, 38, 59, 0.15); --aa-scrollbar-track-background-color-rgb: 234, 234, 234; --aa-scrollbar-thumb-background-color-rgb: var(--aa-background-color-rgb); --aa-scrollbar-thumb-background-color-alpha: 1; } .hero--primary { --ifm-color-primary: hsl(199, 34%, 14%); } [data-theme='dark'] .navbar { --ifm-navbar-background-color: hsl(218, 19%, 23%); --ifm-navbar-link-hover-color: var(--ifm-color-primary); --ifm-menu-color-background-active: rgba(255, 255, 255, 0.05); --ifm-navbar-search-input-color: var(--ifm-color-white); } html[data-theme='dark'] { --ifm-background-color: hsl(199, 34%, 14%); } .footer__copyright { font-size: 0.8em; } .fiddle { min-height: 30px; max-height: 400px; position: relative; background: #f0f0f0; margin: 1em 0; height: 30px; } .fiddle>* { border: 0; position: absolute; width: 100%; height: 100%; top: 0; left: 0; box-sizing: border-box; opacity: 0; transition: opacity 0.5s; pointer-events: none; overflow: hidden; } .fiddle .fiddle-loader { display: flex; justify-content: left; align-items: center; padding-left: 20px } .fiddle .fiddle-fallback { border-radius: 3px; padding: 10px; border: 1px solid #bbb; background: white; top: auto; left: -3000px; max-width: 2000px; } .fiddle .fiddle-fallback h3 { font: bold 16px sans-serif; margin: 0 0 4px 0; } .fiddle .fiddle-fallback pre { margin: 0 0 12px 0; } .fiddle[data-state=loading] .fiddle-loader, .fiddle[data-state=loaded] .fiddle-frame, .fiddle[data-state=fallback] .fiddle-fallback { opacity: 1; pointer-events: auto; overflow: hidden; } .fiddle[data-state=fallback] .fiddle-fallback { position: static; } .fiddle[data-state=fallback] { height: auto !important; max-height: none; min-height: 0; } @media print { html .fiddle { height: auto !important; max-height: none; min-height: 0; } html .fiddle .fiddle-fallback { opacity: 1; position: static; } html .fiddle .fiddle-loader, html .fiddle .fiddle-frame { display: none } } ================================================ FILE: documentation/src/pages/index.js ================================================ import React from 'react'; import clsx from 'clsx'; import Link from '@docusaurus/Link'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import Layout from '@theme/Layout'; import HomepageFeatures from '@site/src/components/HomepageFeatures'; import styles from './index.module.css'; function HomepageHeader() { const {siteConfig} = useDocusaurusContext(); return (

{siteConfig.title}

{siteConfig.tagline}

View Documentation
); } export default function Home() { const {siteConfig} = useDocusaurusContext(); return (
); } ================================================ FILE: documentation/src/pages/index.module.css ================================================ /** * CSS files with the .module.css suffix will be treated as CSS modules * and scoped locally. */ .heroBanner { padding: 4rem 0; text-align: center; position: relative; overflow: hidden; } @media screen and (max-width: 996px) { .heroBanner { padding: 2rem; } } .buttons { display: flex; align-items: center; justify-content: center; } ================================================ FILE: documentation/src/theme/MDXComponents.js ================================================ import React from 'react'; import MDXComponents from '@theme-original/MDXComponents'; import {Fiddle} from '@site/src/components/fiddle'; export default { ...MDXComponents, Fiddle, }; ================================================ FILE: documentation/static/fiddle.js ================================================ window.addEventListener('message', function postMessageHandler(e) { const fiddleEl = document.getElementById(e.data.embedID); if (fiddleEl && e.data.event === 'resize' && fiddleEl.offsetHeight < e.data.contentHeight) { fiddleEl.style.height = e.data.contentHeight + 'px'; } }); ================================================ FILE: documentation/versioned_docs/version-1.13.0/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. Dynamically creating new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) is disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. To enable Dynamic Backends the application will need to explicitly allow Dynamic Backends via: ```js import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); ``` **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. ### Return value A new `Backend` object. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to [https://www.fastly.com/](https://www.fastly.com/) and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # toString The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `ConfigStore` instance should provide access to. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # `Dictionary()` :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabled) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to [https://www.fastly.com/](https://www.fastly.com/) and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object` which contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : A [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name is not the name of an HTTP header, this method throws a `TypeError`. The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. > **Warning:** Although you can technically pass `SHA-1` here, this is strongly discouraged as it is considered vulnerable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-1.13.0/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-1.13.0/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-1.13.0/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/object-store/ObjectStore/ObjectStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ObjectStore()` The **`ObjectStore` constructor** lets you connect your Fastly Compute application to a Fastly Object store. An object store is a persistent, globally consistent key-value store. See https://developer.fastly.com/learning/concepts/data-stores/#object-stores for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ObjectStore(name) ``` > **Note:** `ObjectStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Object store which should be associated with this ObjectStore instance ### Return value A new `ObjectStore` object. ### Exceptions - `TypeError` - Thrown if no Object Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an Object Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { ObjectStore } from "fastly:object-store"; async function app(event) { const files = new ObjectStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/object-store/ObjectStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ObjectStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Object store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Object-store. ### Return value If the key does not exist in the Object store, this returns a `Promise` which resolves with `null`. If the key does exist in the Object store, this returns a `Promise` which resolves with an `ObjectStoreEntry`. ## Description Send the given message, converted to a string, to this ObjectStore instance's endpoint. The `get()` method requires its `this` value to be a [`ObjectStore`](../ObjectStore.mdx) object. If the `this` value does not inherit from `ObjectStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#?*[]\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an Object Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { ObjectStore } from "fastly:object-store"; async function app(event) { const files = new ObjectStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/object-store/ObjectStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ObjectStore.prototype.put The **`put()`** method stores a `value` into the Object store under a `key`. > **Note**: Object stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the Object store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the Object store. ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the Object store. ## Description Stores the supplied `value` into the Object store under the supplied `key`. The `put()` method requires its `this` value to be a [`ObjectStore`](../ObjectStore.mdx) object. If the `this` value does not inherit from `ObjectStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#?*[]\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an Object Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { ObjectStore } from "fastly:object-store"; async function app(event) { const files = new ObjectStore('files') await files.put('hello', 'world') const entry = await files.put('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Secret Store which should be associated with this SecretStore instance ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-1.13.0/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. Dynamically creating new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) is disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. To enable Dynamic Backends the application will need to explicitly allow Dynamic Backends via: ```js import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); ``` **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. ### Return value A new `Backend` object. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to [https://www.fastly.com/](https://www.fastly.com/) and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # toString The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache/SimpleCache/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.delete ▸ **delete**(): `string` Delete the entry associated with the key `key` from the cache. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `delete` querystring parameter, we delete the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('delete')) { SimpleCache.delete(path); return new Response(page, { status: 204 }); } let page = SimpleCache.get(path); if (!page) { page = await render(path); // Store the page in the cache for 1 minute. SimpleCache.set(path, page, 60); } return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); if (!page) { page = await render(path); // Store the page in the cache for 1 minute. SimpleCache.set(path, page, 60); } return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key` if no entry is found (or has expired), the supplied `set` function is executed and it's result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - : A function to execute when the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The number of seconds to store the supplied entry within the cache for. - `length` _: number_ __optional__ - The length of value being stored within the cache. This is only used when the `value` is a ReadableStream. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache/SimpleCache/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.set The **`set()`** method stores an entry into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js set(key, value, ttl) set(key, value, ttl, length) ``` ### Parameters - `key` _: string_ - The key to store the supplied entry under within the cache. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The number of seconds to store the supplied entry within the cache for. - `length` _: number_ __optional__ - The length of value being stored within the cache. This is only used when the `value` is a ReadableStream. ### Return value Returns `undefined` when the provided `value` has been written into the cache. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); if (!page) { page = await render(path); // Store the page in the cache for 1 minute. SimpleCache.set(path, page, 60); } return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `ConfigStore` instance should provide access to. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # `Dictionary()` :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabled) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to [https://www.fastly.com/](https://www.fastly.com/) and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object` which contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : A [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name is not the name of an HTTP header, this method throws a `TypeError`. The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-2.5.0/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-2.5.0/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/kv-stores/#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly KV store which should be associated with this KVStore instance ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#?*[]\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#?*[]\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.put('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-2.5.0/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-2.5.0/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-2.5.0/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- import {Fiddle} from '@site/src/components/fiddle'; # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Secret Store which should be associated with this SecretStore instance ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-2.5.0/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/acl/Acl/open.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.open() Opens the ACL with the given name, returning a new `Acl` instance with the given name on success. ## Syntax ```js Acl.open(name) ``` ### Return value An `Acl` instance. ================================================ FILE: documentation/versioned_docs/version-3.38.4/acl/Acl/prototype/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.prototype.lookup() The **`lookup(ipAddress)`** method returns the name associated with the `Acl` instance. ## Syntax ```js acl.lookup(ipAddress) ``` ### Parameters - `ipAddress` _: string_ - IPv4 or IPv6 address to lookup ### Return value An Object of the form `{ action: 'ALLOW' | 'BlOCK', prefix: string }`, where `prefix` is the IP address prefix that was matched in the ACL. ## Example ```js /// import { Acl } from 'fastly:acl'; addEventListener('fetch', async (evt) => { const myAcl = Acl.open('myacl'); const match = await myAcl.lookup(evt.client.address); evt.respondWith(new Response(match?.action === 'BLOCK' ? 'blocked' : 'allowed')); }); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. >**Note**: Dynamic backends are by default disabled at the Fastly service level. Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request dynamic backends on Fastly Services. To disable the usage of dynamic backends, see [enforceExplicitBackends](../enforceExplicitBackends.mdx). ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. - `grpc` _: boolean_ _**optional**_ - **_Experimental feature_** - When enabled, sets that this backend is to be used for gRPC traffic. - _Warning: When using this experimental feature, no guarantees are provided for behaviours for backends that do not provide gRPC traffic._ All optional generic options can have their defaults set via [`setDefaultDynamicBackendConfig()`](../setDefaultDynamicBackendConfig.mdx). This includes all configuration options above except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. ### Return value A new `Backend` object. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/exists.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.exists() The **`Backend.exists()`** method returns a boolean indicating if a Backend with the given name exists or not. ## Syntax ```js exists(name) ``` ### Return value A boolean indicating if a Backend with the given name exists or not. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/fromName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.fromName() Returns the `Backend` instance with the given name, if one exists. If one does not exist, an error is thrown. ## Syntax ```js fromName(name) ``` ### Return value A `Backend` instance. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.health() :::info This method is deprecated, use [`Backend.prototype.health`](./prototype/health.mdx) instead. ::: The **`Backend.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js Backend.health(backend) ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/betweenBytesTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.betweenBytesTimeout The read-only **`betweenBytesTimeout`** property of a `Backend` instance is an integer number providing the between bytes timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/connectTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.connectTimeout The read-only **`connectTimeout`** property of a `Backend` instance is an integer number providing the connect timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/firstByteTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.firstByteTimeout The read-only **`firstByteTimeout`** property of a `Backend` instance is an integer number providing the first byte timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.health() The **`Backend.prototype.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js health() ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/hostOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.hostOverride The read-only **`hostOverride`** property of a `Backend` instance is the host header override string used when sending requests to this backend. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/httpKeepaliveTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.httpKeepaliveTime The read-only **`httpKeepaliveTime`** property of a `Backend` instance is the HTTP keepalive time for this backend in milliseconds, or 0 if no keepalive is set. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/isDynamic.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isDynamic The read-only **`isDynamic`** property of a `Backend` instance is a boolean indicating if the backend was dynamically created for this service. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/isSSL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isSSL The read-only **`isSSL`** property of a `Backend` instance is a boolean indicating if the backend is using an SSL connection. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # name The read-only **`name`** property of the backend returns the backend name string. ## Value A `string`. ## Description Provides the name of the backend. ## Examples ### Using name The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.port The read-only **`port`** property of a `Backend` instance is the port number of this backend. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/target.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.target The read-only **`target`** property of a `Backend` instance is the host string this backend is configured to use. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/tcpKeepalive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tcpKeepalive The read-only **`tcpKeepalive`** property of a `Backend` instance returns an object providing the TCP keepalive configuration, if any, otherwise returning `null` if TCP keepalive is not enabled. This object has the following properties: - `timeSecs` _: number or null._ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number or null._ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number or null._ - Number of probes to send to the backend before it is considered dead. ## Value A `Object` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/tlsMaxVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMaxVersion The read-only **`tlsMaxVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/tlsMinVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMinVersion The read-only **`tlsMinVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/toName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.toName() :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toName()`** method returns the name associated with the `Backend` instance. ## Syntax ```js toName() ``` ### Return value A string which contains the name of the Backend. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toString :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends :::info This method is deprecated, and dynamic backends are now always supported when enabled at the service level. See [`enforceExplicitBackends`](./enforceExplicitBackends.mdx) instead. ::: The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: By default, while dynamic backends are allowed in the SDK, they are by default disabled at the Fastly service level. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/enforceExplicitBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enforceExplicitBackends Call this function to enforce the security property of explicitly-defined backends, even when dynamic backends are enabled at the Fastly service level. By default, if dynamic backends are supported for the Fastly service, they will be automatically used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a potential security concern since third-party JavaScript code may send arbitrary requests, including sensitive/secret data, off to destinations that the JavaScript project was not intending. When calling this function, an optional default backend name can be provided. >**Note**: This is a separate option to the service-level dynamic backend support for Fastly services, which is by deault disabled for Fastly services. The **`enforceExplicitBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: Dynamic Backends are disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled or disabled on Fastly Services. ## Syntax ```js enforceExplicitBackends(defaultBackend?) ``` ### Parameters - `defaultBackend` _: string_ _**optional**_ - An optional default backend string name to use in `fetch()` requests. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/backend/setDefaultDynamicBackendConfig.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setDefaultDynamicBackendConfig() The **`setDefaultDynamicBackendConfig()`** allows setting backend configuration defaults that should apply to any newly created dynamic backends via the `new Backend()` constructor. ### Parameters - `defaultDynamicBackendConfig` - : An Object which contains the generic configuration options to apply to newly created Backends. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. ## Syntax ```js setDefaultDynamicBackendConfig(defaultConfig) ``` ### Return value None. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, with timeouts and TLS options provided from the default backend configuration options. import { allowDynamicBackends } from "fastly:experimental"; import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! // Timeouts and TLS configuration still get set from the default backend configuration above. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.age The **`age`** method of the `CacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.body The **`body`** method of the `CacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this `CacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.close The **`close`** method of the `CacheEntry` interface closes the connection to the cache for this `CacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.hits The **`hits`** method of the `CacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.length The **`length`** method of the `CacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.maxAge The **`maxAge`** method of the `CacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `CacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.state The **`state`** method of the `CacheEntry` interface returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.userMetadata The **`userMetadata`** method of the `CacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheState/found.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.found The **`found`** method of the `CacheState` interface returns `true` if a cached item was located. Even if an cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. ## Syntax ```js found() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item was located or not. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheState/mustInsertOrUpdate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.mustInsertOrUpdate The **`mustInsertOrUpdate`** method of the `CacheState` interface returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. ## Syntax ```js mustInsertOrUpdate() ``` ### Parameters None. ### Return value A `boolean` which represents whether a fresh cached item was found not. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheState/stale.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.stale The **`stale`** method of the `CacheState` interface returns `true` if the cached item is stale. A cached item is stale if its age is greater than its `maxAge` period. ## Syntax ```js stale() ``` ### Parameters None. ### Return value A `boolean` which represents whether the cached item is stale or not. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CacheState/usable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.usable The **`usable`** method of the `CacheState` interface returns `true` if the cached item is usable. A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. ## Syntax ```js usable() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item is usable or not. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CoreCache/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.insert Performs a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. ## Syntax ```js insert(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item’s contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CoreCache/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.lookup Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. ## Syntax ```js lookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns `CacheEntry` if a usable cached item was found, otherwise returns `null`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/CoreCache/transactionLookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.transactionLookup Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. Request Collapsing: If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, just one of the callers will be instructed to insert the item into the cache as part of the transaction. The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. Revalidation: Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. ## Syntax ```js transactionLookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns an instance of `TransactionCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, and return a message stating whether the entry was in the Fastly Cache or not. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); return new Response(page ? `${path} is in the cache` : `${path} is not in the cache`, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key`. If no entry is found (or has expired), the supplied `set` function is executed and its result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - The function to execute if and only if the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The maximum number of seconds to store the supplied entry in the cache. - `length` _: number_ __optional__ - The length of the value being stored within the cache. This is only used when the `value` is a `ReadableStream`. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/SimpleCache/purge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.purge purge the entry associated with the key `key` from the cache. ## Syntax ```js purge(key, options) ``` ### Parameters - `key` _: string_ - The key to purge from within the cache. - `options` _: object_ - `scope` _: string_ - : Where to purge the content from. - Possible values are: - "global" - This will remove the content from all of Fastly. - "pop" - This will remove the content from the POP that contains the currently executing instance. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `purge` querystring parameter, we purge the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('purge')) { SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.age The **`age`** method of the `TransactionCacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.body The **`body`** method of the `TransactionCacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `TransactionCacheEntry`. An error will be thrown if a stream is already active for this `TransactionCacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.cancel The **`cancel`** method of the `TransactionCacheEntry` interface cancels an obligation to provide an object to the cache. ## Syntax ```js cancel() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.close The **`close`** method of the `TransactionCacheEntry` interface closes the connection to the cache for this `TransactionCacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.hits The **`hits`** method of the `TransactionCacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insert Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. ## Syntax ```js insert(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/insertAndStreamBack.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insertAndStreamBack Perform a transaction cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. ## Syntax ```js insertAndStreamBack(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns an array where the first item is a `FastlyBody` instance and the second item is a `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.length The **`length`** method of the `TransactionCacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.maxAge The **`maxAge`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.state The **`state`** method of the `TransactionCacheEntry` interface returns a `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/update.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.update Perform an update of the cache item's metadata. ## Syntax ```js update(options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache/TransactionCacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.userMetadata The **`userMetadata`** method of the `TransactionCacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.38.4/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) new CacheOverride(init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. This options is also the default when providing an init object directly as the first argument. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. - `beforeSend` _:Function_ _**optional**_ - `(request: Request) => void | PromiseLike` - Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. - See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) in the Fastly cache interfaces documentation for details. - `afterSend` _: Function_ _**optional**_ - `(response: Response) => void | CacheOptions | PromiseLike` - Callback to be invoked after a response has been sent, but before it is stored into the cache. - Where `CacheOptions` contains: - `cache` _: boolean | 'uncacheable'_ _**optional**_ - Whether to cache this response. By default, leaving this field empty, responses will be cached based on their cache header information. - Setting this to true or false will override this default cache behaviour, setting in the cache or not setting in the cache, even if the default behaviour would have been otherwise. - Setting to 'uncacheable' the response will not only not be cached, but the cache will record that the originating request led to an uncacheable response, so that future cache lookups will result in immediately going to the backend, rather than attempting to coordinate concurrent requests to reduce backend traffic. - See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) for more details on the mechanism that `uncacheable` disables. - `bodyTransformFn` _: Function_ _**optional**_ - `(body: Uint8Array) => Uint8Array | PromiseLike` - Provide a function to be used for transforming the response body prior to caching. - Body transformations are performed by specifying a transform, rather than by directly working with the body during the onAfterSend callback function, because not every response contains a fresh body: 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because they do not retransmit the body. - For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will be applied to it. The original backend body is passed in to the transform function, and the function is expected to return the new body. - See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) in the Fastly cache interfaces documentation for details. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/compute/purgeSurrogateKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # purgeSurrogateKey The **`purgeSurrogateKey()`** function is used to purge the given surrogate key string from Fastly's cache. There are two purge modes: soft purge and hard purge, with hard purge as the default which clears all items from the cache immediately. When using a soft purge, stale entries are maintained in the cache, reducing orgin load, while also enabling stale revalidations. See the [Fastly Purge Documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) for more information on caching and purge operations. ## Syntax ```js purgeSurrogateKey(surrogateKey, soft?) ``` ### Parameters - `surrogateKey` _: string_ - The surrogate key string - `soft?` _: boolean_ - Enables a soft purge, retaining stale entries in the cache. Default is a hard purge. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/compute/vCpuTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # vCpuTime The **`vCpuTime()`** function provides the vCPU time used by the current request handler in milliseconds. ## Syntax ```js vCpuTime() ``` ### Parameters None. ### Return value `number`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Defines a config store instance using the resource link name. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have a resource link named "animals" (which is linked to a config store) and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.lookup() Look up the data associated with a particular User-Agent string. ## Syntax ```js lookup(userAgent) ``` ### Return value If there is data associated with the User-Agent, a `Device` instance is returned. Otherwise, `null` is returned. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/brand.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.brand The read-only **`brand`** property of the `Device` interface is either a string stating the brand of the device, which can be different from the manufacturer of that device. If no brand is known, the value will be `null`. ## Value Either a string value if a brand is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/hardwareType.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.hardwareType The read-only **`hardwareType`** property of the `Device` interface is either a string stating the hardware type of the device, or `null` if the hardware type is not known. A string representation of the device's primary platform hardware. The most commonly used device types are also identified via boolean variables. Because a device may have multiple device types and this variable only has the primary type, we recommend using the boolean variables for logic and using this string representation for logging. ## Value Either a string value if a hardware type is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/isDesktop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isDesktop The read-only **`isDesktop`** property of the `Device` interface is either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ## Value Either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/isGameConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isGameConsole The read-only **`isGameConsole`** property of the `Device` interface is either a boolean stating if the device is a video game console, or `null` if the this is not known. ## Value Either a boolean stating if the device is a video game console, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/isMediaPlayer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMediaPlayer The read-only **`isMediaPlayer`** property of the `Device` interface is either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ## Value Either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/isMobile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMobile The read-only **`isMobile`** property of the `Device` interface is either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ## Value Either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/isSmartTV.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isSmartTV The read-only **`isSmartTV`** property of the `Device` interface is either a boolean stating if the device is a smart TV, or `null` if the this is not known. ## Value Either a boolean stating if the device is a smart TV, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/isTablet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTablet The read-only **`isTablet`** property of the `Device` interface is either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ## Value Either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/isTouchscreen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTouchscreen The read-only **`isTouchscreen`** property of the `Device` interface is either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ## Value Either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/model.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.model The read-only **`model`** property of the `Device` interface is either a string stating the model of the device, or `null` if the model is not known. ## Value Either a string value if a model is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.name The read-only **`name`** property of the `Device` interface is either a string stating the name of the device, or `null` if the name is not known. ## Value Either a string value if a name is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/device/Device/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toJSON The `toJSON()` method of the Device interface is a serializer; it returns a JSON representation of the Device object. To get a JSON string, you can use `JSON.stringify(device)` directly; it will call `toJSON()` automatically. ## Syntax ```js toJSON() ``` ### Return value A JSON object that is the serialization of the Device object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Dictionary()` :::info This Class is deprecated ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/edge-rate-limiter/EdgeRateLimiter/EdgeRateLimiter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `EdgeRateLimiter()` The **`EdgeRateLimiter` constructor** lets you open an epen a [ERL](https://docs.fastly.com/products/edge-rate-limiting) with the given ratecounter and penaltybox. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new EdgeRateLimiter(rateCounter, penaltyBox) ``` > **Note:** `EdgeRateLimiter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `rateCounter` _: RateCounter_ - The RateCounter instance to associate with this EdgeRateLimiter instance - `penaltyBox` _: PenaltyBox_ - The PenaltyBox instance which should be associated with this EdgeRateLimiter instance ### Return value A new `EdgeRateLimiter` object. ### Exceptions - `TypeError` - Thrown if the provided rateCounter value is not an instance of RateCounter - Thrown if the provided penaltyBox value is not an instance of PenaltyBox ================================================ FILE: documentation/versioned_docs/version-3.38.4/edge-rate-limiter/EdgeRateLimiter/prototype/checkRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EdgeRateLimiter.prototype.checkRate Increment an entry in the rate counter and check if the entry has exceeded some average number of requests per second (RPS) over the given window. If the entry is over the RPS limit for the window, add to the penaltybox for the given `timeToLive`. Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ## Syntax ```js checkRate(entry, delta, window, limit, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to increment and check - `delta` _: number_ - The amount to increment the `entry` by - `window` _: number_ - The time period to check across, has to be either 1 second, 10 seconds, or 60 seconds - `limit` _: number_ - The requests-per-second limit - `timeToLive` _: number_ - In minutes, how long the entry should be added into the penalty-box - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `true` if the entry has exceeded the average RPS for the window, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive finite number. - Thrown if the provided `window` value is not either, 1, 10, or 60. - Thrown if the provided `limit` value is not a positive finite number. - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.38.4/edge-rate-limiter/PenaltyBox/PenaltyBox.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `PenaltyBox()` The **`PenaltyBox` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for adding and checking if some entry is in the dataset. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new PenaltyBox(name) ``` > **Note:** `PenaltyBox()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a PenaltyBox with the given name ### Return value A new `PenaltyBox` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.38.4/edge-rate-limiter/PenaltyBox/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.add Add an `entry` into the PenaltyBox for the duration of the given `timeToLive`. ## Syntax ```js add(entry, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `timeToLive` _: number_ - In minutes, how long the entry should be added into the PenaltyBox - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.38.4/edge-rate-limiter/PenaltyBox/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.has Check if the given entry is contained in in the PenaltyBox instance. ## Syntax ```js has(entry) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up ### Return value Returns `true` if the entry is contained in the PenaltyBox instance, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.38.4/edge-rate-limiter/RateCounter/RateCounter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `RateCounter()` The **`RateCounter` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for counting and rate calculations. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new RateCounter(name) ``` > **Note:** `RateCounter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a RateCounter with the given name ### Return value A new `RateCounter` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.38.4/edge-rate-limiter/RateCounter/prototype/increment.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.increment Increment the given `entry` in the RateCounter instance with the given `delta` value. ## Syntax ```js increment(entry, delta) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `delta` _: number_ - The amount to increment the entry by ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive, finite number. ================================================ FILE: documentation/versioned_docs/version-3.38.4/edge-rate-limiter/RateCounter/prototype/lookupCount.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupCount Look up the current rate for the given `entry` and the given `duration`. ## Syntax ```js lookupCount(entry, duration) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `duration` _: number_ - The duration to lookup alongside the entry, has to be either, 10, 20, 30, 40, 50, or 60 seconds. ### Return value Returns a number which is the count for the given `entry` and `duration` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `duration` value is not either, 10, 20, 30, 40, 50 or 60. ================================================ FILE: documentation/versioned_docs/version-3.38.4/edge-rate-limiter/RateCounter/prototype/lookupRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupRate Look up the current rate for the given `entry` and the given `window`. ## Syntax ```js lookupRate(entry, window) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `window` _: number_ - The window to look up alongside the entry, has to be either 1 second, 10 seconds, or 60 seconds ### Return value Returns a number which is the rate for the given `entry` and `window` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `window` value is not either, 1, 10, or 60. ================================================ FILE: documentation/versioned_docs/version-3.38.4/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabledOrConfig` _: boolean_ - Whether or not to allow Dynamic Backends or - `enabledOrConfig` _: object_ - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to https://www.fastly.com/ and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/experimental/mapAndLogError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapAndLogError The **`mapAndLogError()`** function calls `mapError` on an `Error` object and sends the output to standard error. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapAndLogError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value `undefined`. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { mapAndLogError(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | mapAndLogError(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/experimental/mapError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapError The **`mapError()`** function extracts information from an `Error` object as a human-readable array of strings. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value Returns an array of `string`s. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { console.error(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | console.error(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/experimental/sdkVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sdkVersion The read-only **`sdkVersion`** property is a string whose indicates what JavaScript SDK version is being used. ## Value A string value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object`, or `null` if no geolocation data was found. The object contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Blob/Blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob() The **`Blob()`** constructor creates a `Blob` object, which represents a file-like object of immutable, raw data. ## Syntax ```js new Blob() new Blob(array) new Blob(array, options) ``` > **Note:** `Blob()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `array` _**optional**_ - : An array of values to include in the `Blob`. These can be [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx), [`Blob`](../../globals/Blob/Blob.mdx), or strings. If any of these elements is a [`Blob`](../../globals/Blob/Blob.mdx), its content (and not the object itself) is copied into the Blob being constructed. - `options` _**optional**_ - : An object containing optional attributes for the `Blob`. - `type` - : A string indicating the MIME type of the data. The default value is the empty string `""`. - `endings` - : A string indicating how to handle line endings in the data. This can be either `"transparent"` (default) to keep line endings unchanged, or `"native"` to convert line endings to the platform's native line endings (e.g., `\r\n` on Windows). ### Return value A new `Blob` object containing the specified data. ## Description `Blob` objects represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting its functionality and expanding it to support files on the user's system. To construct a `Blob` from other non-blob objects and data, use the `Blob()` constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](../../globals/Blob/prototype/slice.mdx) method. The `type` property of a `Blob` object will match the MIME type specified in the constructor's `options` parameter, defaulting to an empty string if not specified. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Blob/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.arrayBuffer() The **`arrayBuffer()`** method of the `Blob` interface returns a `Promise` that resolves with an `ArrayBuffer` containing the entire contents of the `Blob` as binary data. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A `Promise` that resolves with an `ArrayBuffer` containing the blob's data. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Blob/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.size The **`size`** read-only property of the `Blob` interface returns the size of the `Blob` in bytes. ## Value A number representing the size of the `Blob` in bytes. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Blob/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.slice() The **`slice()`** method of the `Blob` interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. ## Syntax ```js slice() slice(start) slice(start, end) slice(start, end, contentType) ``` ### Parameters - `start` _**optional**_ - : The 0-based index of the first byte to include in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is 0. - `end` _**optional**_ - : The 0-based index of the first byte that will not be included in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is `size`. - `contentType` _**optional**_ - : A string indicating the content type to assign to the new `Blob`. The default value is an empty string. ### Return value A new `Blob` object containing the specified subset of data. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Blob/prototype/stream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.stream() The **`stream()`** method of the `Blob` interface returns a `ReadableStream` that can be used to read the contents of the `Blob`. ## Syntax ```js stream() ``` ### Parameters None. ### Return value A `ReadableStream` that provides the data contained within the `Blob`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Blob/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.text() The **`text()`** method of the `Blob` interface returns a `Promise` that resolves with a string containing the contents of the blob, interpreted as UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a string containing the blob's data as a text string. The data is always interpreted as UTF-8. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Blob/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.type The **`type`** read-only property of the `Blob` interface returns the MIME type of the `Blob`. ## Value A string indicating the MIME type of the `Blob`. If the type cannot be determined, this returns an empty string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/EcKeyImportParams/EcKeyImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcKeyImportParams The **`EcKeyImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as ECDSA. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/EcdsaParams/EcdsaParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcdsaParams The **`EcdsaParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `hash` - : A string. An identifier for the digest algorithm to use. This should be one of the following: - `SHA-256`: selects the SHA-256 algorithm. - `SHA-384`: selects the SHA-384 algorithm. - `SHA-512`: selects the SHA-512 algorithm. > **Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. While these fields are always defined on Compute, they may be *null* when not available in testing environments such as Viceroy. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : Either `null`, or a [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. - `FetchEvent.client.tlsJA3MD5` _**readonly**_ - : Either `null` or a string representation of the JA3 hash of the TLS ClientHello message. - `FetchEvent.client.tlsCipherOpensslName` _**readonly**_ - : Either `null` or a string representation of the cipher suite used to secure the client TLS connection. - `FetchEvent.client.tlsProtocol` _**readonly**_ - : Either `null` or a string representation of the TLS protocol version used to secure the client TLS connection. - `FetchEvent.client.tlsClientCertificate` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw client certificate in the mutual TLS handshake message. It is in PEM format. Returns an empty ArrayBuffer if this is not mTLS or available. - `FetchEvent.client.tlsClientHello` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw bytes sent by the client in the TLS ClientHello message. - `FetchEvent.client.tlsJA4` _**readonly**_ - : Either `null` or a string representation of the JA4 fingerprint of the TLS ClientHello message. - `FetchEvent.client.h2Fingerprint` _**readonly**_ - : Either `null` or a string representation of the HTTP/2 fingerprint for HTTP/2 connections. Returns `null` for HTTP/1.1 connections. - `FetchEvent.client.ohFingerprint` _**readonly**_ - : Either `null` or a string representation of the Original Header fingerprint based on the order and presence of request headers. - `FetchEvent.server` _**readonly**_ - : Information about the server receiving the request for the Fastly Compute service. - `FetchEvent.server.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the server which received the request. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.sendEarlyHints()`](./prototype/sendEarlyHints.mdx) - : Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FetchEvent/prototype/sendEarlyHints.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.sendEarlyHints() The **`sendEarlyHints()`** method allows you to send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response back to the client which made the incoming request to your application. ## Syntax ```js sendEarlyHints(headers) ``` ### Parameters - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../Headers/Headers.mdx) object or object literal of [`String`](../../String/String.mdx) key/value pairs. ### Return value Always returns `undefined`. ### Examples ```js event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'] ]); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/FormData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData() The **`FormData()`** constructor creates a new `FormData` object. ## Syntax ```js new FormData() new FormData(form) ``` > **Note:** `FormData()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `form` _**optional**_ - : An HTML `` element — when specified, the `FormData` object will be populated with the form's current key/value pairs using the name property of each element for the keys and their submitted value for the values. File input elements are handled specially: their values are taken from the files selected by the user in the upload control. ### Return value A new `FormData` object, pre-populated with form data if the optional `form` parameter was provided. ## Description The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using methods such as `fetch()`. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also append additional data to the `FormData` object after it's created using its various methods. A `FormData` object can be used in a number of ways with other APIs: 1. It can be sent with the `fetch()` API 2. It works seamlessly with the `Request` and `Response` objects - it can be used directly as the body of a `Request` object 3. It can be obtained from a `Response` object using the `formData()` method 4. It can be passed directly to the `URLSearchParams` constructor The transmitted data is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to `"multipart/form-data"`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.append() The **`append()`** method of the `FormData` interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. ## Syntax ```js append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.delete() The **`delete()`** method of the `FormData` interface removes all key/value pairs with the given name from the `FormData` object. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.entries() The **`entries()`** method of the `FormData` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator yields a new array for each key/value pair, with the first element being the key and the second element being the value. ## Syntax ```js entries() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.forEach() The **`forEach()`** method of the `FormData` interface executes the provided callback function once for each key/value pair in the `FormData` object. ## Syntax ```js forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each entry in the object. The function will be passed the following arguments: - `value` - : The value of the current entry. - `key` - : The key of the current entry. - `formData` - : The `FormData` object being traversed. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.get() The **`get()`** method of the `FormData` interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the [`getAll()`](../../../globals/FormData/prototype/getAll.mdx) method instead. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value A `FormDataEntryValue` containing the value. If the key does not exist, it returns `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/prototype/getAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.getAll() The **`getAll()`** method of the `FormData` interface returns all the values associated with a given key from within a `FormData` object. ## Syntax ```js getAll(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value An array of `FormDataEntryValue` items containing all values with the given key. If the key doesn't exist, an empty array is returned. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.has() The **`has()`** method of the `FormData` interface returns a boolean indicating whether a `FormData` object contains a key/value pair with the given name. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the key you want to test for existence. ### Return value `true` if a key/value pair with the specified name exists; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.keys() The **`keys()`** method of the `FormData` interface returns an iterator allowing iteration through all keys contained in this object. The iterator yields the key for each value. ## Syntax ```js keys() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.set() The **`set()`** method of the `FormData` interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and [`append()`](../../../globals/FormData/prototype/append.mdx) is that if the specified key already exists, `set()` overwrites all existing values with the new one, whereas `append()` appends the new value onto the end of the existing values. ## Syntax ```js set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/FormData/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.values() The **`values()`** method of the `FormData` interface returns an iterator allowing iteration through all values contained in this object. The iterator yields the value for each key/value pair. ## Syntax ```js values() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name is not the name of an HTTP header, this method throws a `TypeError`. The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/prototype/getSetCookie.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.getSetCookie() The **`getSetCookie()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns an array of all the values of the `Set-Cookie` headers, returning an empty list if none are present. ## Syntax ```js getSetCookie() ``` ### Return value `String[]` representing the list of `Set-Cookie` headers. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2 or greater than π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex where x is a number very close to 0, you should get an answer very close to 1 + x, because limx0ex1x=1. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, a `ReadableStream` object, a [`Blob`](../../globals/Blob/Blob.mdx) object, or a [`FormData`](../../globals/FormData/FormData.mdx) object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_, see [`CacheOverride`](../../fastly:cache-override/CacheOverride/CacheOverride.mdx). - `cacheKey` _**Fastly-specific**_ - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.blob() The **`blob()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/clone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.clone() The **`clone()`** method of the `Request` interface creates a copy of the current `Request` object. Like the underlying `ReadableStream.tee`` api, the `body` of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Beware when you construct a `Request` from a stream and then `clone` it. `clone()` throws a `TypeError` if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) If you intend to modify the request, you may prefer the `Request` constructor. ## Syntax ```js clone() ``` ### Parameters None. ### Return value A `Request` object, which is an exact copy of the `Request` that `clone()` was called on. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.formData() The **`formData()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. - `SyntaxError` - : Thrown if the request's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Request` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Request instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - [`Blob`](../../globals/Blob/Blob.mdx) - [`FormData`](../../globals/FormData/FormData.mdx) - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.blob() The **`blob()`** method of the [`Response`](../Response.mdx) interface takes a [`Response`](../Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.formData() The **`formData()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. - `SyntaxError` - : Thrown if the response's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/ip.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ip The **`ip`** getter of the `Response` interface returns the IP address associated with the request, as either an IPv6 or IPv4 string. In the case where no IP address is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with an IP, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `string`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.port The **`port`** getter of the `Response` interface returns the port associated with the request, as a number. In the case where no port is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with a port, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `number`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Response` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Response instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - For ECDSA: Pass an [`EcKeyImportParams`](../../EcKeyImportParams/EcKeyImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](https://en.wikipedia.org/wiki/HZ_(character_encoding)). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Explicit Backends Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service. This `backend` option is then a special Fastly-specific fetch option that is provided to the `fetch()` call: ```js fetch('https://origin.com/path', { backend: 'origin' }); ``` Backends are configured using the Fastly service backend configuration, see the [Backend documentation](https://developer.fastly.com/reference/api/services/backend/) for more information. ## Dynamic Backends Dynamic backends are a compute feature that allow services to define backends for themselves. If the `backend` option is not provided when making `fetch()` requests, a backend will be automatically created by extracting the protocol, host, and port from the provided URL. In addition, custom backend configuration options can then also be provided through the [`Backend()`](../fastly:backend/Backend/Backend.mdx) constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ - `imageOptimizerOptions` _**Fastly-specific**_, see [`imageOptimizerOptions`](../fastly:image-optimizer/imageOptimizerOptions.mdx). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-3.38.4/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/after.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # after The `after` method inserts content after the closing tag of the element. ## Syntax ```js element.after(content); element.after(content, options); ``` ### Parameters - `content` _: string_ - The content to insert after the element's closing tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.after("World"); // Result:
Hello
World ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # append The `append` method inserts content at the end of the element's content. ## Syntax ```js element.append(content); element.append(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the end of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.append(", World"); // Result:
Hello, World
``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/before.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # before The `before` method inserts content before the opening tag of the element. ## Syntax ```js element.before(content); element.before(content, options); ``` ### Parameters - `content` _: string_ - The content to insert before the element's opening tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.before("Well"); // Result: Well
Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/hasAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # hasAttribute The `hasAttribute` method returns a `boolean` value indicating whether the specified attribute is present on the element. ## Syntax ```js element.hasAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to check for. ### Return value A boolean value indicating whether the attribute is present. ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/prepend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # prepend The `prepend` method inserts content at the beginning of the element's content. ## Syntax ```js element.prepend(content); element.prepend(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the beginning of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.prepend("Well, "); // Result:
Well, Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/removeAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # removeAttribute The `removeAttribute` method removes the specified attribute from the element. ## Syntax ```js element.removeAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to remove. ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/replaceChildren.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceChildren The `replaceChildren` method replaces the element's children with new content. ## Syntax ```js element.replaceChildren(content); element.replaceChildren(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element's children with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceChildren("Greetings!"); // Result:
Greetings!
``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/replaceWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceWith The `replaceWith` method replaces the element with new content. ## Syntax ```js element.replaceWith(content); element.replaceWith(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceWith("

Greetings!

"); // Result:

Greetings!

``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/selector.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # selector The `selector` read-only property is a `string` representing the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) that matches the element. ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/setAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setAttribute The `setAttribute` method sets the value of the specified attribute on the element. If the value already exists, it will be updated; otherwise, a new attribute with the specified name and value will be added to the element. ## Syntax ```js element.setAttribute(attributeName, value); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to set. - `value` _: string_ - The value to assign to the attribute. ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/Element/prototype/tag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # tag The `tag` read-only property is a `string` representing the tag name of the element. ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/HTMLRewritingStream/HTMLRewritingStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `HTMLRewritingStream()` The **`HTMLRewritingStream`** lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback. This callback can manipulate the attributes of the element, and add or remove content from the immediate context. ## Syntax ```js new HTMLRewritingStream() ``` ### Return value A new `HTMLRewritingStream` object. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/html-rewriter/HTMLRewritingStream/prototype/onElement.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # onElement ▸ **onElement**`(selector: string, handler: (element: Element) => void): this` Registers an element handler with the [`HTMLRewritingStream`] that will be called for each [`Element`] that matches the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) `selector`. Elements added by handlers will not be processed by other handlers. ## Syntax ```js .onElement(selector, handler) ``` ### Parameters - `selector` _: string_ - A CSS selector that determines the elements for which `handler` will be called - The following types of CSS selector are supported: Currently the rewriter supports the following CSS selectors: | Pattern | Description | |----------------------|----------------------------------------------------------------------------| | `*` | Any element | | `E` | All elements of type `E` | | `E F` | `F` elements inside `E` elements | | `E > F` | `F` elements directly inside `E` elements | | `E:nth-child(n)` | The n-th child of type `E` | | `E:first-child` | First child of type `E` | | `E:nth-of-type(n)` | The n-th sibling of type `E` | | `E:first-of-type` | First sibling of type `E` | | `E:not(s)` | Type `E` elements not matching selector `s` | | `E.myclass` | Type `E` elements with class `"myclass"` | | `E#myid` | Type `E` elements with ID `"myid"` | | `E[attr]` | Type `E` elements with attribute `attr` | | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | | `E[attr="val" i]` | Type `E` elements where `attr` is `"val"`, case-insensitive | | `E[attr="val" s]` | Type `E` elements where `attr` is `"val"`, case-sensitive | | `E[attr~="val"]` | Type `E` elements where `attr` contains `"val"` in a space-separated list | | `E[attr`|`;="val"]`| Type `E` elements where `attr` is hyphen-separated and starts with `"val"` | | `E[attr^="val"]` | Type `E` elements where `attr` starts with `"val"` | | `E[attr$="val"]` | Type `E` elements where `attr` ends with `"val"` | | `E[attr*="val"]` | Type `E` elements where `attr` contains `"val"` | - `handler` _: (element: Element) => void_ - A callback function that will be called once for each element that matches `selector` ### Return value The `HTMLRewritingStream`, so multiple calls to `onElement` can be chained. ### Exceptions - `Error` - If the provided `selector` is not a valid CSS selector. - If the provided `handler` is not a function. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/Auto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Auto` Enumerator options for [`imageOptimizerOptions.auto`](./imageOptimizerOptions.mdx). ## Constants - `AVIF` (`"avif"`) If the browser's Accept header indicates compatibility, deliver an AVIF image. - `WEBP` (`"webp"`) If the browser's Accept header indicates compatibility, deliver a WebP image. ## Examples ```js import { Auto, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, auto: Auto.AVIF }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/BWAlgorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `BWAlgorithm` Enumerator options for [`imageOptimizerOptions.bw`](./imageOptimizerOptions.mdx). ## Constants - `Threshold` (`"threshold"`) Uses a luminance threshold to convert the image to black and white. - `Atkinson` (`"atkinson"`) Uses [Atkinson dithering](https://en.wikipedia.org/wiki/Atkinson_dithering) to convert the image to black and white. ## Examples ```js import { Region, BWAlgorithm } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, bw: BWAlgorithm.Threshold }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/CropMode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CropMode` Enumerator options for [`imageOptimizerOptions.crop.mode`](./imageOptimizerOptions.mdx) and `imageOptimizerOptions.precrop.mode`. ## Constants - `Smart` (`"smart"`) Enables content-aware algorithms to attempt to crop the image to the desired aspect ratio while intelligently focusing on the most important visual content, including the detection of faces. - `Safe` (`"safe"`) Allow cropping out-of-bounds regions. ## Examples ```js import { CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Smart, } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/Disable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Disable` Enumerator options for [`imageOptimizerOptions.disable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Prevent images being resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Disable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, disable: Disable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/Enable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Enable` Enumerator options for [`imageOptimizerOptions.enable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Allow images to be resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Enable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, enable: Enable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/Fit.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Fit` Enumerator options for [`imageOptimizerOptions.fit`](./imageOptimizerOptions.mdx). ## Constants - `Bounds` (`"bounds"`) Resize the image to fit entirely within the specified region, making one dimension smaller if needed. - `Cover` (`"cover"`) Resize the image to entirely cover the specified region, making one dimension larger if needed. - `Crop` (`"crop"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Fit, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 150, height; 150, fit: Fit.Bounds }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/Format.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Format` Enumerator options for [`imageOptimizerOptions.format`](./imageOptimizerOptions.mdx). ## Constants - `Auto` (`"auto"`) Automatically use the best format based on browser support and image/transform characteristics - `AVIF` (`"avif"`) AVIF - `BJPG` (`"bjpg"`) Baseline JPEG - `GIF` (`"gif"`) Graphics Interchange Format - `JPG` (`"jpg"`) JPEG - `JXL` (`"jxl"`) JPEGXL - `MP4` (`"mp4"`) MP4 (H.264) - `PJPG` (`"pjpg"`) Progressive JPEG - `PJXL` (`"pjxl"`) Progressive JPEGXL - `PNG` (`"png"`) Portable Network Graphics - `PNG8` (`"png8"`) Portable Network Graphics palette image with 256 colors and 8-bit transparency - `SVG` (`"svg"`) Scalable Vector Graphics - `WEBP` (`"webp"`) WebP - `WEBPLL` (`"webpll"`) WebP (Lossless) - `WEBPLY` (`"webply"`) WebP (Lossy) ## Examples ```js import { Format, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/Metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Metadata` Enumerator options for [`imageOptimizerOptions.metadata`](./imageOptimizerOptions.mdx). ## Constants - `Copyright` (`"copyright"`) Preserve [copyright notice](https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#copyright-notice), creator, credit line, licensor, and web statement of rights fields. - `C2PA` (`"c2pa"`) Preserve the [C2PA manifest](https://c2pa.org/) and add any transformations performed by Fastly Image Optimizer. - `CopyRightAndC2PA` (`"copyright,c2pa"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Metadata, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, metadata: Metadata.Copyright }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/Optimize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Optimize` Enumerator options for [`imageOptimizerOptions.optimize`](./imageOptimizerOptions.mdx). ## Constants - `Low` (`"low"`) Output image quality will be similar to the input image quality. - `Medium` (`"medium"`) More optimization is allowed. We attempt to preserve the visual quality of the input image. - `High` (`"high"`) Minor visual artifacts may be visible. This produces the smallest file. ## Examples ```js import { Optimize, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, optimize: Optimize.High }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/Orient.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Orient` Enumerator options for [`imageOptimizerOptions.orient`](./imageOptimizerOptions.mdx). ## Constants - `Default` (`"1"`) - `FlipHorizontal` (`"2"`) - `FlipHorizontalAndVertical` (`"3"`) - `FlipVertical` (`"4"`) - `FlipHorizontalOrientLeft` (`"5"`) - `OrientRight` (`"6"`) - `FlipHorizontalOrientRight` (`"7"`) - `OrientLeft` (`"8"`) ## Examples ```js import { Orient, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, orient: Orient.FlipHorizontal }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/Profile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Profile` Enumerator options for [`imageOptimizerOptions.profile`](./imageOptimizerOptions.mdx). ## Constants - `Baseline` (`"baseline"`) The profile recommended for video conferencing and mobile applications. (Default) - `Main` (`"main"`) The profile recommended for standard-definition broadcasts. - `High` (`"high"`) The profile recommended for high-definition broadcasts. ## Examples ```js import { Profile, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, profile: Profile.Main }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/Region.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Region` Enumerator options for [`imageOptimizerOptions.region`](./imageOptimizerOptions.mdx). ## Constants - `UsEast` (`"us_east"`) - `UsCentral` (`"us_central"`) - `UsWest` (`"us_west"`) - `EuCentral` (`"eu_central"`) - `EuWest` (`"eu_west"`) - `Asia` (`"asia"`) - `Australia` (`"australia"`) ## Examples ```js import { Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/ResizeFilter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ResizeFilter` Enumerator options for [`imageOptimizerOptions.resizeFilter`](./imageOptimizerOptions.mdx). ## Constants - `Nearest` (`"nearest"`) Uses the value of nearby translated pixel values. - `Bilinear` (`"bilinear"`) Uses an average of a 2x2 environment of pixels. - `Linear` (`"linear"`) Same as `Bilenear`. - `Bicubic` (`"bicubic"`) Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. - `Cubic` (`"cubic"`) Same as `Bicubic`. - `Lanczos2` (`"lanczos2"`) Uses the Lanczos filter to increase the ability to detect edges and linear features within an image and uses sinc resampling to provide the best possible reconstruction. - `Lanczos3` (`"lanczos3"`) Lanczos3 uses a better approximation of the sinc resampling function. (Default) - `Lanczos` (`"lanczos"`) Same as `Lanczos3`. ## Examples ```js import { ResizeFilter, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, resizeFilter: ResizeFilter.Linear }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/image-optimizer/imageOptimizerOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `imageOptimizerOptions` Options specified in the [`Request`](../globals/Request/Request.mdx) constructor for running the [Fastly Image Optimizer](https://docs.fastly.com/products/image-optimizer). More detailed documentation on all Image Optimizer options is available in the [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/). ## Parameters All parameters other than `region` are optional. - `region`: _[`Region`](./Region.mdx)_ Where image optimizations should occur. - `auto`: _[`Auto`](./Auto.mdx)_ Enable optimization features automatically. - `bgColor`: _[`Color`](#color)_ Set the background color of an image. - `blur`: _`number` (0.5-1000) or [`Percentage`](#percentage)_ Set the blurriness of the output image. - `brightness`: _`number` (-100-100)_ Set the brightness of the output image. - `bw`: _[`BWAlgorithm`](./BWAlgorithm.mdx)_ Convert an image to black and white. - `canvas`: _`Object`_ Increase the size of the canvas around an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `contrast`: _`number` (-100-100)_ Set the contrast of the output image. - `crop`: _`Object`_ Remove pixels from an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `mode` (optional): _[`CropMode`](./CropMode.mdx)_ - `disable`: _[`Disable`](./Disable.mdx)_ Disable functionality that is enabled by default. - `dpr`: `number` Ratio between physical pixels and logical pixels. - `enable`: _[`Enable`](./Enable.mdx)_ Enable functionality that is disabled by default. - `fit`: _[`Fit`](./Fit.mdx)_ Set how the image will fit within the size bounds provided. - `format`: _[`Format`](./Format.mdx)_ Specify the output format to convert the image to. - `frame`: _`number` (must have the value 1)_ Extract the first frame from an animated image sequence. - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the height of the image. - `level`: _`String` containing one of the [allowed values](https://www.fastly.com/documentation/reference/io/level/#allowed-values)_ Specify the level constraints when converting to video. - `metadata`: _[`Metadata`](./Metadata.mdx)_ Control which metadata fields are preserved during transformation. - `optimize`: _[`Optimize`](./Optimize.mdx)_ Automatically apply optimal quality compression. - `orient`: _[`Orient`](./Orient.mdx)_ Change the cardinal orientation of the image. - `pad`: _[`Sides`](#sides)_ Add pixels to the edge of an image. - `precrop`: _`Object`_ Remove pixels from an image before any other transformations occur. - `size`: _[`Size`](#size)_ - `position`: _[`Position`](#position)_ - `mode`: _[`CropMode`](./CropMode.mdx)_ - `profile`: _[`Profile`](./Profile.mdx)_ Specify the profile class of application when converting to video. - `quality`: _`integer` (1-100)_ Optimize the image to the given compression level for lossy file formatted images. - `resizeFilter`: _[`ResizeFilter`](./ResizeFilter.mdx)_ Specify the resize filter used when resizing images. - `saturation`: _`number` (-100-100)_ Set the saturation of the output image. - `sharpen`: _`Object`_ Set the sharpness of the output image. - `amount`: _`number` (0-10)_ - `radius`: _`number` (0.5-1000)_ - `threshold`: _`integer` (0-255)_ - `trim`: _[`Sides`](#sides)_ Remove pixels from the edge of an image. - `viewbox`: _`number` (must have the value 1)_ Remove explicit width and height properties in SVG output. - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the width of the image. ## Types ### Color Either: - a 3 or 6 character hexadecimal string - an `Object` containing: - `r`: _`integer` (0-255)_ Red component - `g`: _`integer` (0-255)_ Green component - `b`: _`integer` (0-255)_ Blue component - `a` (optional): _`number` (0.0-1.0)_ Alpha component ### Percentage A `String` containing a number suffixed with a percent sign (%). ### Position An `Object` containing: - Exactly one of: - `x`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetX`: _`number` (interpreted as a percentage)_ - Exactly one of: - `y`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetY`: _`number` (interpreted as a percentage)_ ### Sides An `Object` containing `top`, `bottom`, `left`, and `right`, all of which are either an `integer` or [`Percentage`](#percentage). ### Size An `Object` containing either: - `absolute`: _`Object`_ - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `ratio`: _`Object`_ - `width`: _`number`_ - `height`: _`number`_ ## Examples ```js import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG, bgColor: { 'r': 100, 'g': 255, 'b': 9, 'a': 0.5 }, blur: '1%', brightness: -20, contrast: -20, height: 600, level: '4.0', orient: Orient.FlipVertical, saturation: 80, sharpen: { 'amount': 5, 'radius': 6, 'threshold': 44 }, canvas: { 'size': { 'absolute': { 'width': 400, 'height': 400 } } }, crop: { size: { absolute: { width: 200, height: 200 }, mode: CropMode.Safe } }, trim: { top: 10, left: 10, right: 10, bottom: 10 }, pad: { top: 30, left: 30, right: "1%", bottom: 30 } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a KV store instance using the resource link name. ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStore/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.delete Deletes the value associated with the key `key` in the KV store. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value Returns `undefined` ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - Does not exist ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then delete the entry. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') await files.delete('hello') const entry = await files.get('hello') if (entry) { return new Response(await entry.text()) } else { return new Response('no file named hello exists') } } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStore/prototype/list.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.list The **`list()`** can be used to list the keys of a store. ## Syntax ```js list(options?) ``` ### Parameters - `options` _: object_ _**optional**_ - List options supporting properties: - `cursor` _: string_ _**optional**_ - The cursor used to pick up from a previous iteration. - `limit` _: number_ _**optional**_ - The maximum number of keys to return. - `prefix` _: string_ _**optional**_ - List only those keys that start with the given string prefix. - `noSync` _: boolean_ _**optional**_ - Do not sync the key list first, instead provide a possibly out-of-date listing. May be faster but inconsistent. ### Return value Returns a `Promise` which resolves with `{ list: string[], cursor: string | undefined }`. ## Example In this example we list the keys of a KV Store named `'files'`, iterating 10 at a time, counting the total; ```js /// import { KVStore } from 'fastly:kv-store'; async function app(event) { const files = new KVStore('files'); let cursor, list, total = 0; do { ({ cursor, list } = await files.list({ limit: 10, cursor })); total += list?.length; } while (list); return new Response(`Iterated ${total} entries`); } addEventListener('fetch', (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value, options?) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. - `options` _: object_ _**optional**_ - An insert options parameter, supporting: - `metadata` _: ArrayBuffer | TypedArray | DataView_ _**optional**_ - Binary metadata associated with the entry, may be up to 1000 bytes. - `ttl` _: number_ _**optional**_ - TTL for the entry - `mode` _: 'overwrite' | 'add' | 'append' | 'prepend'_ _**optional**_ - Insert mode, defaults to 'overwrite' - `gen` _: number_ _**optional**_ - 'generation' header specific to the version of an entry key ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - `TypeError` - If the provided `gen`: - Is not an number ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStoreEntry/prototype/metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadata() The `metadata()` method of the `KVStoreEntry` interface provides the binary metadata associated with the `KVStoreEntry`. The metadata binary may be up to 1000 bytes, and is returned as a `Uint8Array` TypedArray buffer, if metadata is set, or null otherwise. ## Syntax ```js metadata() ``` ### Parameters None. ### Return value A `Promise` that resolves to a `Uint8Array` buffer object. ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStoreEntry/prototype/metadataText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadataText() The `metadataText()` method of the `KVStoreEntry` interface provides a String interpretation of binary metadata associated with the `KVStoreEntry`. If the binary data is not a valid string, an encoding error will be thrown. ## Syntax ```js metadataText() ``` ### Parameters None. ### Return value A `Promise` that resolves to a String. ================================================ FILE: documentation/versioned_docs/version-3.38.4/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; const logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; let logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/logger/configureConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # configureConsole The **`configureConsole()`** function allows configuring the behaviour of the `console` global JS logger. ## Syntax ```js configureConsole(loggingOptions) ``` ### Parameters - `loggingOptions` _: object_ - - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ## Examples In this example, we disable prefixing for `console.log` and use `stderr` output for `console.error`: ```js import { configureConsole } from "fastly:logger"; configureConsole({ prefixing: false, stderr: true }); async function handleRequest(event) { console.log(JSON.stringify(event.request.headers)); const url = new URL(event.request.url); try { validate(url); } catch (e) { console.error(`Validation error: ${e}`); return new Response('Bad Request', { status: 400 }); } return new Response('OK'); } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v2 to v3` ## SimpleCache.delete renamed to SimpleCache.purge and requires purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using `SimpleCache.delete` to `SimpleCache.purge` with the same purging behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a Secret Store instance using the resource link name. ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/secret-store/SecretStore/fromBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fromBytes The **`fromBytes()`** function is used to create an in-memory secret from an array buffer. >**Note**: This API should be avoided when possible, by instead using [SecretStore.prototype.get](./prototype/get.mdx) to obtain secure secrets. ## Syntax ```js fromBytes(new Uint8Array([1, 2, 3])) ``` ### Parameters None. ### Return value Returns a `SecretStoreEntry`. ================================================ FILE: documentation/versioned_docs/version-3.38.4/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/secret-store/SecretStoreEntry/prototype/rawBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.rawBytes ▸ **rawBytes**(): `Uint8Array` Returns the raw byte contents of the SecretStoreEntry instance as a Uint8Array. ## Syntax ```js rawBytes() ``` ### Parameters None. ### Return value A Uint8Array ### Exceptions The `rawBytes()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ================================================ FILE: documentation/versioned_docs/version-3.38.4/security/inspect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # inspect The **`inspect()`** function inspects a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). ## Syntax ```js inspect(request, config); ``` ### Parameters - `request` _: Request_ - The Request to get a WAF determination for. - `config` _: object_ - `corp` _: string_ - Set a corp name for the configuration. - This parameter is currently required. - `workspace` _: string_ - Set a workspace name for the configuration. - This parameter is currently required. - `overrideClientIp` _: string_ - Specify an explicit client IP address to inspect. - By default, `inspect` will use the IP address that made the request to the running Compute service, but you may want to use a different IP when service chaining or if requests are proxied from outside of Fastly’s network. ### Return value Returns an `Object` with the `inspect` response, with the following fields: - `waf_response` _: number_ - Security status code. - `redirect_url` _: string | null_ - A redirect URL returned from Security. - `tags` _: string[]_ - Tags returned by Security. - `verdict` _: string_ - The outcome of inspecting a request with Security. It can be one of the following: - `"allow"` - Security indicated that this request is allowed. - `"block"` - Security indicated that this request should be blocked. - `"unauthorized"` - Security indicated that this service is not authorized to inspect a request. - Other verdicts may be returned but not currently documented. - `decision_ms` _: number_ - How long Security spent determining its verdict, in milliseconds. ## Examples ```js /// import { inspect } from "fastly:security"; async function app(event) { const res = inspect(event.request, { corp: "mycorp", workspace: "myws" }); switch (res.verdict) { case "allow": return await fetch(event.request); case "block": return new Response("Request Blocked", { status: 400 }); case "unauthorized": return new Response("Unauthorized", { status: 401 }); default: return new Response("idk", { status: 500 }); } } addEventListener("fetch", (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/shielding/Shield/Shield.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Shield()` Load information about the given shield. Returns an object representing the shield if it is active, or throws an exception if the string is malformed or the shield doesn’t exist. Shield names are defined on [this webpage](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations), in the “shield code” column. For example, the string “pdx-or-us” will look up our Portland, OR, USA shield site, while “paris-fr” will look up our Paris site. If you are using a major cloud provider for your primary origin site, consider looking at the “Recommended for” column, to find the Fastly POP most closely located to the given cloud provider. ## Syntax ```js new Shield(name) ``` > **Note:** `Shield()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Exceptions - `TypeError` - Thrown if no Shield exists with the provided name ## Examples In this example, we create a Shield instance for the Sydney, Australia shield POP. If the code is running on that shield POP, it fetches directly from origin. Otherwise, it routes the request through the shield using an encrypted connection. ```js /// import { Shield } from "fastly:shielding"; async function app(event) { const shield = new Shield('wsi-australia-au'); // If running on the shield POP, fetch from the origin directly if (shield.runningOn()) { return await fetch('https://http-me.fastly.com/anything', { backend: 'httpme' }); } // Otherwise, route the request through the shield using an encrypted connection return await fetch(event.request, { backend: shield.encryptedBackend() }); } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.38.4/shielding/Shield/prototype/encryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.encryptedBackend ▸ **encryptedBackend**(): `Backend` Returns a `Backend` representing an encrypted connection to the POP. For reference, this is almost always the backend that you want to use. Only use [`Shield::unencryptedBackend`](./unencryptedBackend.mdx) in situations in which you are 100% sure that all the data you will send and receive over the backend is already encrypted. ================================================ FILE: documentation/versioned_docs/version-3.38.4/shielding/Shield/prototype/runningOn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.runningOn ▸ **runningOn**(): `boolean` Returns whether we are currently operating on the given shield. Technically, this may also return true in very isolated incidents in which Fastly is routing traffic from the target shield POP to the POP that this code is running on, but in these situations the results should be approximately identical. (For example, it may be the case that you are asking to shield to ‘pdx-or-us’. But, for load balancing, performance, or other reasons, Fastly is temporarily shifting shielding traffic from Portland to Seattle. In that case, this function may return true for hosts running on ‘bfi-wa-us’, our Seattle site, because effectively the shield has moved to that location. This should give you a slightly faster experience than the alternative, in which this function would return false, you would try to forward your traffic to the Portland site, and then that traffic would be caught and redirected back to Seattle.) ================================================ FILE: documentation/versioned_docs/version-3.38.4/shielding/Shield/prototype/unencryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.unencryptedBackend ▸ **unencryptedBackend**(): `Backend` Returns a `Backend` representing an unencrypted connection to the POP. Generally speaking, we encourage users to use [`Shield::encryptedBackend`](./encryptedBackend.mdx) instead of this function. Data sent over this backend – the unencrypted version – will be sent over the open internet, with no protections. In most cases, this is not what you want. However, in some cases – such as when you want to ship large data blobs that you know are already encrypted — using these backends can prevent a double-encryption performance penalty. ================================================ FILE: documentation/versioned_docs/version-3.38.4/websocket/createWebsocketHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createWebsocketHandoff The **`createWebsocketHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Websocket, to the declared backend. ## Syntax ```js createWebsocketHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Websocket. - `backend` _: string_ - The name of the backend that Websocket should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Websocket. ```js import { createWebsocketHandoff } from "fastly:websocket"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createWebsocketHandoff(event.request, 'websocket_backend'); } else { return new Response('oopsie, make a request to /stream for some websocket goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/acl/Acl/open.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.open() Opens the ACL with the given name, returning a new `Acl` instance with the given name on success. ## Syntax ```js Acl.open(name) ``` ### Return value An `Acl` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.0/acl/Acl/prototype/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.prototype.lookup() The **`lookup(ipAddress)`** method returns the name associated with the `Acl` instance. ## Syntax ```js acl.lookup(ipAddress) ``` ### Parameters - `ipAddress` _: string_ - IPv4 or IPv6 address to lookup ### Return value An Object of the form `{ action: 'ALLOW' | 'BlOCK', prefix: string }`, where `prefix` is the IP address prefix that was matched in the ACL. ## Example ```js /// import { Acl } from 'fastly:acl'; addEventListener('fetch', async (evt) => { const myAcl = Acl.open('myacl'); const match = await myAcl.lookup(evt.client.address); evt.respondWith(new Response(match?.action === 'BLOCK' ? 'blocked' : 'allowed')); }); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. >**Note**: Dynamic backends are by default disabled at the Fastly service level. Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request dynamic backends on Fastly Services. To disable the usage of dynamic backends, see [enforceExplicitBackends](../enforceExplicitBackends.mdx). ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. - `grpc` _: boolean_ _**optional**_ - **_Experimental feature_** - When enabled, sets that this backend is to be used for gRPC traffic. - _Warning: When using this experimental feature, no guarantees are provided for behaviours for backends that do not provide gRPC traffic._ All optional generic options can have their defaults set via [`setDefaultDynamicBackendConfig()`](../setDefaultDynamicBackendConfig.mdx). This includes all configuration options above except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. ### Return value A new `Backend` object. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/exists.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.exists() The **`Backend.exists()`** method returns a boolean indicating if a Backend with the given name exists or not. ## Syntax ```js exists(name) ``` ### Return value A boolean indicating if a Backend with the given name exists or not. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/fromName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.fromName() Returns the `Backend` instance with the given name, if one exists. If one does not exist, an error is thrown. ## Syntax ```js fromName(name) ``` ### Return value A `Backend` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.health() :::info This method is deprecated, use [`Backend.prototype.health`](./prototype/health.mdx) instead. ::: The **`Backend.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js Backend.health(backend) ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/betweenBytesTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.betweenBytesTimeout The read-only **`betweenBytesTimeout`** property of a `Backend` instance is an integer number providing the between bytes timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/connectTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.connectTimeout The read-only **`connectTimeout`** property of a `Backend` instance is an integer number providing the connect timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/firstByteTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.firstByteTimeout The read-only **`firstByteTimeout`** property of a `Backend` instance is an integer number providing the first byte timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.health() The **`Backend.prototype.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js health() ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/hostOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.hostOverride The read-only **`hostOverride`** property of a `Backend` instance is the host header override string used when sending requests to this backend. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/httpKeepaliveTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.httpKeepaliveTime The read-only **`httpKeepaliveTime`** property of a `Backend` instance is the HTTP keepalive time for this backend in milliseconds, or 0 if no keepalive is set. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/isDynamic.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isDynamic The read-only **`isDynamic`** property of a `Backend` instance is a boolean indicating if the backend was dynamically created for this service. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/isSSL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isSSL The read-only **`isSSL`** property of a `Backend` instance is a boolean indicating if the backend is using an SSL connection. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # name The read-only **`name`** property of the backend returns the backend name string. ## Value A `string`. ## Description Provides the name of the backend. ## Examples ### Using name The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.port The read-only **`port`** property of a `Backend` instance is the port number of this backend. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/target.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.target The read-only **`target`** property of a `Backend` instance is the host string this backend is configured to use. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/tcpKeepalive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tcpKeepalive The read-only **`tcpKeepalive`** property of a `Backend` instance returns an object providing the TCP keepalive configuration, if any, otherwise returning `null` if TCP keepalive is not enabled. This object has the following properties: - `timeSecs` _: number or null._ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number or null._ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number or null._ - Number of probes to send to the backend before it is considered dead. ## Value A `Object` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/tlsMaxVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMaxVersion The read-only **`tlsMaxVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/tlsMinVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMinVersion The read-only **`tlsMinVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/toName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.toName() :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toName()`** method returns the name associated with the `Backend` instance. ## Syntax ```js toName() ``` ### Return value A string which contains the name of the Backend. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toString :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends :::info This method is deprecated, and dynamic backends are now always supported when enabled at the service level. See [`enforceExplicitBackends`](./enforceExplicitBackends.mdx) instead. ::: The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: By default, while dynamic backends are allowed in the SDK, they are by default disabled at the Fastly service level. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/enforceExplicitBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enforceExplicitBackends Call this function to enforce the security property of explicitly-defined backends, even when dynamic backends are enabled at the Fastly service level. By default, if dynamic backends are supported for the Fastly service, they will be automatically used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a potential security concern since third-party JavaScript code may send arbitrary requests, including sensitive/secret data, off to destinations that the JavaScript project was not intending. When calling this function, an optional default backend name can be provided. >**Note**: This is a separate option to the service-level dynamic backend support for Fastly services, which is by deault disabled for Fastly services. The **`enforceExplicitBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: Dynamic Backends are disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled or disabled on Fastly Services. ## Syntax ```js enforceExplicitBackends(defaultBackend?) ``` ### Parameters - `defaultBackend` _: string_ _**optional**_ - An optional default backend string name to use in `fetch()` requests. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/backend/setDefaultDynamicBackendConfig.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setDefaultDynamicBackendConfig() The **`setDefaultDynamicBackendConfig()`** allows setting backend configuration defaults that should apply to any newly created dynamic backends via the `new Backend()` constructor. ### Parameters - `defaultDynamicBackendConfig` - : An Object which contains the generic configuration options to apply to newly created Backends. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. ## Syntax ```js setDefaultDynamicBackendConfig(defaultConfig) ``` ### Return value None. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, with timeouts and TLS options provided from the default backend configuration options. import { allowDynamicBackends } from "fastly:experimental"; import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! // Timeouts and TLS configuration still get set from the default backend configuration above. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.age The **`age`** method of the `CacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.body The **`body`** method of the `CacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this `CacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.close The **`close`** method of the `CacheEntry` interface closes the connection to the cache for this `CacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.hits The **`hits`** method of the `CacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.length The **`length`** method of the `CacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.maxAge The **`maxAge`** method of the `CacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `CacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.state The **`state`** method of the `CacheEntry` interface returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.userMetadata The **`userMetadata`** method of the `CacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheState/found.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.found The **`found`** method of the `CacheState` interface returns `true` if a cached item was located. Even if an cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. ## Syntax ```js found() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item was located or not. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheState/mustInsertOrUpdate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.mustInsertOrUpdate The **`mustInsertOrUpdate`** method of the `CacheState` interface returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. ## Syntax ```js mustInsertOrUpdate() ``` ### Parameters None. ### Return value A `boolean` which represents whether a fresh cached item was found not. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheState/stale.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.stale The **`stale`** method of the `CacheState` interface returns `true` if the cached item is stale. A cached item is stale if its age is greater than its `maxAge` period. ## Syntax ```js stale() ``` ### Parameters None. ### Return value A `boolean` which represents whether the cached item is stale or not. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CacheState/usable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.usable The **`usable`** method of the `CacheState` interface returns `true` if the cached item is usable. A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. ## Syntax ```js usable() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item is usable or not. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CoreCache/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.insert Performs a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. ## Syntax ```js insert(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item’s contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CoreCache/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.lookup Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. ## Syntax ```js lookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns `CacheEntry` if a usable cached item was found, otherwise returns `null`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/CoreCache/transactionLookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.transactionLookup Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. Request Collapsing: If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, just one of the callers will be instructed to insert the item into the cache as part of the transaction. The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. Revalidation: Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. ## Syntax ```js transactionLookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns an instance of `TransactionCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, and return a message stating whether the entry was in the Fastly Cache or not. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); return new Response(page ? `${path} is in the cache` : `${path} is not in the cache`, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key`. If no entry is found (or has expired), the supplied `set` function is executed and its result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - The function to execute if and only if the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The maximum number of seconds to store the supplied entry in the cache. - `length` _: number_ __optional__ - The length of the value being stored within the cache. This is only used when the `value` is a `ReadableStream`. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/SimpleCache/purge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.purge purge the entry associated with the key `key` from the cache. ## Syntax ```js purge(key, options) ``` ### Parameters - `key` _: string_ - The key to purge from within the cache. - `options` _: object_ - `scope` _: string_ - : Where to purge the content from. - Possible values are: - "global" - This will remove the content from all of Fastly. - "pop" - This will remove the content from the POP that contains the currently executing instance. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `purge` querystring parameter, we purge the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('purge')) { SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.age The **`age`** method of the `TransactionCacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.body The **`body`** method of the `TransactionCacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `TransactionCacheEntry`. An error will be thrown if a stream is already active for this `TransactionCacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.cancel The **`cancel`** method of the `TransactionCacheEntry` interface cancels an obligation to provide an object to the cache. ## Syntax ```js cancel() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.close The **`close`** method of the `TransactionCacheEntry` interface closes the connection to the cache for this `TransactionCacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.hits The **`hits`** method of the `TransactionCacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insert Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. ## Syntax ```js insert(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/insertAndStreamBack.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insertAndStreamBack Perform a transaction cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. ## Syntax ```js insertAndStreamBack(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns an array where the first item is a `FastlyBody` instance and the second item is a `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.length The **`length`** method of the `TransactionCacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.maxAge The **`maxAge`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.state The **`state`** method of the `TransactionCacheEntry` interface returns a `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/update.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.update Perform an update of the cache item's metadata. ## Syntax ```js update(options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache/TransactionCacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.userMetadata The **`userMetadata`** method of the `TransactionCacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.0/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) new CacheOverride(init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. This options is also the default when providing an init object directly as the first argument. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. - `beforeSend` _:Function_ _**optional**_ - `(request: Request) => void | PromiseLike` - Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. - See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) in the Fastly cache interfaces documentation for details. - `afterSend` _: Function_ _**optional**_ - `(response: Response) => void | CacheOptions | PromiseLike` - Callback to be invoked after a response has been sent, but before it is stored into the cache. - Where `CacheOptions` contains: - `cache` _: boolean | 'uncacheable'_ _**optional**_ - Whether to cache this response. By default, leaving this field empty, responses will be cached based on their cache header information. - Setting this to true or false will override this default cache behaviour, setting in the cache or not setting in the cache, even if the default behaviour would have been otherwise. - Setting to 'uncacheable' the response will not only not be cached, but the cache will record that the originating request led to an uncacheable response, so that future cache lookups will result in immediately going to the backend, rather than attempting to coordinate concurrent requests to reduce backend traffic. - See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) for more details on the mechanism that `uncacheable` disables. - `bodyTransformFn` _: Function_ _**optional**_ - `(body: Uint8Array) => Uint8Array | PromiseLike` - Provide a function to be used for transforming the response body prior to caching. - Body transformations are performed by specifying a transform, rather than by directly working with the body during the onAfterSend callback function, because not every response contains a fresh body: 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because they do not retransmit the body. - For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will be applied to it. The original backend body is passed in to the transform function, and the function is expected to return the new body. - See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) in the Fastly cache interfaces documentation for details. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/compute/purgeSurrogateKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # purgeSurrogateKey The **`purgeSurrogateKey()`** function is used to purge the given surrogate key string from Fastly's cache. There are two purge modes: soft purge and hard purge, with hard purge as the default which clears all items from the cache immediately. When using a soft purge, stale entries are maintained in the cache, reducing orgin load, while also enabling stale revalidations. See the [Fastly Purge Documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) for more information on caching and purge operations. ## Syntax ```js purgeSurrogateKey(surrogateKey, soft?) ``` ### Parameters - `surrogateKey` _: string_ - The surrogate key string - `soft?` _: boolean_ - Enables a soft purge, retaining stale entries in the cache. Default is a hard purge. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/compute/vCpuTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # vCpuTime The **`vCpuTime()`** function provides the vCPU time used by the current request handler in milliseconds. ## Syntax ```js vCpuTime() ``` ### Parameters None. ### Return value `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Defines a config store instance using the resource link name. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have a resource link named "animals" (which is linked to a config store) and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.lookup() Look up the data associated with a particular User-Agent string. ## Syntax ```js lookup(userAgent) ``` ### Return value If there is data associated with the User-Agent, a `Device` instance is returned. Otherwise, `null` is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/brand.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.brand The read-only **`brand`** property of the `Device` interface is either a string stating the brand of the device, which can be different from the manufacturer of that device. If no brand is known, the value will be `null`. ## Value Either a string value if a brand is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/hardwareType.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.hardwareType The read-only **`hardwareType`** property of the `Device` interface is either a string stating the hardware type of the device, or `null` if the hardware type is not known. A string representation of the device's primary platform hardware. The most commonly used device types are also identified via boolean variables. Because a device may have multiple device types and this variable only has the primary type, we recommend using the boolean variables for logic and using this string representation for logging. ## Value Either a string value if a hardware type is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/isBot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isBot The read-only **`isBot`** property of the `Device` interface is either a boolean stating if the device is a bot, or `null` if the this is not known. ## Value Either a boolean stating if the device is a bot, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/isDesktop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isDesktop The read-only **`isDesktop`** property of the `Device` interface is either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ## Value Either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/isGameConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isGameConsole The read-only **`isGameConsole`** property of the `Device` interface is either a boolean stating if the device is a video game console, or `null` if the this is not known. ## Value Either a boolean stating if the device is a video game console, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/isMediaPlayer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMediaPlayer The read-only **`isMediaPlayer`** property of the `Device` interface is either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ## Value Either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/isMobile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMobile The read-only **`isMobile`** property of the `Device` interface is either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ## Value Either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/isSmartTV.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isSmartTV The read-only **`isSmartTV`** property of the `Device` interface is either a boolean stating if the device is a smart TV, or `null` if the this is not known. ## Value Either a boolean stating if the device is a smart TV, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/isTablet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTablet The read-only **`isTablet`** property of the `Device` interface is either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ## Value Either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/isTouchscreen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTouchscreen The read-only **`isTouchscreen`** property of the `Device` interface is either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ## Value Either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/model.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.model The read-only **`model`** property of the `Device` interface is either a string stating the model of the device, or `null` if the model is not known. ## Value Either a string value if a model is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.name The read-only **`name`** property of the `Device` interface is either a string stating the name of the device, or `null` if the name is not known. ## Value Either a string value if a name is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/device/Device/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toJSON The `toJSON()` method of the Device interface is a serializer; it returns a JSON representation of the Device object. To get a JSON string, you can use `JSON.stringify(device)` directly; it will call `toJSON()` automatically. ## Syntax ```js toJSON() ``` ### Return value A JSON object that is the serialization of the Device object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Dictionary()` :::info This Class is deprecated ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/edge-rate-limiter/EdgeRateLimiter/EdgeRateLimiter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `EdgeRateLimiter()` The **`EdgeRateLimiter` constructor** lets you open an epen a [ERL](https://docs.fastly.com/products/edge-rate-limiting) with the given ratecounter and penaltybox. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new EdgeRateLimiter(rateCounter, penaltyBox) ``` > **Note:** `EdgeRateLimiter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `rateCounter` _: RateCounter_ - The RateCounter instance to associate with this EdgeRateLimiter instance - `penaltyBox` _: PenaltyBox_ - The PenaltyBox instance which should be associated with this EdgeRateLimiter instance ### Return value A new `EdgeRateLimiter` object. ### Exceptions - `TypeError` - Thrown if the provided rateCounter value is not an instance of RateCounter - Thrown if the provided penaltyBox value is not an instance of PenaltyBox ================================================ FILE: documentation/versioned_docs/version-3.39.0/edge-rate-limiter/EdgeRateLimiter/prototype/checkRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EdgeRateLimiter.prototype.checkRate Increment an entry in the rate counter and check if the entry has exceeded some average number of requests per second (RPS) over the given window. If the entry is over the RPS limit for the window, add to the penaltybox for the given `timeToLive`. Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ## Syntax ```js checkRate(entry, delta, window, limit, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to increment and check - `delta` _: number_ - The amount to increment the `entry` by - `window` _: number_ - The time period to check across, has to be either 1 second, 10 seconds, or 60 seconds - `limit` _: number_ - The requests-per-second limit - `timeToLive` _: number_ - In minutes, how long the entry should be added into the penalty-box - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `true` if the entry has exceeded the average RPS for the window, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive finite number. - Thrown if the provided `window` value is not either, 1, 10, or 60. - Thrown if the provided `limit` value is not a positive finite number. - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.39.0/edge-rate-limiter/PenaltyBox/PenaltyBox.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `PenaltyBox()` The **`PenaltyBox` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for adding and checking if some entry is in the dataset. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new PenaltyBox(name) ``` > **Note:** `PenaltyBox()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a PenaltyBox with the given name ### Return value A new `PenaltyBox` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.0/edge-rate-limiter/PenaltyBox/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.add Add an `entry` into the PenaltyBox for the duration of the given `timeToLive`. ## Syntax ```js add(entry, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `timeToLive` _: number_ - In minutes, how long the entry should be added into the PenaltyBox - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.39.0/edge-rate-limiter/PenaltyBox/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.has Check if the given entry is contained in in the PenaltyBox instance. ## Syntax ```js has(entry) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up ### Return value Returns `true` if the entry is contained in the PenaltyBox instance, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.0/edge-rate-limiter/RateCounter/RateCounter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `RateCounter()` The **`RateCounter` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for counting and rate calculations. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new RateCounter(name) ``` > **Note:** `RateCounter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a RateCounter with the given name ### Return value A new `RateCounter` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.0/edge-rate-limiter/RateCounter/prototype/increment.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.increment Increment the given `entry` in the RateCounter instance with the given `delta` value. ## Syntax ```js increment(entry, delta) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `delta` _: number_ - The amount to increment the entry by ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive, finite number. ================================================ FILE: documentation/versioned_docs/version-3.39.0/edge-rate-limiter/RateCounter/prototype/lookupCount.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupCount Look up the current rate for the given `entry` and the given `duration`. ## Syntax ```js lookupCount(entry, duration) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `duration` _: number_ - The duration to lookup alongside the entry, has to be either, 10, 20, 30, 40, 50, or 60 seconds. ### Return value Returns a number which is the count for the given `entry` and `duration` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `duration` value is not either, 10, 20, 30, 40, 50 or 60. ================================================ FILE: documentation/versioned_docs/version-3.39.0/edge-rate-limiter/RateCounter/prototype/lookupRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupRate Look up the current rate for the given `entry` and the given `window`. ## Syntax ```js lookupRate(entry, window) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `window` _: number_ - The window to look up alongside the entry, has to be either 1 second, 10 seconds, or 60 seconds ### Return value Returns a number which is the rate for the given `entry` and `window` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `window` value is not either, 1, 10, or 60. ================================================ FILE: documentation/versioned_docs/version-3.39.0/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabledOrConfig` _: boolean_ - Whether or not to allow Dynamic Backends or - `enabledOrConfig` _: object_ - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to https://www.fastly.com/ and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/experimental/mapAndLogError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapAndLogError The **`mapAndLogError()`** function calls `mapError` on an `Error` object and sends the output to standard error. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapAndLogError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value `undefined`. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { mapAndLogError(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | mapAndLogError(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/experimental/mapError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapError The **`mapError()`** function extracts information from an `Error` object as a human-readable array of strings. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value Returns an array of `string`s. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { console.error(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | console.error(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/experimental/sdkVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sdkVersion The read-only **`sdkVersion`** property is a string whose indicates what JavaScript SDK version is being used. ## Value A string value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object`, or `null` if no geolocation data was found. The object contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Blob/Blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob() The **`Blob()`** constructor creates a `Blob` object, which represents a file-like object of immutable, raw data. ## Syntax ```js new Blob() new Blob(array) new Blob(array, options) ``` > **Note:** `Blob()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `array` _**optional**_ - : An array of values to include in the `Blob`. These can be [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx), [`Blob`](../../globals/Blob/Blob.mdx), or strings. If any of these elements is a [`Blob`](../../globals/Blob/Blob.mdx), its content (and not the object itself) is copied into the Blob being constructed. - `options` _**optional**_ - : An object containing optional attributes for the `Blob`. - `type` - : A string indicating the MIME type of the data. The default value is the empty string `""`. - `endings` - : A string indicating how to handle line endings in the data. This can be either `"transparent"` (default) to keep line endings unchanged, or `"native"` to convert line endings to the platform's native line endings (e.g., `\r\n` on Windows). ### Return value A new `Blob` object containing the specified data. ## Description `Blob` objects represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting its functionality and expanding it to support files on the user's system. To construct a `Blob` from other non-blob objects and data, use the `Blob()` constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](../../globals/Blob/prototype/slice.mdx) method. The `type` property of a `Blob` object will match the MIME type specified in the constructor's `options` parameter, defaulting to an empty string if not specified. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Blob/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.arrayBuffer() The **`arrayBuffer()`** method of the `Blob` interface returns a `Promise` that resolves with an `ArrayBuffer` containing the entire contents of the `Blob` as binary data. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A `Promise` that resolves with an `ArrayBuffer` containing the blob's data. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Blob/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.size The **`size`** read-only property of the `Blob` interface returns the size of the `Blob` in bytes. ## Value A number representing the size of the `Blob` in bytes. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Blob/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.slice() The **`slice()`** method of the `Blob` interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. ## Syntax ```js slice() slice(start) slice(start, end) slice(start, end, contentType) ``` ### Parameters - `start` _**optional**_ - : The 0-based index of the first byte to include in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is 0. - `end` _**optional**_ - : The 0-based index of the first byte that will not be included in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is `size`. - `contentType` _**optional**_ - : A string indicating the content type to assign to the new `Blob`. The default value is an empty string. ### Return value A new `Blob` object containing the specified subset of data. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Blob/prototype/stream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.stream() The **`stream()`** method of the `Blob` interface returns a `ReadableStream` that can be used to read the contents of the `Blob`. ## Syntax ```js stream() ``` ### Parameters None. ### Return value A `ReadableStream` that provides the data contained within the `Blob`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Blob/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.text() The **`text()`** method of the `Blob` interface returns a `Promise` that resolves with a string containing the contents of the blob, interpreted as UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a string containing the blob's data as a text string. The data is always interpreted as UTF-8. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Blob/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.type The **`type`** read-only property of the `Blob` interface returns the MIME type of the `Blob`. ## Value A string indicating the MIME type of the `Blob`. If the type cannot be determined, this returns an empty string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/EcKeyImportParams/EcKeyImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcKeyImportParams The **`EcKeyImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as ECDSA. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/EcdsaParams/EcdsaParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcdsaParams The **`EcdsaParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `hash` - : A string. An identifier for the digest algorithm to use. This should be one of the following: - `SHA-256`: selects the SHA-256 algorithm. - `SHA-384`: selects the SHA-384 algorithm. - `SHA-512`: selects the SHA-512 algorithm. > **Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. While these fields are always defined on Compute, they may be *null* when not available in testing environments such as Viceroy. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : Either `null`, or a [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. - `FetchEvent.client.tlsJA3MD5` _**readonly**_ - : Either `null` or a string representation of the JA3 hash of the TLS ClientHello message. - `FetchEvent.client.tlsCipherOpensslName` _**readonly**_ - : Either `null` or a string representation of the cipher suite used to secure the client TLS connection. - `FetchEvent.client.tlsProtocol` _**readonly**_ - : Either `null` or a string representation of the TLS protocol version used to secure the client TLS connection. - `FetchEvent.client.tlsClientCertificate` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw client certificate in the mutual TLS handshake message. It is in PEM format. Returns an empty ArrayBuffer if this is not mTLS or available. - `FetchEvent.client.tlsClientHello` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw bytes sent by the client in the TLS ClientHello message. - `FetchEvent.client.tlsJA4` _**readonly**_ - : Either `null` or a string representation of the JA4 fingerprint of the TLS ClientHello message. - `FetchEvent.client.h2Fingerprint` _**readonly**_ - : Either `null` or a string representation of the HTTP/2 fingerprint for HTTP/2 connections. Returns `null` for HTTP/1.1 connections. - `FetchEvent.client.ohFingerprint` _**readonly**_ - : Either `null` or a string representation of the Original Header fingerprint based on the order and presence of request headers. - `FetchEvent.server` _**readonly**_ - : Information about the server receiving the request for the Fastly Compute service. - `FetchEvent.server.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the server which received the request. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.sendEarlyHints()`](./prototype/sendEarlyHints.mdx) - : Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FetchEvent/prototype/sendEarlyHints.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.sendEarlyHints() The **`sendEarlyHints()`** method allows you to send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response back to the client which made the incoming request to your application. ## Syntax ```js sendEarlyHints(headers) ``` ### Parameters - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../Headers/Headers.mdx) object or object literal of [`String`](../../String/String.mdx) key/value pairs. ### Return value Always returns `undefined`. ### Examples ```js event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'] ]); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/FormData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData() The **`FormData()`** constructor creates a new `FormData` object. ## Syntax ```js new FormData() new FormData(form) ``` > **Note:** `FormData()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `form` _**optional**_ - : An HTML `` element — when specified, the `FormData` object will be populated with the form's current key/value pairs using the name property of each element for the keys and their submitted value for the values. File input elements are handled specially: their values are taken from the files selected by the user in the upload control. ### Return value A new `FormData` object, pre-populated with form data if the optional `form` parameter was provided. ## Description The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using methods such as `fetch()`. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also append additional data to the `FormData` object after it's created using its various methods. A `FormData` object can be used in a number of ways with other APIs: 1. It can be sent with the `fetch()` API 2. It works seamlessly with the `Request` and `Response` objects - it can be used directly as the body of a `Request` object 3. It can be obtained from a `Response` object using the `formData()` method 4. It can be passed directly to the `URLSearchParams` constructor The transmitted data is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to `"multipart/form-data"`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.append() The **`append()`** method of the `FormData` interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. ## Syntax ```js append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.delete() The **`delete()`** method of the `FormData` interface removes all key/value pairs with the given name from the `FormData` object. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.entries() The **`entries()`** method of the `FormData` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator yields a new array for each key/value pair, with the first element being the key and the second element being the value. ## Syntax ```js entries() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.forEach() The **`forEach()`** method of the `FormData` interface executes the provided callback function once for each key/value pair in the `FormData` object. ## Syntax ```js forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each entry in the object. The function will be passed the following arguments: - `value` - : The value of the current entry. - `key` - : The key of the current entry. - `formData` - : The `FormData` object being traversed. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.get() The **`get()`** method of the `FormData` interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the [`getAll()`](../../../globals/FormData/prototype/getAll.mdx) method instead. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value A `FormDataEntryValue` containing the value. If the key does not exist, it returns `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/prototype/getAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.getAll() The **`getAll()`** method of the `FormData` interface returns all the values associated with a given key from within a `FormData` object. ## Syntax ```js getAll(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value An array of `FormDataEntryValue` items containing all values with the given key. If the key doesn't exist, an empty array is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.has() The **`has()`** method of the `FormData` interface returns a boolean indicating whether a `FormData` object contains a key/value pair with the given name. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the key you want to test for existence. ### Return value `true` if a key/value pair with the specified name exists; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.keys() The **`keys()`** method of the `FormData` interface returns an iterator allowing iteration through all keys contained in this object. The iterator yields the key for each value. ## Syntax ```js keys() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.set() The **`set()`** method of the `FormData` interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and [`append()`](../../../globals/FormData/prototype/append.mdx) is that if the specified key already exists, `set()` overwrites all existing values with the new one, whereas `append()` appends the new value onto the end of the existing values. ## Syntax ```js set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/FormData/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.values() The **`values()`** method of the `FormData` interface returns an iterator allowing iteration through all values contained in this object. The iterator yields the value for each key/value pair. ## Syntax ```js values() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name is not the name of an HTTP header, this method throws a `TypeError`. The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/prototype/getSetCookie.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.getSetCookie() The **`getSetCookie()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns an array of all the values of the `Set-Cookie` headers, returning an empty list if none are present. ## Syntax ```js getSetCookie() ``` ### Return value `String[]` representing the list of `Set-Cookie` headers. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2 or greater than π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex where x is a number very close to 0, you should get an answer very close to 1 + x, because limx0ex1x=1. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, a `ReadableStream` object, a [`Blob`](../../globals/Blob/Blob.mdx) object, or a [`FormData`](../../globals/FormData/FormData.mdx) object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_, see [`CacheOverride`](../../fastly:cache-override/CacheOverride/CacheOverride.mdx). - `cacheKey` _**Fastly-specific**_ - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.blob() The **`blob()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/clone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.clone() The **`clone()`** method of the `Request` interface creates a copy of the current `Request` object. Like the underlying `ReadableStream.tee`` api, the `body` of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Beware when you construct a `Request` from a stream and then `clone` it. `clone()` throws a `TypeError` if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) If you intend to modify the request, you may prefer the `Request` constructor. ## Syntax ```js clone() ``` ### Parameters None. ### Return value A `Request` object, which is an exact copy of the `Request` that `clone()` was called on. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.formData() The **`formData()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. - `SyntaxError` - : Thrown if the request's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Request` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Request instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - [`Blob`](../../globals/Blob/Blob.mdx) - [`FormData`](../../globals/FormData/FormData.mdx) - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.blob() The **`blob()`** method of the [`Response`](../Response.mdx) interface takes a [`Response`](../Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.formData() The **`formData()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. - `SyntaxError` - : Thrown if the response's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/ip.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ip The **`ip`** getter of the `Response` interface returns the IP address associated with the request, as either an IPv6 or IPv4 string. In the case where no IP address is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with an IP, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.port The **`port`** getter of the `Response` interface returns the port associated with the request, as a number. In the case where no port is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with a port, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Response` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Response instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - For ECDSA: Pass an [`EcKeyImportParams`](../../EcKeyImportParams/EcKeyImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](https://en.wikipedia.org/wiki/HZ_(character_encoding)). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Explicit Backends Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service. This `backend` option is then a special Fastly-specific fetch option that is provided to the `fetch()` call: ```js fetch('https://origin.com/path', { backend: 'origin' }); ``` Backends are configured using the Fastly service backend configuration, see the [Backend documentation](https://developer.fastly.com/reference/api/services/backend/) for more information. ## Dynamic Backends Dynamic backends are a compute feature that allow services to define backends for themselves. If the `backend` option is not provided when making `fetch()` requests, a backend will be automatically created by extracting the protocol, host, and port from the provided URL. In addition, custom backend configuration options can then also be provided through the [`Backend()`](../fastly:backend/Backend/Backend.mdx) constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ - `imageOptimizerOptions` _**Fastly-specific**_, see [`imageOptimizerOptions`](../fastly:image-optimizer/imageOptimizerOptions.mdx). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-3.39.0/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/after.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # after The `after` method inserts content after the closing tag of the element. ## Syntax ```js element.after(content); element.after(content, options); ``` ### Parameters - `content` _: string_ - The content to insert after the element's closing tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.after("World"); // Result:
Hello
World ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # append The `append` method inserts content at the end of the element's content. ## Syntax ```js element.append(content); element.append(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the end of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.append(", World"); // Result:
Hello, World
``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/before.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # before The `before` method inserts content before the opening tag of the element. ## Syntax ```js element.before(content); element.before(content, options); ``` ### Parameters - `content` _: string_ - The content to insert before the element's opening tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.before("Well"); // Result: Well
Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/hasAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # hasAttribute The `hasAttribute` method returns a `boolean` value indicating whether the specified attribute is present on the element. ## Syntax ```js element.hasAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to check for. ### Return value A boolean value indicating whether the attribute is present. ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/prepend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # prepend The `prepend` method inserts content at the beginning of the element's content. ## Syntax ```js element.prepend(content); element.prepend(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the beginning of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.prepend("Well, "); // Result:
Well, Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/removeAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # removeAttribute The `removeAttribute` method removes the specified attribute from the element. ## Syntax ```js element.removeAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to remove. ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/replaceChildren.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceChildren The `replaceChildren` method replaces the element's children with new content. ## Syntax ```js element.replaceChildren(content); element.replaceChildren(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element's children with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceChildren("Greetings!"); // Result:
Greetings!
``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/replaceWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceWith The `replaceWith` method replaces the element with new content. ## Syntax ```js element.replaceWith(content); element.replaceWith(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceWith("

Greetings!

"); // Result:

Greetings!

``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/selector.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # selector The `selector` read-only property is a `string` representing the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) that matches the element. ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/setAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setAttribute The `setAttribute` method sets the value of the specified attribute on the element. If the value already exists, it will be updated; otherwise, a new attribute with the specified name and value will be added to the element. ## Syntax ```js element.setAttribute(attributeName, value); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to set. - `value` _: string_ - The value to assign to the attribute. ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/Element/prototype/tag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # tag The `tag` read-only property is a `string` representing the tag name of the element. ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/HTMLRewritingStream/HTMLRewritingStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `HTMLRewritingStream()` The **`HTMLRewritingStream`** lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback. This callback can manipulate the attributes of the element, and add or remove content from the immediate context. ## Syntax ```js new HTMLRewritingStream() ``` ### Return value A new `HTMLRewritingStream` object. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/html-rewriter/HTMLRewritingStream/prototype/onElement.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # onElement ▸ **onElement**`(selector: string, handler: (element: Element) => void): this` Registers an element handler with the [`HTMLRewritingStream`] that will be called for each [`Element`] that matches the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) `selector`. Elements added by handlers will not be processed by other handlers. ## Syntax ```js .onElement(selector, handler) ``` ### Parameters - `selector` _: string_ - A CSS selector that determines the elements for which `handler` will be called - The following types of CSS selector are supported: Currently the rewriter supports the following CSS selectors: | Pattern | Description | |----------------------|----------------------------------------------------------------------------| | `*` | Any element | | `E` | All elements of type `E` | | `E F` | `F` elements inside `E` elements | | `E > F` | `F` elements directly inside `E` elements | | `E:nth-child(n)` | The n-th child of type `E` | | `E:first-child` | First child of type `E` | | `E:nth-of-type(n)` | The n-th sibling of type `E` | | `E:first-of-type` | First sibling of type `E` | | `E:not(s)` | Type `E` elements not matching selector `s` | | `E.myclass` | Type `E` elements with class `"myclass"` | | `E#myid` | Type `E` elements with ID `"myid"` | | `E[attr]` | Type `E` elements with attribute `attr` | | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | | `E[attr="val" i]` | Type `E` elements where `attr` is `"val"`, case-insensitive | | `E[attr="val" s]` | Type `E` elements where `attr` is `"val"`, case-sensitive | | `E[attr~="val"]` | Type `E` elements where `attr` contains `"val"` in a space-separated list | | `E[attr`|`;="val"]`| Type `E` elements where `attr` is hyphen-separated and starts with `"val"` | | `E[attr^="val"]` | Type `E` elements where `attr` starts with `"val"` | | `E[attr$="val"]` | Type `E` elements where `attr` ends with `"val"` | | `E[attr*="val"]` | Type `E` elements where `attr` contains `"val"` | - `handler` _: (element: Element) => void_ - A callback function that will be called once for each element that matches `selector` ### Return value The `HTMLRewritingStream`, so multiple calls to `onElement` can be chained. ### Exceptions - `Error` - If the provided `selector` is not a valid CSS selector. - If the provided `handler` is not a function. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/Auto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Auto` Enumerator options for [`imageOptimizerOptions.auto`](./imageOptimizerOptions.mdx). ## Constants - `AVIF` (`"avif"`) If the browser's Accept header indicates compatibility, deliver an AVIF image. - `WEBP` (`"webp"`) If the browser's Accept header indicates compatibility, deliver a WebP image. ## Examples ```js import { Auto, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, auto: Auto.AVIF }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/BWAlgorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `BWAlgorithm` Enumerator options for [`imageOptimizerOptions.bw`](./imageOptimizerOptions.mdx). ## Constants - `Threshold` (`"threshold"`) Uses a luminance threshold to convert the image to black and white. - `Atkinson` (`"atkinson"`) Uses [Atkinson dithering](https://en.wikipedia.org/wiki/Atkinson_dithering) to convert the image to black and white. ## Examples ```js import { Region, BWAlgorithm } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, bw: BWAlgorithm.Threshold }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/CropMode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CropMode` Enumerator options for [`imageOptimizerOptions.crop.mode`](./imageOptimizerOptions.mdx) and `imageOptimizerOptions.precrop.mode`. ## Constants - `Smart` (`"smart"`) Enables content-aware algorithms to attempt to crop the image to the desired aspect ratio while intelligently focusing on the most important visual content, including the detection of faces. - `Safe` (`"safe"`) Allow cropping out-of-bounds regions. ## Examples ```js import { CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Smart, } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/Disable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Disable` Enumerator options for [`imageOptimizerOptions.disable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Prevent images being resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Disable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, disable: Disable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/Enable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Enable` Enumerator options for [`imageOptimizerOptions.enable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Allow images to be resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Enable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, enable: Enable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/Fit.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Fit` Enumerator options for [`imageOptimizerOptions.fit`](./imageOptimizerOptions.mdx). ## Constants - `Bounds` (`"bounds"`) Resize the image to fit entirely within the specified region, making one dimension smaller if needed. - `Cover` (`"cover"`) Resize the image to entirely cover the specified region, making one dimension larger if needed. - `Crop` (`"crop"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Fit, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 150, height; 150, fit: Fit.Bounds }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/Format.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Format` Enumerator options for [`imageOptimizerOptions.format`](./imageOptimizerOptions.mdx). ## Constants - `Auto` (`"auto"`) Automatically use the best format based on browser support and image/transform characteristics - `AVIF` (`"avif"`) AVIF - `BJPG` (`"bjpg"`) Baseline JPEG - `GIF` (`"gif"`) Graphics Interchange Format - `JPG` (`"jpg"`) JPEG - `JXL` (`"jxl"`) JPEGXL - `MP4` (`"mp4"`) MP4 (H.264) - `PJPG` (`"pjpg"`) Progressive JPEG - `PJXL` (`"pjxl"`) Progressive JPEGXL - `PNG` (`"png"`) Portable Network Graphics - `PNG8` (`"png8"`) Portable Network Graphics palette image with 256 colors and 8-bit transparency - `SVG` (`"svg"`) Scalable Vector Graphics - `WEBP` (`"webp"`) WebP - `WEBPLL` (`"webpll"`) WebP (Lossless) - `WEBPLY` (`"webply"`) WebP (Lossy) ## Examples ```js import { Format, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/Metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Metadata` Enumerator options for [`imageOptimizerOptions.metadata`](./imageOptimizerOptions.mdx). ## Constants - `Copyright` (`"copyright"`) Preserve [copyright notice](https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#copyright-notice), creator, credit line, licensor, and web statement of rights fields. - `C2PA` (`"c2pa"`) Preserve the [C2PA manifest](https://c2pa.org/) and add any transformations performed by Fastly Image Optimizer. - `CopyRightAndC2PA` (`"copyright,c2pa"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Metadata, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, metadata: Metadata.Copyright }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/Optimize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Optimize` Enumerator options for [`imageOptimizerOptions.optimize`](./imageOptimizerOptions.mdx). ## Constants - `Low` (`"low"`) Output image quality will be similar to the input image quality. - `Medium` (`"medium"`) More optimization is allowed. We attempt to preserve the visual quality of the input image. - `High` (`"high"`) Minor visual artifacts may be visible. This produces the smallest file. ## Examples ```js import { Optimize, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, optimize: Optimize.High }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/Orient.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Orient` Enumerator options for [`imageOptimizerOptions.orient`](./imageOptimizerOptions.mdx). ## Constants - `Default` (`"1"`) - `FlipHorizontal` (`"2"`) - `FlipHorizontalAndVertical` (`"3"`) - `FlipVertical` (`"4"`) - `FlipHorizontalOrientLeft` (`"5"`) - `OrientRight` (`"6"`) - `FlipHorizontalOrientRight` (`"7"`) - `OrientLeft` (`"8"`) ## Examples ```js import { Orient, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, orient: Orient.FlipHorizontal }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/Profile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Profile` Enumerator options for [`imageOptimizerOptions.profile`](./imageOptimizerOptions.mdx). ## Constants - `Baseline` (`"baseline"`) The profile recommended for video conferencing and mobile applications. (Default) - `Main` (`"main"`) The profile recommended for standard-definition broadcasts. - `High` (`"high"`) The profile recommended for high-definition broadcasts. ## Examples ```js import { Profile, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, profile: Profile.Main }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/Region.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Region` Enumerator options for [`imageOptimizerOptions.region`](./imageOptimizerOptions.mdx). ## Constants - `UsEast` (`"us_east"`) - `UsCentral` (`"us_central"`) - `UsWest` (`"us_west"`) - `EuCentral` (`"eu_central"`) - `EuWest` (`"eu_west"`) - `Asia` (`"asia"`) - `Australia` (`"australia"`) ## Examples ```js import { Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/ResizeFilter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ResizeFilter` Enumerator options for [`imageOptimizerOptions.resizeFilter`](./imageOptimizerOptions.mdx). ## Constants - `Nearest` (`"nearest"`) Uses the value of nearby translated pixel values. - `Bilinear` (`"bilinear"`) Uses an average of a 2x2 environment of pixels. - `Linear` (`"linear"`) Same as `Bilenear`. - `Bicubic` (`"bicubic"`) Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. - `Cubic` (`"cubic"`) Same as `Bicubic`. - `Lanczos2` (`"lanczos2"`) Uses the Lanczos filter to increase the ability to detect edges and linear features within an image and uses sinc resampling to provide the best possible reconstruction. - `Lanczos3` (`"lanczos3"`) Lanczos3 uses a better approximation of the sinc resampling function. (Default) - `Lanczos` (`"lanczos"`) Same as `Lanczos3`. ## Examples ```js import { ResizeFilter, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, resizeFilter: ResizeFilter.Linear }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/image-optimizer/imageOptimizerOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `imageOptimizerOptions` Options specified in the [`Request`](../globals/Request/Request.mdx) constructor for running the [Fastly Image Optimizer](https://docs.fastly.com/products/image-optimizer). More detailed documentation on all Image Optimizer options is available in the [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/). ## Parameters All parameters other than `region` are optional. - `region`: _[`Region`](./Region.mdx)_ Where image optimizations should occur. - `auto`: _[`Auto`](./Auto.mdx)_ Enable optimization features automatically. - `bgColor`: _[`Color`](#color)_ Set the background color of an image. - `blur`: _`number` (0.5-1000) or [`Percentage`](#percentage)_ Set the blurriness of the output image. - `brightness`: _`number` (-100-100)_ Set the brightness of the output image. - `bw`: _[`BWAlgorithm`](./BWAlgorithm.mdx)_ Convert an image to black and white. - `canvas`: _`Object`_ Increase the size of the canvas around an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `contrast`: _`number` (-100-100)_ Set the contrast of the output image. - `crop`: _`Object`_ Remove pixels from an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `mode` (optional): _[`CropMode`](./CropMode.mdx)_ - `disable`: _[`Disable`](./Disable.mdx)_ Disable functionality that is enabled by default. - `dpr`: `number` Ratio between physical pixels and logical pixels. - `enable`: _[`Enable`](./Enable.mdx)_ Enable functionality that is disabled by default. - `fit`: _[`Fit`](./Fit.mdx)_ Set how the image will fit within the size bounds provided. - `format`: _[`Format`](./Format.mdx)_ Specify the output format to convert the image to. - `frame`: _`number` (must have the value 1)_ Extract the first frame from an animated image sequence. - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the height of the image. - `level`: _`String` containing one of the [allowed values](https://www.fastly.com/documentation/reference/io/level/#allowed-values)_ Specify the level constraints when converting to video. - `metadata`: _[`Metadata`](./Metadata.mdx)_ Control which metadata fields are preserved during transformation. - `optimize`: _[`Optimize`](./Optimize.mdx)_ Automatically apply optimal quality compression. - `orient`: _[`Orient`](./Orient.mdx)_ Change the cardinal orientation of the image. - `pad`: _[`Sides`](#sides)_ Add pixels to the edge of an image. - `precrop`: _`Object`_ Remove pixels from an image before any other transformations occur. - `size`: _[`Size`](#size)_ - `position`: _[`Position`](#position)_ - `mode`: _[`CropMode`](./CropMode.mdx)_ - `profile`: _[`Profile`](./Profile.mdx)_ Specify the profile class of application when converting to video. - `quality`: _`integer` (1-100)_ Optimize the image to the given compression level for lossy file formatted images. - `resizeFilter`: _[`ResizeFilter`](./ResizeFilter.mdx)_ Specify the resize filter used when resizing images. - `saturation`: _`number` (-100-100)_ Set the saturation of the output image. - `sharpen`: _`Object`_ Set the sharpness of the output image. - `amount`: _`number` (0-10)_ - `radius`: _`number` (0.5-1000)_ - `threshold`: _`integer` (0-255)_ - `trim`: _[`Sides`](#sides)_ Remove pixels from the edge of an image. - `viewbox`: _`number` (must have the value 1)_ Remove explicit width and height properties in SVG output. - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the width of the image. ## Types ### Color Either: - a 3 or 6 character hexadecimal string - an `Object` containing: - `r`: _`integer` (0-255)_ Red component - `g`: _`integer` (0-255)_ Green component - `b`: _`integer` (0-255)_ Blue component - `a` (optional): _`number` (0.0-1.0)_ Alpha component ### Percentage A `String` containing a number suffixed with a percent sign (%). ### Position An `Object` containing: - Exactly one of: - `x`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetX`: _`number` (interpreted as a percentage)_ - Exactly one of: - `y`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetY`: _`number` (interpreted as a percentage)_ ### Sides An `Object` containing `top`, `bottom`, `left`, and `right`, all of which are either an `integer` or [`Percentage`](#percentage). ### Size An `Object` containing either: - `absolute`: _`Object`_ - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `ratio`: _`Object`_ - `width`: _`number`_ - `height`: _`number`_ ## Examples ```js import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG, bgColor: { 'r': 100, 'g': 255, 'b': 9, 'a': 0.5 }, blur: '1%', brightness: -20, contrast: -20, height: 600, level: '4.0', orient: Orient.FlipVertical, saturation: 80, sharpen: { 'amount': 5, 'radius': 6, 'threshold': 44 }, canvas: { 'size': { 'absolute': { 'width': 400, 'height': 400 } } }, crop: { size: { absolute: { width: 200, height: 200 }, mode: CropMode.Safe } }, trim: { top: 10, left: 10, right: 10, bottom: 10 }, pad: { top: 30, left: 30, right: "1%", bottom: 30 } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a KV store instance using the resource link name. ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStore/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.delete Deletes the value associated with the key `key` in the KV store. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value Returns `undefined` ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - Does not exist ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then delete the entry. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') await files.delete('hello') const entry = await files.get('hello') if (entry) { return new Response(await entry.text()) } else { return new Response('no file named hello exists') } } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStore/prototype/list.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.list The **`list()`** can be used to list the keys of a store. ## Syntax ```js list(options?) ``` ### Parameters - `options` _: object_ _**optional**_ - List options supporting properties: - `cursor` _: string_ _**optional**_ - The cursor used to pick up from a previous iteration. - `limit` _: number_ _**optional**_ - The maximum number of keys to return. - `prefix` _: string_ _**optional**_ - List only those keys that start with the given string prefix. - `noSync` _: boolean_ _**optional**_ - Do not sync the key list first, instead provide a possibly out-of-date listing. May be faster but inconsistent. ### Return value Returns a `Promise` which resolves with `{ list: string[], cursor: string | undefined }`. ## Example In this example we list the keys of a KV Store named `'files'`, iterating 10 at a time, counting the total; ```js /// import { KVStore } from 'fastly:kv-store'; async function app(event) { const files = new KVStore('files'); let cursor, list, total = 0; do { ({ cursor, list } = await files.list({ limit: 10, cursor })); total += list?.length; } while (list); return new Response(`Iterated ${total} entries`); } addEventListener('fetch', (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value, options?) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. - `options` _: object_ _**optional**_ - An insert options parameter, supporting: - `metadata` _: ArrayBuffer | TypedArray | DataView_ _**optional**_ - Binary metadata associated with the entry, may be up to 1000 bytes. - `ttl` _: number_ _**optional**_ - TTL for the entry - `mode` _: 'overwrite' | 'add' | 'append' | 'prepend'_ _**optional**_ - Insert mode, defaults to 'overwrite' - `gen` _: number_ _**optional**_ - 'generation' header specific to the version of an entry key ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - `TypeError` - If the provided `gen`: - Is not an number ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStoreEntry/prototype/metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadata() The `metadata()` method of the `KVStoreEntry` interface provides the binary metadata associated with the `KVStoreEntry`. The metadata binary may be up to 1000 bytes, and is returned as a `Uint8Array` TypedArray buffer, if metadata is set, or null otherwise. ## Syntax ```js metadata() ``` ### Parameters None. ### Return value A `Promise` that resolves to a `Uint8Array` buffer object. ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStoreEntry/prototype/metadataText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadataText() The `metadataText()` method of the `KVStoreEntry` interface provides a String interpretation of binary metadata associated with the `KVStoreEntry`. If the binary data is not a valid string, an encoding error will be thrown. ## Syntax ```js metadataText() ``` ### Parameters None. ### Return value A `Promise` that resolves to a String. ================================================ FILE: documentation/versioned_docs/version-3.39.0/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; const logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; let logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/logger/configureConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # configureConsole The **`configureConsole()`** function allows configuring the behaviour of the `console` global JS logger. ## Syntax ```js configureConsole(loggingOptions) ``` ### Parameters - `loggingOptions` _: object_ - - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ## Examples In this example, we disable prefixing for `console.log` and use `stderr` output for `console.error`: ```js import { configureConsole } from "fastly:logger"; configureConsole({ prefixing: false, stderr: true }); async function handleRequest(event) { console.log(JSON.stringify(event.request.headers)); const url = new URL(event.request.url); try { validate(url); } catch (e) { console.error(`Validation error: ${e}`); return new Response('Bad Request', { status: 400 }); } return new Response('OK'); } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v2 to v3` ## SimpleCache.delete renamed to SimpleCache.purge and requires purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using `SimpleCache.delete` to `SimpleCache.purge` with the same purging behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a Secret Store instance using the resource link name. ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/secret-store/SecretStore/fromBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fromBytes The **`fromBytes()`** function is used to create an in-memory secret from an array buffer. >**Note**: This API should be avoided when possible, by instead using [SecretStore.prototype.get](./prototype/get.mdx) to obtain secure secrets. ## Syntax ```js fromBytes(new Uint8Array([1, 2, 3])) ``` ### Parameters None. ### Return value Returns a `SecretStoreEntry`. ================================================ FILE: documentation/versioned_docs/version-3.39.0/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/secret-store/SecretStoreEntry/prototype/rawBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.rawBytes ▸ **rawBytes**(): `Uint8Array` Returns the raw byte contents of the SecretStoreEntry instance as a Uint8Array. ## Syntax ```js rawBytes() ``` ### Parameters None. ### Return value A Uint8Array ### Exceptions The `rawBytes()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ================================================ FILE: documentation/versioned_docs/version-3.39.0/security/inspect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # inspect The **`inspect()`** function inspects a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). ## Syntax ```js inspect(request, config); ``` ### Parameters - `request` _: Request_ - The Request to get a WAF determination for. - `config` _: object_ - `corp` _: string_ - Set a corp name for the configuration. - This parameter is currently required. - `workspace` _: string_ - Set a workspace name for the configuration. - This parameter is currently required. - `overrideClientIp` _: string_ - Specify an explicit client IP address to inspect. - By default, `inspect` will use the IP address that made the request to the running Compute service, but you may want to use a different IP when service chaining or if requests are proxied from outside of Fastly’s network. ### Return value Returns an `Object` with the `inspect` response, with the following fields: - `waf_response` _: number_ - Security status code. - `redirect_url` _: string | null_ - A redirect URL returned from Security. - `tags` _: string[]_ - Tags returned by Security. - `verdict` _: string_ - The outcome of inspecting a request with Security. It can be one of the following: - `"allow"` - Security indicated that this request is allowed. - `"block"` - Security indicated that this request should be blocked. - `"unauthorized"` - Security indicated that this service is not authorized to inspect a request. - Other verdicts may be returned but not currently documented. - `decision_ms` _: number_ - How long Security spent determining its verdict, in milliseconds. ## Examples ```js /// import { inspect } from "fastly:security"; async function app(event) { const res = inspect(event.request, { corp: "mycorp", workspace: "myws" }); switch (res.verdict) { case "allow": return await fetch(event.request); case "block": return new Response("Request Blocked", { status: 400 }); case "unauthorized": return new Response("Unauthorized", { status: 401 }); default: return new Response("idk", { status: 500 }); } } addEventListener("fetch", (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/shielding/Shield/Shield.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Shield()` Load information about the given shield. Returns an object representing the shield if it is active, or throws an exception if the string is malformed or the shield doesn’t exist. Shield names are defined on [this webpage](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations), in the “shield code” column. For example, the string “pdx-or-us” will look up our Portland, OR, USA shield site, while “paris-fr” will look up our Paris site. If you are using a major cloud provider for your primary origin site, consider looking at the “Recommended for” column, to find the Fastly POP most closely located to the given cloud provider. ## Syntax ```js new Shield(name) ``` > **Note:** `Shield()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Exceptions - `TypeError` - Thrown if no Shield exists with the provided name ## Examples In this example, we create a Shield instance for the Sydney, Australia shield POP. If the code is running on that shield POP, it fetches directly from origin. Otherwise, it routes the request through the shield using an encrypted connection. ```js /// import { Shield } from "fastly:shielding"; async function app(event) { const shield = new Shield('wsi-australia-au'); // If running on the shield POP, fetch from the origin directly if (shield.runningOn()) { return await fetch('https://http-me.fastly.com/anything', { backend: 'httpme' }); } // Otherwise, route the request through the shield using an encrypted connection return await fetch(event.request, { backend: shield.encryptedBackend() }); } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.0/shielding/Shield/prototype/encryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.encryptedBackend ▸ **encryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an encrypted connection to the POP. For reference, this is almost always the backend that you want to use. Only use [`Shield::unencryptedBackend`](./unencryptedBackend.mdx) in situations in which you are 100% sure that all the data you will send and receive over the backend is already encrypted. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.39.0/shielding/Shield/prototype/runningOn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.runningOn ▸ **runningOn**(): `boolean` Returns whether we are currently operating on the given shield. Technically, this may also return true in very isolated incidents in which Fastly is routing traffic from the target shield POP to the POP that this code is running on, but in these situations the results should be approximately identical. (For example, it may be the case that you are asking to shield to ‘pdx-or-us’. But, for load balancing, performance, or other reasons, Fastly is temporarily shifting shielding traffic from Portland to Seattle. In that case, this function may return true for hosts running on ‘bfi-wa-us’, our Seattle site, because effectively the shield has moved to that location. This should give you a slightly faster experience than the alternative, in which this function would return false, you would try to forward your traffic to the Portland site, and then that traffic would be caught and redirected back to Seattle.) ================================================ FILE: documentation/versioned_docs/version-3.39.0/shielding/Shield/prototype/unencryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.unencryptedBackend ▸ **unencryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an unencrypted connection to the POP. Generally speaking, we encourage users to use [`Shield::encryptedBackend`](./encryptedBackend.mdx) instead of this function. Data sent over this backend – the unencrypted version – will be sent over the open internet, with no protections. In most cases, this is not what you want. However, in some cases – such as when you want to ship large data blobs that you know are already encrypted — using these backends can prevent a double-encryption performance penalty. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.39.0/websocket/createWebsocketHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createWebsocketHandoff The **`createWebsocketHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Websocket, to the declared backend. ## Syntax ```js createWebsocketHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Websocket. - `backend` _: string_ - The name of the backend that Websocket should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Websocket. ```js import { createWebsocketHandoff } from "fastly:websocket"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createWebsocketHandoff(event.request, 'websocket_backend'); } else { return new Response('oopsie, make a request to /stream for some websocket goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/acl/Acl/open.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.open() Opens the ACL with the given name, returning a new `Acl` instance with the given name on success. ## Syntax ```js Acl.open(name) ``` ### Return value An `Acl` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.1/acl/Acl/prototype/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.prototype.lookup() The **`lookup(ipAddress)`** method returns the name associated with the `Acl` instance. ## Syntax ```js acl.lookup(ipAddress) ``` ### Parameters - `ipAddress` _: string_ - IPv4 or IPv6 address to lookup ### Return value An Object of the form `{ action: 'ALLOW' | 'BlOCK', prefix: string }`, where `prefix` is the IP address prefix that was matched in the ACL. ## Example ```js /// import { Acl } from 'fastly:acl'; addEventListener('fetch', async (evt) => { const myAcl = Acl.open('myacl'); const match = await myAcl.lookup(evt.client.address); evt.respondWith(new Response(match?.action === 'BLOCK' ? 'blocked' : 'allowed')); }); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. >**Note**: Dynamic backends are by default disabled at the Fastly service level. Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request dynamic backends on Fastly Services. To disable the usage of dynamic backends, see [enforceExplicitBackends](../enforceExplicitBackends.mdx). ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. - `grpc` _: boolean_ _**optional**_ - **_Experimental feature_** - When enabled, sets that this backend is to be used for gRPC traffic. - _Warning: When using this experimental feature, no guarantees are provided for behaviours for backends that do not provide gRPC traffic._ All optional generic options can have their defaults set via [`setDefaultDynamicBackendConfig()`](../setDefaultDynamicBackendConfig.mdx). This includes all configuration options above except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. ### Return value A new `Backend` object. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/exists.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.exists() The **`Backend.exists()`** method returns a boolean indicating if a Backend with the given name exists or not. ## Syntax ```js exists(name) ``` ### Return value A boolean indicating if a Backend with the given name exists or not. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/fromName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.fromName() Returns the `Backend` instance with the given name, if one exists. If one does not exist, an error is thrown. ## Syntax ```js fromName(name) ``` ### Return value A `Backend` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.health() :::info This method is deprecated, use [`Backend.prototype.health`](./prototype/health.mdx) instead. ::: The **`Backend.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js Backend.health(backend) ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/betweenBytesTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.betweenBytesTimeout The read-only **`betweenBytesTimeout`** property of a `Backend` instance is an integer number providing the between bytes timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/connectTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.connectTimeout The read-only **`connectTimeout`** property of a `Backend` instance is an integer number providing the connect timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/firstByteTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.firstByteTimeout The read-only **`firstByteTimeout`** property of a `Backend` instance is an integer number providing the first byte timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.health() The **`Backend.prototype.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js health() ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/hostOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.hostOverride The read-only **`hostOverride`** property of a `Backend` instance is the host header override string used when sending requests to this backend. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/httpKeepaliveTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.httpKeepaliveTime The read-only **`httpKeepaliveTime`** property of a `Backend` instance is the HTTP keepalive time for this backend in milliseconds, or 0 if no keepalive is set. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/isDynamic.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isDynamic The read-only **`isDynamic`** property of a `Backend` instance is a boolean indicating if the backend was dynamically created for this service. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/isSSL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isSSL The read-only **`isSSL`** property of a `Backend` instance is a boolean indicating if the backend is using an SSL connection. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # name The read-only **`name`** property of the backend returns the backend name string. ## Value A `string`. ## Description Provides the name of the backend. ## Examples ### Using name The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.port The read-only **`port`** property of a `Backend` instance is the port number of this backend. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/target.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.target The read-only **`target`** property of a `Backend` instance is the host string this backend is configured to use. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/tcpKeepalive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tcpKeepalive The read-only **`tcpKeepalive`** property of a `Backend` instance returns an object providing the TCP keepalive configuration, if any, otherwise returning `null` if TCP keepalive is not enabled. This object has the following properties: - `timeSecs` _: number or null._ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number or null._ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number or null._ - Number of probes to send to the backend before it is considered dead. ## Value A `Object` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/tlsMaxVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMaxVersion The read-only **`tlsMaxVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/tlsMinVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMinVersion The read-only **`tlsMinVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/toName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.toName() :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toName()`** method returns the name associated with the `Backend` instance. ## Syntax ```js toName() ``` ### Return value A string which contains the name of the Backend. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toString :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends :::info This method is deprecated, and dynamic backends are now always supported when enabled at the service level. See [`enforceExplicitBackends`](./enforceExplicitBackends.mdx) instead. ::: The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: By default, while dynamic backends are allowed in the SDK, they are by default disabled at the Fastly service level. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/enforceExplicitBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enforceExplicitBackends Call this function to enforce the security property of explicitly-defined backends, even when dynamic backends are enabled at the Fastly service level. By default, if dynamic backends are supported for the Fastly service, they will be automatically used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a potential security concern since third-party JavaScript code may send arbitrary requests, including sensitive/secret data, off to destinations that the JavaScript project was not intending. When calling this function, an optional default backend name can be provided. >**Note**: This is a separate option to the service-level dynamic backend support for Fastly services, which is by deault disabled for Fastly services. The **`enforceExplicitBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: Dynamic Backends are disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled or disabled on Fastly Services. ## Syntax ```js enforceExplicitBackends(defaultBackend?) ``` ### Parameters - `defaultBackend` _: string_ _**optional**_ - An optional default backend string name to use in `fetch()` requests. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/backend/setDefaultDynamicBackendConfig.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setDefaultDynamicBackendConfig() The **`setDefaultDynamicBackendConfig()`** allows setting backend configuration defaults that should apply to any newly created dynamic backends via the `new Backend()` constructor. ### Parameters - `defaultDynamicBackendConfig` - : An Object which contains the generic configuration options to apply to newly created Backends. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. ## Syntax ```js setDefaultDynamicBackendConfig(defaultConfig) ``` ### Return value None. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, with timeouts and TLS options provided from the default backend configuration options. import { allowDynamicBackends } from "fastly:experimental"; import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! // Timeouts and TLS configuration still get set from the default backend configuration above. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.age The **`age`** method of the `CacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.body The **`body`** method of the `CacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this `CacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.close The **`close`** method of the `CacheEntry` interface closes the connection to the cache for this `CacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.hits The **`hits`** method of the `CacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.length The **`length`** method of the `CacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.maxAge The **`maxAge`** method of the `CacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `CacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.state The **`state`** method of the `CacheEntry` interface returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.userMetadata The **`userMetadata`** method of the `CacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheState/found.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.found The **`found`** method of the `CacheState` interface returns `true` if a cached item was located. Even if an cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. ## Syntax ```js found() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item was located or not. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheState/mustInsertOrUpdate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.mustInsertOrUpdate The **`mustInsertOrUpdate`** method of the `CacheState` interface returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. ## Syntax ```js mustInsertOrUpdate() ``` ### Parameters None. ### Return value A `boolean` which represents whether a fresh cached item was found not. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheState/stale.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.stale The **`stale`** method of the `CacheState` interface returns `true` if the cached item is stale. A cached item is stale if its age is greater than its `maxAge` period. ## Syntax ```js stale() ``` ### Parameters None. ### Return value A `boolean` which represents whether the cached item is stale or not. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CacheState/usable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.usable The **`usable`** method of the `CacheState` interface returns `true` if the cached item is usable. A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. ## Syntax ```js usable() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item is usable or not. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CoreCache/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.insert Performs a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. ## Syntax ```js insert(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item’s contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CoreCache/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.lookup Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. ## Syntax ```js lookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns `CacheEntry` if a usable cached item was found, otherwise returns `null`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/CoreCache/transactionLookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.transactionLookup Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. Request Collapsing: If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, just one of the callers will be instructed to insert the item into the cache as part of the transaction. The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. Revalidation: Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. ## Syntax ```js transactionLookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns an instance of `TransactionCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, and return a message stating whether the entry was in the Fastly Cache or not. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); return new Response(page ? `${path} is in the cache` : `${path} is not in the cache`, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key`. If no entry is found (or has expired), the supplied `set` function is executed and its result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - The function to execute if and only if the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The maximum number of seconds to store the supplied entry in the cache. - `length` _: number_ __optional__ - The length of the value being stored within the cache. This is only used when the `value` is a `ReadableStream`. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/SimpleCache/purge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.purge purge the entry associated with the key `key` from the cache. ## Syntax ```js purge(key, options) ``` ### Parameters - `key` _: string_ - The key to purge from within the cache. - `options` _: object_ - `scope` _: string_ - : Where to purge the content from. - Possible values are: - "global" - This will remove the content from all of Fastly. - "pop" - This will remove the content from the POP that contains the currently executing instance. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `purge` querystring parameter, we purge the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('purge')) { SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.age The **`age`** method of the `TransactionCacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.body The **`body`** method of the `TransactionCacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `TransactionCacheEntry`. An error will be thrown if a stream is already active for this `TransactionCacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.cancel The **`cancel`** method of the `TransactionCacheEntry` interface cancels an obligation to provide an object to the cache. ## Syntax ```js cancel() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.close The **`close`** method of the `TransactionCacheEntry` interface closes the connection to the cache for this `TransactionCacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.hits The **`hits`** method of the `TransactionCacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insert Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. ## Syntax ```js insert(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/insertAndStreamBack.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insertAndStreamBack Perform a transaction cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. ## Syntax ```js insertAndStreamBack(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns an array where the first item is a `FastlyBody` instance and the second item is a `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.length The **`length`** method of the `TransactionCacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.maxAge The **`maxAge`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.state The **`state`** method of the `TransactionCacheEntry` interface returns a `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/update.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.update Perform an update of the cache item's metadata. ## Syntax ```js update(options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache/TransactionCacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.userMetadata The **`userMetadata`** method of the `TransactionCacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.1/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) new CacheOverride(init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. This options is also the default when providing an init object directly as the first argument. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. - `beforeSend` _:Function_ _**optional**_ - `(request: Request) => void | PromiseLike` - Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. - See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) in the Fastly cache interfaces documentation for details. - `afterSend` _: Function_ _**optional**_ - `(response: Response) => void | CacheOptions | PromiseLike` - Callback to be invoked after a response has been sent, but before it is stored into the cache. - Where `CacheOptions` contains: - `cache` _: boolean | 'uncacheable'_ _**optional**_ - Whether to cache this response. By default, leaving this field empty, responses will be cached based on their cache header information. - Setting this to true or false will override this default cache behaviour, setting in the cache or not setting in the cache, even if the default behaviour would have been otherwise. - Setting to 'uncacheable' the response will not only not be cached, but the cache will record that the originating request led to an uncacheable response, so that future cache lookups will result in immediately going to the backend, rather than attempting to coordinate concurrent requests to reduce backend traffic. - See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) for more details on the mechanism that `uncacheable` disables. - `bodyTransformFn` _: Function_ _**optional**_ - `(body: Uint8Array) => Uint8Array | PromiseLike` - Provide a function to be used for transforming the response body prior to caching. - Body transformations are performed by specifying a transform, rather than by directly working with the body during the onAfterSend callback function, because not every response contains a fresh body: 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because they do not retransmit the body. - For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will be applied to it. The original backend body is passed in to the transform function, and the function is expected to return the new body. - See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) in the Fastly cache interfaces documentation for details. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/compute/purgeSurrogateKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # purgeSurrogateKey The **`purgeSurrogateKey()`** function is used to purge the given surrogate key string from Fastly's cache. There are two purge modes: soft purge and hard purge, with hard purge as the default which clears all items from the cache immediately. When using a soft purge, stale entries are maintained in the cache, reducing orgin load, while also enabling stale revalidations. See the [Fastly Purge Documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) for more information on caching and purge operations. ## Syntax ```js purgeSurrogateKey(surrogateKey, soft?) ``` ### Parameters - `surrogateKey` _: string_ - The surrogate key string - `soft?` _: boolean_ - Enables a soft purge, retaining stale entries in the cache. Default is a hard purge. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/compute/vCpuTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # vCpuTime The **`vCpuTime()`** function provides the vCPU time used by the current request handler in milliseconds. ## Syntax ```js vCpuTime() ``` ### Parameters None. ### Return value `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Defines a config store instance using the resource link name. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have a resource link named "animals" (which is linked to a config store) and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.lookup() Look up the data associated with a particular User-Agent string. ## Syntax ```js lookup(userAgent) ``` ### Return value If there is data associated with the User-Agent, a `Device` instance is returned. Otherwise, `null` is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/brand.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.brand The read-only **`brand`** property of the `Device` interface is either a string stating the brand of the device, which can be different from the manufacturer of that device. If no brand is known, the value will be `null`. ## Value Either a string value if a brand is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/hardwareType.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.hardwareType The read-only **`hardwareType`** property of the `Device` interface is either a string stating the hardware type of the device, or `null` if the hardware type is not known. A string representation of the device's primary platform hardware. The most commonly used device types are also identified via boolean variables. Because a device may have multiple device types and this variable only has the primary type, we recommend using the boolean variables for logic and using this string representation for logging. ## Value Either a string value if a hardware type is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/isBot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isBot The read-only **`isBot`** property of the `Device` interface is either a boolean stating if the device is a bot, or `null` if the this is not known. ## Value Either a boolean stating if the device is a bot, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/isDesktop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isDesktop The read-only **`isDesktop`** property of the `Device` interface is either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ## Value Either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/isGameConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isGameConsole The read-only **`isGameConsole`** property of the `Device` interface is either a boolean stating if the device is a video game console, or `null` if the this is not known. ## Value Either a boolean stating if the device is a video game console, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/isMediaPlayer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMediaPlayer The read-only **`isMediaPlayer`** property of the `Device` interface is either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ## Value Either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/isMobile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMobile The read-only **`isMobile`** property of the `Device` interface is either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ## Value Either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/isSmartTV.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isSmartTV The read-only **`isSmartTV`** property of the `Device` interface is either a boolean stating if the device is a smart TV, or `null` if the this is not known. ## Value Either a boolean stating if the device is a smart TV, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/isTablet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTablet The read-only **`isTablet`** property of the `Device` interface is either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ## Value Either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/isTouchscreen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTouchscreen The read-only **`isTouchscreen`** property of the `Device` interface is either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ## Value Either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/model.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.model The read-only **`model`** property of the `Device` interface is either a string stating the model of the device, or `null` if the model is not known. ## Value Either a string value if a model is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.name The read-only **`name`** property of the `Device` interface is either a string stating the name of the device, or `null` if the name is not known. ## Value Either a string value if a name is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/device/Device/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toJSON The `toJSON()` method of the Device interface is a serializer; it returns a JSON representation of the Device object. To get a JSON string, you can use `JSON.stringify(device)` directly; it will call `toJSON()` automatically. ## Syntax ```js toJSON() ``` ### Return value A JSON object that is the serialization of the Device object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Dictionary()` :::info This Class is deprecated ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/edge-rate-limiter/EdgeRateLimiter/EdgeRateLimiter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `EdgeRateLimiter()` The **`EdgeRateLimiter` constructor** lets you open an epen a [ERL](https://docs.fastly.com/products/edge-rate-limiting) with the given ratecounter and penaltybox. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new EdgeRateLimiter(rateCounter, penaltyBox) ``` > **Note:** `EdgeRateLimiter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `rateCounter` _: RateCounter_ - The RateCounter instance to associate with this EdgeRateLimiter instance - `penaltyBox` _: PenaltyBox_ - The PenaltyBox instance which should be associated with this EdgeRateLimiter instance ### Return value A new `EdgeRateLimiter` object. ### Exceptions - `TypeError` - Thrown if the provided rateCounter value is not an instance of RateCounter - Thrown if the provided penaltyBox value is not an instance of PenaltyBox ================================================ FILE: documentation/versioned_docs/version-3.39.1/edge-rate-limiter/EdgeRateLimiter/prototype/checkRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EdgeRateLimiter.prototype.checkRate Increment an entry in the rate counter and check if the entry has exceeded some average number of requests per second (RPS) over the given window. If the entry is over the RPS limit for the window, add to the penaltybox for the given `timeToLive`. Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ## Syntax ```js checkRate(entry, delta, window, limit, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to increment and check - `delta` _: number_ - The amount to increment the `entry` by - `window` _: number_ - The time period to check across, has to be either 1 second, 10 seconds, or 60 seconds - `limit` _: number_ - The requests-per-second limit - `timeToLive` _: number_ - In minutes, how long the entry should be added into the penalty-box - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `true` if the entry has exceeded the average RPS for the window, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive finite number. - Thrown if the provided `window` value is not either, 1, 10, or 60. - Thrown if the provided `limit` value is not a positive finite number. - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.39.1/edge-rate-limiter/PenaltyBox/PenaltyBox.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `PenaltyBox()` The **`PenaltyBox` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for adding and checking if some entry is in the dataset. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new PenaltyBox(name) ``` > **Note:** `PenaltyBox()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a PenaltyBox with the given name ### Return value A new `PenaltyBox` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.1/edge-rate-limiter/PenaltyBox/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.add Add an `entry` into the PenaltyBox for the duration of the given `timeToLive`. ## Syntax ```js add(entry, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `timeToLive` _: number_ - In minutes, how long the entry should be added into the PenaltyBox - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.39.1/edge-rate-limiter/PenaltyBox/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.has Check if the given entry is contained in in the PenaltyBox instance. ## Syntax ```js has(entry) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up ### Return value Returns `true` if the entry is contained in the PenaltyBox instance, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.1/edge-rate-limiter/RateCounter/RateCounter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `RateCounter()` The **`RateCounter` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for counting and rate calculations. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new RateCounter(name) ``` > **Note:** `RateCounter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a RateCounter with the given name ### Return value A new `RateCounter` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.1/edge-rate-limiter/RateCounter/prototype/increment.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.increment Increment the given `entry` in the RateCounter instance with the given `delta` value. ## Syntax ```js increment(entry, delta) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `delta` _: number_ - The amount to increment the entry by ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive, finite number. ================================================ FILE: documentation/versioned_docs/version-3.39.1/edge-rate-limiter/RateCounter/prototype/lookupCount.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupCount Look up the current rate for the given `entry` and the given `duration`. ## Syntax ```js lookupCount(entry, duration) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `duration` _: number_ - The duration to lookup alongside the entry, has to be either, 10, 20, 30, 40, 50, or 60 seconds. ### Return value Returns a number which is the count for the given `entry` and `duration` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `duration` value is not either, 10, 20, 30, 40, 50 or 60. ================================================ FILE: documentation/versioned_docs/version-3.39.1/edge-rate-limiter/RateCounter/prototype/lookupRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupRate Look up the current rate for the given `entry` and the given `window`. ## Syntax ```js lookupRate(entry, window) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `window` _: number_ - The window to look up alongside the entry, has to be either 1 second, 10 seconds, or 60 seconds ### Return value Returns a number which is the rate for the given `entry` and `window` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `window` value is not either, 1, 10, or 60. ================================================ FILE: documentation/versioned_docs/version-3.39.1/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabledOrConfig` _: boolean_ - Whether or not to allow Dynamic Backends or - `enabledOrConfig` _: object_ - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to https://www.fastly.com/ and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/experimental/mapAndLogError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapAndLogError The **`mapAndLogError()`** function calls `mapError` on an `Error` object and sends the output to standard error. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapAndLogError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value `undefined`. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { mapAndLogError(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | mapAndLogError(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/experimental/mapError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapError The **`mapError()`** function extracts information from an `Error` object as a human-readable array of strings. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value Returns an array of `string`s. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { console.error(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | console.error(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/experimental/sdkVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sdkVersion The read-only **`sdkVersion`** property is a string whose indicates what JavaScript SDK version is being used. ## Value A string value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object`, or `null` if no geolocation data was found. The object contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Blob/Blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob() The **`Blob()`** constructor creates a `Blob` object, which represents a file-like object of immutable, raw data. ## Syntax ```js new Blob() new Blob(array) new Blob(array, options) ``` > **Note:** `Blob()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `array` _**optional**_ - : An array of values to include in the `Blob`. These can be [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx), [`Blob`](../../globals/Blob/Blob.mdx), or strings. If any of these elements is a [`Blob`](../../globals/Blob/Blob.mdx), its content (and not the object itself) is copied into the Blob being constructed. - `options` _**optional**_ - : An object containing optional attributes for the `Blob`. - `type` - : A string indicating the MIME type of the data. The default value is the empty string `""`. - `endings` - : A string indicating how to handle line endings in the data. This can be either `"transparent"` (default) to keep line endings unchanged, or `"native"` to convert line endings to the platform's native line endings (e.g., `\r\n` on Windows). ### Return value A new `Blob` object containing the specified data. ## Description `Blob` objects represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting its functionality and expanding it to support files on the user's system. To construct a `Blob` from other non-blob objects and data, use the `Blob()` constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](../../globals/Blob/prototype/slice.mdx) method. The `type` property of a `Blob` object will match the MIME type specified in the constructor's `options` parameter, defaulting to an empty string if not specified. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Blob/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.arrayBuffer() The **`arrayBuffer()`** method of the `Blob` interface returns a `Promise` that resolves with an `ArrayBuffer` containing the entire contents of the `Blob` as binary data. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A `Promise` that resolves with an `ArrayBuffer` containing the blob's data. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Blob/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.size The **`size`** read-only property of the `Blob` interface returns the size of the `Blob` in bytes. ## Value A number representing the size of the `Blob` in bytes. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Blob/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.slice() The **`slice()`** method of the `Blob` interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. ## Syntax ```js slice() slice(start) slice(start, end) slice(start, end, contentType) ``` ### Parameters - `start` _**optional**_ - : The 0-based index of the first byte to include in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is 0. - `end` _**optional**_ - : The 0-based index of the first byte that will not be included in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is `size`. - `contentType` _**optional**_ - : A string indicating the content type to assign to the new `Blob`. The default value is an empty string. ### Return value A new `Blob` object containing the specified subset of data. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Blob/prototype/stream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.stream() The **`stream()`** method of the `Blob` interface returns a `ReadableStream` that can be used to read the contents of the `Blob`. ## Syntax ```js stream() ``` ### Parameters None. ### Return value A `ReadableStream` that provides the data contained within the `Blob`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Blob/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.text() The **`text()`** method of the `Blob` interface returns a `Promise` that resolves with a string containing the contents of the blob, interpreted as UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a string containing the blob's data as a text string. The data is always interpreted as UTF-8. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Blob/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.type The **`type`** read-only property of the `Blob` interface returns the MIME type of the `Blob`. ## Value A string indicating the MIME type of the `Blob`. If the type cannot be determined, this returns an empty string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/EcKeyImportParams/EcKeyImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcKeyImportParams The **`EcKeyImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as ECDSA. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/EcdsaParams/EcdsaParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcdsaParams The **`EcdsaParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `hash` - : A string. An identifier for the digest algorithm to use. This should be one of the following: - `SHA-256`: selects the SHA-256 algorithm. - `SHA-384`: selects the SHA-384 algorithm. - `SHA-512`: selects the SHA-512 algorithm. > **Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. While these fields are always defined on Compute, they may be *null* when not available in testing environments such as Viceroy. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : Either `null`, or a [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. - `FetchEvent.client.tlsJA3MD5` _**readonly**_ - : Either `null` or a string representation of the JA3 hash of the TLS ClientHello message. - `FetchEvent.client.tlsCipherOpensslName` _**readonly**_ - : Either `null` or a string representation of the cipher suite used to secure the client TLS connection. - `FetchEvent.client.tlsProtocol` _**readonly**_ - : Either `null` or a string representation of the TLS protocol version used to secure the client TLS connection. - `FetchEvent.client.tlsClientCertificate` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw client certificate in the mutual TLS handshake message. It is in PEM format. Returns an empty ArrayBuffer if this is not mTLS or available. - `FetchEvent.client.tlsClientHello` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw bytes sent by the client in the TLS ClientHello message. - `FetchEvent.client.tlsJA4` _**readonly**_ - : Either `null` or a string representation of the JA4 fingerprint of the TLS ClientHello message. - `FetchEvent.client.h2Fingerprint` _**readonly**_ - : Either `null` or a string representation of the HTTP/2 fingerprint for HTTP/2 connections. Returns `null` for HTTP/1.1 connections. - `FetchEvent.client.ohFingerprint` _**readonly**_ - : Either `null` or a string representation of the Original Header fingerprint based on the order and presence of request headers. - `FetchEvent.server` _**readonly**_ - : Information about the server receiving the request for the Fastly Compute service. - `FetchEvent.server.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the server which received the request. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.sendEarlyHints()`](./prototype/sendEarlyHints.mdx) - : Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FetchEvent/prototype/sendEarlyHints.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.sendEarlyHints() The **`sendEarlyHints()`** method allows you to send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response back to the client which made the incoming request to your application. ## Syntax ```js sendEarlyHints(headers) ``` ### Parameters - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../Headers/Headers.mdx) object or object literal of [`String`](../../String/String.mdx) key/value pairs. ### Return value Always returns `undefined`. ### Examples ```js event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'] ]); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/FormData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData() The **`FormData()`** constructor creates a new `FormData` object. ## Syntax ```js new FormData() new FormData(form) ``` > **Note:** `FormData()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `form` _**optional**_ - : An HTML `` element — when specified, the `FormData` object will be populated with the form's current key/value pairs using the name property of each element for the keys and their submitted value for the values. File input elements are handled specially: their values are taken from the files selected by the user in the upload control. ### Return value A new `FormData` object, pre-populated with form data if the optional `form` parameter was provided. ## Description The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using methods such as `fetch()`. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also append additional data to the `FormData` object after it's created using its various methods. A `FormData` object can be used in a number of ways with other APIs: 1. It can be sent with the `fetch()` API 2. It works seamlessly with the `Request` and `Response` objects - it can be used directly as the body of a `Request` object 3. It can be obtained from a `Response` object using the `formData()` method 4. It can be passed directly to the `URLSearchParams` constructor The transmitted data is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to `"multipart/form-data"`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.append() The **`append()`** method of the `FormData` interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. ## Syntax ```js append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.delete() The **`delete()`** method of the `FormData` interface removes all key/value pairs with the given name from the `FormData` object. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.entries() The **`entries()`** method of the `FormData` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator yields a new array for each key/value pair, with the first element being the key and the second element being the value. ## Syntax ```js entries() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.forEach() The **`forEach()`** method of the `FormData` interface executes the provided callback function once for each key/value pair in the `FormData` object. ## Syntax ```js forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each entry in the object. The function will be passed the following arguments: - `value` - : The value of the current entry. - `key` - : The key of the current entry. - `formData` - : The `FormData` object being traversed. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.get() The **`get()`** method of the `FormData` interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the [`getAll()`](../../../globals/FormData/prototype/getAll.mdx) method instead. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value A `FormDataEntryValue` containing the value. If the key does not exist, it returns `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/prototype/getAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.getAll() The **`getAll()`** method of the `FormData` interface returns all the values associated with a given key from within a `FormData` object. ## Syntax ```js getAll(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value An array of `FormDataEntryValue` items containing all values with the given key. If the key doesn't exist, an empty array is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.has() The **`has()`** method of the `FormData` interface returns a boolean indicating whether a `FormData` object contains a key/value pair with the given name. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the key you want to test for existence. ### Return value `true` if a key/value pair with the specified name exists; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.keys() The **`keys()`** method of the `FormData` interface returns an iterator allowing iteration through all keys contained in this object. The iterator yields the key for each value. ## Syntax ```js keys() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.set() The **`set()`** method of the `FormData` interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and [`append()`](../../../globals/FormData/prototype/append.mdx) is that if the specified key already exists, `set()` overwrites all existing values with the new one, whereas `append()` appends the new value onto the end of the existing values. ## Syntax ```js set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/FormData/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.values() The **`values()`** method of the `FormData` interface returns an iterator allowing iteration through all values contained in this object. The iterator yields the value for each key/value pair. ## Syntax ```js values() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name is not the name of an HTTP header, this method throws a `TypeError`. The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/prototype/getSetCookie.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.getSetCookie() The **`getSetCookie()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns an array of all the values of the `Set-Cookie` headers, returning an empty list if none are present. ## Syntax ```js getSetCookie() ``` ### Return value `String[]` representing the list of `Set-Cookie` headers. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2 or greater than π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex where x is a number very close to 0, you should get an answer very close to 1 + x, because limx0ex1x=1. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, a `ReadableStream` object, a [`Blob`](../../globals/Blob/Blob.mdx) object, or a [`FormData`](../../globals/FormData/FormData.mdx) object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_, see [`CacheOverride`](../../fastly:cache-override/CacheOverride/CacheOverride.mdx). - `cacheKey` _**Fastly-specific**_ - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.blob() The **`blob()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/clone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.clone() The **`clone()`** method of the `Request` interface creates a copy of the current `Request` object. Like the underlying `ReadableStream.tee`` api, the `body` of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Beware when you construct a `Request` from a stream and then `clone` it. `clone()` throws a `TypeError` if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) If you intend to modify the request, you may prefer the `Request` constructor. ## Syntax ```js clone() ``` ### Parameters None. ### Return value A `Request` object, which is an exact copy of the `Request` that `clone()` was called on. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.formData() The **`formData()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. - `SyntaxError` - : Thrown if the request's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Request` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Request instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - [`Blob`](../../globals/Blob/Blob.mdx) - [`FormData`](../../globals/FormData/FormData.mdx) - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.blob() The **`blob()`** method of the [`Response`](../Response.mdx) interface takes a [`Response`](../Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.formData() The **`formData()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. - `SyntaxError` - : Thrown if the response's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/ip.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ip The **`ip`** getter of the `Response` interface returns the IP address associated with the request, as either an IPv6 or IPv4 string. In the case where no IP address is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with an IP, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.port The **`port`** getter of the `Response` interface returns the port associated with the request, as a number. In the case where no port is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with a port, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Response` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Response instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - For ECDSA: Pass an [`EcKeyImportParams`](../../EcKeyImportParams/EcKeyImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](https://en.wikipedia.org/wiki/HZ_(character_encoding)). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Explicit Backends Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service. This `backend` option is then a special Fastly-specific fetch option that is provided to the `fetch()` call: ```js fetch('https://origin.com/path', { backend: 'origin' }); ``` Backends are configured using the Fastly service backend configuration, see the [Backend documentation](https://developer.fastly.com/reference/api/services/backend/) for more information. ## Dynamic Backends Dynamic backends are a compute feature that allow services to define backends for themselves. If the `backend` option is not provided when making `fetch()` requests, a backend will be automatically created by extracting the protocol, host, and port from the provided URL. In addition, custom backend configuration options can then also be provided through the [`Backend()`](../fastly:backend/Backend/Backend.mdx) constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ - `imageOptimizerOptions` _**Fastly-specific**_, see [`imageOptimizerOptions`](../fastly:image-optimizer/imageOptimizerOptions.mdx). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-3.39.1/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/after.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # after The `after` method inserts content after the closing tag of the element. ## Syntax ```js element.after(content); element.after(content, options); ``` ### Parameters - `content` _: string_ - The content to insert after the element's closing tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.after("World"); // Result:
Hello
World ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # append The `append` method inserts content at the end of the element's content. ## Syntax ```js element.append(content); element.append(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the end of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.append(", World"); // Result:
Hello, World
``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/before.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # before The `before` method inserts content before the opening tag of the element. ## Syntax ```js element.before(content); element.before(content, options); ``` ### Parameters - `content` _: string_ - The content to insert before the element's opening tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.before("Well"); // Result: Well
Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/hasAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # hasAttribute The `hasAttribute` method returns a `boolean` value indicating whether the specified attribute is present on the element. ## Syntax ```js element.hasAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to check for. ### Return value A boolean value indicating whether the attribute is present. ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/prepend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # prepend The `prepend` method inserts content at the beginning of the element's content. ## Syntax ```js element.prepend(content); element.prepend(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the beginning of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.prepend("Well, "); // Result:
Well, Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/removeAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # removeAttribute The `removeAttribute` method removes the specified attribute from the element. ## Syntax ```js element.removeAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to remove. ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/replaceChildren.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceChildren The `replaceChildren` method replaces the element's children with new content. ## Syntax ```js element.replaceChildren(content); element.replaceChildren(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element's children with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceChildren("Greetings!"); // Result:
Greetings!
``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/replaceWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceWith The `replaceWith` method replaces the element with new content. ## Syntax ```js element.replaceWith(content); element.replaceWith(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceWith("

Greetings!

"); // Result:

Greetings!

``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/selector.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # selector The `selector` read-only property is a `string` representing the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) that matches the element. ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/setAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setAttribute The `setAttribute` method sets the value of the specified attribute on the element. If the value already exists, it will be updated; otherwise, a new attribute with the specified name and value will be added to the element. ## Syntax ```js element.setAttribute(attributeName, value); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to set. - `value` _: string_ - The value to assign to the attribute. ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/Element/prototype/tag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # tag The `tag` read-only property is a `string` representing the tag name of the element. ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/HTMLRewritingStream/HTMLRewritingStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `HTMLRewritingStream()` The **`HTMLRewritingStream`** lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback. This callback can manipulate the attributes of the element, and add or remove content from the immediate context. ## Syntax ```js new HTMLRewritingStream() ``` ### Return value A new `HTMLRewritingStream` object. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/html-rewriter/HTMLRewritingStream/prototype/onElement.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # onElement ▸ **onElement**`(selector: string, handler: (element: Element) => void): this` Registers an element handler with the [`HTMLRewritingStream`] that will be called for each [`Element`] that matches the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) `selector`. Elements added by handlers will not be processed by other handlers. ## Syntax ```js .onElement(selector, handler) ``` ### Parameters - `selector` _: string_ - A CSS selector that determines the elements for which `handler` will be called - The following types of CSS selector are supported: Currently the rewriter supports the following CSS selectors: | Pattern | Description | |----------------------|----------------------------------------------------------------------------| | `*` | Any element | | `E` | All elements of type `E` | | `E F` | `F` elements inside `E` elements | | `E > F` | `F` elements directly inside `E` elements | | `E:nth-child(n)` | The n-th child of type `E` | | `E:first-child` | First child of type `E` | | `E:nth-of-type(n)` | The n-th sibling of type `E` | | `E:first-of-type` | First sibling of type `E` | | `E:not(s)` | Type `E` elements not matching selector `s` | | `E.myclass` | Type `E` elements with class `"myclass"` | | `E#myid` | Type `E` elements with ID `"myid"` | | `E[attr]` | Type `E` elements with attribute `attr` | | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | | `E[attr="val" i]` | Type `E` elements where `attr` is `"val"`, case-insensitive | | `E[attr="val" s]` | Type `E` elements where `attr` is `"val"`, case-sensitive | | `E[attr~="val"]` | Type `E` elements where `attr` contains `"val"` in a space-separated list | | `E[attr`|`;="val"]`| Type `E` elements where `attr` is hyphen-separated and starts with `"val"` | | `E[attr^="val"]` | Type `E` elements where `attr` starts with `"val"` | | `E[attr$="val"]` | Type `E` elements where `attr` ends with `"val"` | | `E[attr*="val"]` | Type `E` elements where `attr` contains `"val"` | - `handler` _: (element: Element) => void_ - A callback function that will be called once for each element that matches `selector` ### Return value The `HTMLRewritingStream`, so multiple calls to `onElement` can be chained. ### Exceptions - `Error` - If the provided `selector` is not a valid CSS selector. - If the provided `handler` is not a function. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/Auto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Auto` Enumerator options for [`imageOptimizerOptions.auto`](./imageOptimizerOptions.mdx). ## Constants - `AVIF` (`"avif"`) If the browser's Accept header indicates compatibility, deliver an AVIF image. - `WEBP` (`"webp"`) If the browser's Accept header indicates compatibility, deliver a WebP image. ## Examples ```js import { Auto, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, auto: Auto.AVIF }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/BWAlgorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `BWAlgorithm` Enumerator options for [`imageOptimizerOptions.bw`](./imageOptimizerOptions.mdx). ## Constants - `Threshold` (`"threshold"`) Uses a luminance threshold to convert the image to black and white. - `Atkinson` (`"atkinson"`) Uses [Atkinson dithering](https://en.wikipedia.org/wiki/Atkinson_dithering) to convert the image to black and white. ## Examples ```js import { Region, BWAlgorithm } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, bw: BWAlgorithm.Threshold }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/CropMode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CropMode` Enumerator options for [`imageOptimizerOptions.crop.mode`](./imageOptimizerOptions.mdx) and `imageOptimizerOptions.precrop.mode`. ## Constants - `Smart` (`"smart"`) Enables content-aware algorithms to attempt to crop the image to the desired aspect ratio while intelligently focusing on the most important visual content, including the detection of faces. - `Safe` (`"safe"`) Allow cropping out-of-bounds regions. ## Examples ```js import { CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Smart, } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/Disable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Disable` Enumerator options for [`imageOptimizerOptions.disable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Prevent images being resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Disable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, disable: Disable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/Enable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Enable` Enumerator options for [`imageOptimizerOptions.enable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Allow images to be resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Enable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, enable: Enable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/Fit.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Fit` Enumerator options for [`imageOptimizerOptions.fit`](./imageOptimizerOptions.mdx). ## Constants - `Bounds` (`"bounds"`) Resize the image to fit entirely within the specified region, making one dimension smaller if needed. - `Cover` (`"cover"`) Resize the image to entirely cover the specified region, making one dimension larger if needed. - `Crop` (`"crop"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Fit, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 150, height; 150, fit: Fit.Bounds }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/Format.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Format` Enumerator options for [`imageOptimizerOptions.format`](./imageOptimizerOptions.mdx). ## Constants - `Auto` (`"auto"`) Automatically use the best format based on browser support and image/transform characteristics - `AVIF` (`"avif"`) AVIF - `BJPG` (`"bjpg"`) Baseline JPEG - `GIF` (`"gif"`) Graphics Interchange Format - `JPG` (`"jpg"`) JPEG - `JXL` (`"jxl"`) JPEGXL - `MP4` (`"mp4"`) MP4 (H.264) - `PJPG` (`"pjpg"`) Progressive JPEG - `PJXL` (`"pjxl"`) Progressive JPEGXL - `PNG` (`"png"`) Portable Network Graphics - `PNG8` (`"png8"`) Portable Network Graphics palette image with 256 colors and 8-bit transparency - `SVG` (`"svg"`) Scalable Vector Graphics - `WEBP` (`"webp"`) WebP - `WEBPLL` (`"webpll"`) WebP (Lossless) - `WEBPLY` (`"webply"`) WebP (Lossy) ## Examples ```js import { Format, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/Metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Metadata` Enumerator options for [`imageOptimizerOptions.metadata`](./imageOptimizerOptions.mdx). ## Constants - `Copyright` (`"copyright"`) Preserve [copyright notice](https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#copyright-notice), creator, credit line, licensor, and web statement of rights fields. - `C2PA` (`"c2pa"`) Preserve the [C2PA manifest](https://c2pa.org/) and add any transformations performed by Fastly Image Optimizer. - `CopyRightAndC2PA` (`"copyright,c2pa"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Metadata, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, metadata: Metadata.Copyright }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/Optimize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Optimize` Enumerator options for [`imageOptimizerOptions.optimize`](./imageOptimizerOptions.mdx). ## Constants - `Low` (`"low"`) Output image quality will be similar to the input image quality. - `Medium` (`"medium"`) More optimization is allowed. We attempt to preserve the visual quality of the input image. - `High` (`"high"`) Minor visual artifacts may be visible. This produces the smallest file. ## Examples ```js import { Optimize, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, optimize: Optimize.High }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/Orient.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Orient` Enumerator options for [`imageOptimizerOptions.orient`](./imageOptimizerOptions.mdx). ## Constants - `Default` (`"1"`) - `FlipHorizontal` (`"2"`) - `FlipHorizontalAndVertical` (`"3"`) - `FlipVertical` (`"4"`) - `FlipHorizontalOrientLeft` (`"5"`) - `OrientRight` (`"6"`) - `FlipHorizontalOrientRight` (`"7"`) - `OrientLeft` (`"8"`) ## Examples ```js import { Orient, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, orient: Orient.FlipHorizontal }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/Profile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Profile` Enumerator options for [`imageOptimizerOptions.profile`](./imageOptimizerOptions.mdx). ## Constants - `Baseline` (`"baseline"`) The profile recommended for video conferencing and mobile applications. (Default) - `Main` (`"main"`) The profile recommended for standard-definition broadcasts. - `High` (`"high"`) The profile recommended for high-definition broadcasts. ## Examples ```js import { Profile, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, profile: Profile.Main }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/Region.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Region` Enumerator options for [`imageOptimizerOptions.region`](./imageOptimizerOptions.mdx). ## Constants - `UsEast` (`"us_east"`) - `UsCentral` (`"us_central"`) - `UsWest` (`"us_west"`) - `EuCentral` (`"eu_central"`) - `EuWest` (`"eu_west"`) - `Asia` (`"asia"`) - `Australia` (`"australia"`) ## Examples ```js import { Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/ResizeFilter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ResizeFilter` Enumerator options for [`imageOptimizerOptions.resizeFilter`](./imageOptimizerOptions.mdx). ## Constants - `Nearest` (`"nearest"`) Uses the value of nearby translated pixel values. - `Bilinear` (`"bilinear"`) Uses an average of a 2x2 environment of pixels. - `Linear` (`"linear"`) Same as `Bilenear`. - `Bicubic` (`"bicubic"`) Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. - `Cubic` (`"cubic"`) Same as `Bicubic`. - `Lanczos2` (`"lanczos2"`) Uses the Lanczos filter to increase the ability to detect edges and linear features within an image and uses sinc resampling to provide the best possible reconstruction. - `Lanczos3` (`"lanczos3"`) Lanczos3 uses a better approximation of the sinc resampling function. (Default) - `Lanczos` (`"lanczos"`) Same as `Lanczos3`. ## Examples ```js import { ResizeFilter, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, resizeFilter: ResizeFilter.Linear }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/image-optimizer/imageOptimizerOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `imageOptimizerOptions` Options specified in the [`Request`](../globals/Request/Request.mdx) constructor for running the [Fastly Image Optimizer](https://docs.fastly.com/products/image-optimizer). More detailed documentation on all Image Optimizer options is available in the [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/). ## Parameters All parameters other than `region` are optional. - `region`: _[`Region`](./Region.mdx)_ Where image optimizations should occur. - `auto`: _[`Auto`](./Auto.mdx)_ Enable optimization features automatically. - `bgColor`: _[`Color`](#color)_ Set the background color of an image. - `blur`: _`number` (0.5-1000) or [`Percentage`](#percentage)_ Set the blurriness of the output image. - `brightness`: _`number` (-100-100)_ Set the brightness of the output image. - `bw`: _[`BWAlgorithm`](./BWAlgorithm.mdx)_ Convert an image to black and white. - `canvas`: _`Object`_ Increase the size of the canvas around an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `contrast`: _`number` (-100-100)_ Set the contrast of the output image. - `crop`: _`Object`_ Remove pixels from an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `mode` (optional): _[`CropMode`](./CropMode.mdx)_ - `disable`: _[`Disable`](./Disable.mdx)_ Disable functionality that is enabled by default. - `dpr`: `number` Ratio between physical pixels and logical pixels. - `enable`: _[`Enable`](./Enable.mdx)_ Enable functionality that is disabled by default. - `fit`: _[`Fit`](./Fit.mdx)_ Set how the image will fit within the size bounds provided. - `format`: _[`Format`](./Format.mdx)_ Specify the output format to convert the image to. - `frame`: _`number` (must have the value 1)_ Extract the first frame from an animated image sequence. - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the height of the image. - `level`: _`String` containing one of the [allowed values](https://www.fastly.com/documentation/reference/io/level/#allowed-values)_ Specify the level constraints when converting to video. - `metadata`: _[`Metadata`](./Metadata.mdx)_ Control which metadata fields are preserved during transformation. - `optimize`: _[`Optimize`](./Optimize.mdx)_ Automatically apply optimal quality compression. - `orient`: _[`Orient`](./Orient.mdx)_ Change the cardinal orientation of the image. - `pad`: _[`Sides`](#sides)_ Add pixels to the edge of an image. - `precrop`: _`Object`_ Remove pixels from an image before any other transformations occur. - `size`: _[`Size`](#size)_ - `position`: _[`Position`](#position)_ - `mode`: _[`CropMode`](./CropMode.mdx)_ - `profile`: _[`Profile`](./Profile.mdx)_ Specify the profile class of application when converting to video. - `quality`: _`integer` (1-100)_ Optimize the image to the given compression level for lossy file formatted images. - `resizeFilter`: _[`ResizeFilter`](./ResizeFilter.mdx)_ Specify the resize filter used when resizing images. - `saturation`: _`number` (-100-100)_ Set the saturation of the output image. - `sharpen`: _`Object`_ Set the sharpness of the output image. - `amount`: _`number` (0-10)_ - `radius`: _`number` (0.5-1000)_ - `threshold`: _`integer` (0-255)_ - `trim`: _[`Sides`](#sides)_ Remove pixels from the edge of an image. - `viewbox`: _`number` (must have the value 1)_ Remove explicit width and height properties in SVG output. - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the width of the image. ## Types ### Color Either: - a 3 or 6 character hexadecimal string - an `Object` containing: - `r`: _`integer` (0-255)_ Red component - `g`: _`integer` (0-255)_ Green component - `b`: _`integer` (0-255)_ Blue component - `a` (optional): _`number` (0.0-1.0)_ Alpha component ### Percentage A `String` containing a number suffixed with a percent sign (%). ### Position An `Object` containing: - Exactly one of: - `x`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetX`: _`number` (interpreted as a percentage)_ - Exactly one of: - `y`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetY`: _`number` (interpreted as a percentage)_ ### Sides An `Object` containing `top`, `bottom`, `left`, and `right`, all of which are either an `integer` or [`Percentage`](#percentage). ### Size An `Object` containing either: - `absolute`: _`Object`_ - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `ratio`: _`Object`_ - `width`: _`number`_ - `height`: _`number`_ ## Examples ```js import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG, bgColor: { 'r': 100, 'g': 255, 'b': 9, 'a': 0.5 }, blur: '1%', brightness: -20, contrast: -20, height: 600, level: '4.0', orient: Orient.FlipVertical, saturation: 80, sharpen: { 'amount': 5, 'radius': 6, 'threshold': 44 }, canvas: { 'size': { 'absolute': { 'width': 400, 'height': 400 } } }, crop: { size: { absolute: { width: 200, height: 200 }, mode: CropMode.Safe } }, trim: { top: 10, left: 10, right: 10, bottom: 10 }, pad: { top: 30, left: 30, right: "1%", bottom: 30 } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a KV store instance using the resource link name. ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStore/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.delete Deletes the value associated with the key `key` in the KV store. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value Returns `undefined` ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - Does not exist ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then delete the entry. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') await files.delete('hello') const entry = await files.get('hello') if (entry) { return new Response(await entry.text()) } else { return new Response('no file named hello exists') } } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStore/prototype/list.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.list The **`list()`** can be used to list the keys of a store. ## Syntax ```js list(options?) ``` ### Parameters - `options` _: object_ _**optional**_ - List options supporting properties: - `cursor` _: string_ _**optional**_ - The cursor used to pick up from a previous iteration. - `limit` _: number_ _**optional**_ - The maximum number of keys to return. - `prefix` _: string_ _**optional**_ - List only those keys that start with the given string prefix. - `noSync` _: boolean_ _**optional**_ - Do not sync the key list first, instead provide a possibly out-of-date listing. May be faster but inconsistent. ### Return value Returns a `Promise` which resolves with `{ list: string[], cursor: string | undefined }`. ## Example In this example we list the keys of a KV Store named `'files'`, iterating 10 at a time, counting the total; ```js /// import { KVStore } from 'fastly:kv-store'; async function app(event) { const files = new KVStore('files'); let cursor, list, total = 0; do { ({ cursor, list } = await files.list({ limit: 10, cursor })); total += list?.length; } while (list); return new Response(`Iterated ${total} entries`); } addEventListener('fetch', (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value, options?) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. - `options` _: object_ _**optional**_ - An insert options parameter, supporting: - `metadata` _: ArrayBuffer | TypedArray | DataView_ _**optional**_ - Binary metadata associated with the entry, may be up to 1000 bytes. - `ttl` _: number_ _**optional**_ - TTL for the entry - `mode` _: 'overwrite' | 'add' | 'append' | 'prepend'_ _**optional**_ - Insert mode, defaults to 'overwrite' - `gen` _: number_ _**optional**_ - 'generation' header specific to the version of an entry key ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - `TypeError` - If the provided `gen`: - Is not an number ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStoreEntry/prototype/metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadata() The `metadata()` method of the `KVStoreEntry` interface provides the binary metadata associated with the `KVStoreEntry`. The metadata binary may be up to 1000 bytes, and is returned as a `Uint8Array` TypedArray buffer, if metadata is set, or null otherwise. ## Syntax ```js metadata() ``` ### Parameters None. ### Return value A `Promise` that resolves to a `Uint8Array` buffer object. ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStoreEntry/prototype/metadataText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadataText() The `metadataText()` method of the `KVStoreEntry` interface provides a String interpretation of binary metadata associated with the `KVStoreEntry`. If the binary data is not a valid string, an encoding error will be thrown. ## Syntax ```js metadataText() ``` ### Parameters None. ### Return value A `Promise` that resolves to a String. ================================================ FILE: documentation/versioned_docs/version-3.39.1/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; const logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; let logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/logger/configureConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # configureConsole The **`configureConsole()`** function allows configuring the behaviour of the `console` global JS logger. ## Syntax ```js configureConsole(loggingOptions) ``` ### Parameters - `loggingOptions` _: object_ - - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ## Examples In this example, we disable prefixing for `console.log` and use `stderr` output for `console.error`: ```js import { configureConsole } from "fastly:logger"; configureConsole({ prefixing: false, stderr: true }); async function handleRequest(event) { console.log(JSON.stringify(event.request.headers)); const url = new URL(event.request.url); try { validate(url); } catch (e) { console.error(`Validation error: ${e}`); return new Response('Bad Request', { status: 400 }); } return new Response('OK'); } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v2 to v3` ## SimpleCache.delete renamed to SimpleCache.purge and requires purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using `SimpleCache.delete` to `SimpleCache.purge` with the same purging behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a Secret Store instance using the resource link name. ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/secret-store/SecretStore/fromBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fromBytes The **`fromBytes()`** function is used to create an in-memory secret from an array buffer. >**Note**: This API should be avoided when possible, by instead using [SecretStore.prototype.get](./prototype/get.mdx) to obtain secure secrets. ## Syntax ```js fromBytes(new Uint8Array([1, 2, 3])) ``` ### Parameters None. ### Return value Returns a `SecretStoreEntry`. ================================================ FILE: documentation/versioned_docs/version-3.39.1/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/secret-store/SecretStoreEntry/prototype/rawBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.rawBytes ▸ **rawBytes**(): `Uint8Array` Returns the raw byte contents of the SecretStoreEntry instance as a Uint8Array. ## Syntax ```js rawBytes() ``` ### Parameters None. ### Return value A Uint8Array ### Exceptions The `rawBytes()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ================================================ FILE: documentation/versioned_docs/version-3.39.1/security/inspect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # inspect The **`inspect()`** function inspects a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). ## Syntax ```js inspect(request, config); ``` ### Parameters - `request` _: Request_ - The Request to get a WAF determination for. - `config` _: object_ - `corp` _: string_ - Set a corp name for the configuration. - This parameter is currently required. - `workspace` _: string_ - Set a workspace name for the configuration. - This parameter is currently required. - `overrideClientIp` _: string_ - Specify an explicit client IP address to inspect. - By default, `inspect` will use the IP address that made the request to the running Compute service, but you may want to use a different IP when service chaining or if requests are proxied from outside of Fastly’s network. ### Return value Returns an `Object` with the `inspect` response, with the following fields: - `waf_response` _: number_ - Security status code. - `redirect_url` _: string | null_ - A redirect URL returned from Security. - `tags` _: string[]_ - Tags returned by Security. - `verdict` _: string_ - The outcome of inspecting a request with Security. It can be one of the following: - `"allow"` - Security indicated that this request is allowed. - `"block"` - Security indicated that this request should be blocked. - `"unauthorized"` - Security indicated that this service is not authorized to inspect a request. - Other verdicts may be returned but not currently documented. - `decision_ms` _: number_ - How long Security spent determining its verdict, in milliseconds. ## Examples ```js /// import { inspect } from "fastly:security"; async function app(event) { const res = inspect(event.request, { corp: "mycorp", workspace: "myws" }); switch (res.verdict) { case "allow": return await fetch(event.request); case "block": return new Response("Request Blocked", { status: 400 }); case "unauthorized": return new Response("Unauthorized", { status: 401 }); default: return new Response("idk", { status: 500 }); } } addEventListener("fetch", (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/shielding/Shield/Shield.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Shield()` Load information about the given shield. Returns an object representing the shield if it is active, or throws an exception if the string is malformed or the shield doesn’t exist. Shield names are defined on [this webpage](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations), in the “shield code” column. For example, the string “pdx-or-us” will look up our Portland, OR, USA shield site, while “paris-fr” will look up our Paris site. If you are using a major cloud provider for your primary origin site, consider looking at the “Recommended for” column, to find the Fastly POP most closely located to the given cloud provider. ## Syntax ```js new Shield(name) ``` > **Note:** `Shield()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Exceptions - `TypeError` - Thrown if no Shield exists with the provided name ## Examples In this example, we create a Shield instance for the Sydney, Australia shield POP. If the code is running on that shield POP, it fetches directly from origin. Otherwise, it routes the request through the shield using an encrypted connection. ```js /// import { Shield } from "fastly:shielding"; async function app(event) { const shield = new Shield('wsi-australia-au'); // If running on the shield POP, fetch from the origin directly if (shield.runningOn()) { return await fetch('https://http-me.fastly.com/anything', { backend: 'httpme' }); } // Otherwise, route the request through the shield using an encrypted connection return await fetch(event.request, { backend: shield.encryptedBackend() }); } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.1/shielding/Shield/prototype/encryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.encryptedBackend ▸ **encryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an encrypted connection to the POP. For reference, this is almost always the backend that you want to use. Only use [`Shield::unencryptedBackend`](./unencryptedBackend.mdx) in situations in which you are 100% sure that all the data you will send and receive over the backend is already encrypted. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.39.1/shielding/Shield/prototype/runningOn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.runningOn ▸ **runningOn**(): `boolean` Returns whether we are currently operating on the given shield. Technically, this may also return true in very isolated incidents in which Fastly is routing traffic from the target shield POP to the POP that this code is running on, but in these situations the results should be approximately identical. (For example, it may be the case that you are asking to shield to ‘pdx-or-us’. But, for load balancing, performance, or other reasons, Fastly is temporarily shifting shielding traffic from Portland to Seattle. In that case, this function may return true for hosts running on ‘bfi-wa-us’, our Seattle site, because effectively the shield has moved to that location. This should give you a slightly faster experience than the alternative, in which this function would return false, you would try to forward your traffic to the Portland site, and then that traffic would be caught and redirected back to Seattle.) ================================================ FILE: documentation/versioned_docs/version-3.39.1/shielding/Shield/prototype/unencryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.unencryptedBackend ▸ **unencryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an unencrypted connection to the POP. Generally speaking, we encourage users to use [`Shield::encryptedBackend`](./encryptedBackend.mdx) instead of this function. Data sent over this backend – the unencrypted version – will be sent over the open internet, with no protections. In most cases, this is not what you want. However, in some cases – such as when you want to ship large data blobs that you know are already encrypted — using these backends can prevent a double-encryption performance penalty. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.39.1/websocket/createWebsocketHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createWebsocketHandoff The **`createWebsocketHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Websocket, to the declared backend. ## Syntax ```js createWebsocketHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Websocket. - `backend` _: string_ - The name of the backend that Websocket should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Websocket. ```js import { createWebsocketHandoff } from "fastly:websocket"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createWebsocketHandoff(event.request, 'websocket_backend'); } else { return new Response('oopsie, make a request to /stream for some websocket goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/acl/Acl/open.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.open() Opens the ACL with the given name, returning a new `Acl` instance with the given name on success. ## Syntax ```js Acl.open(name) ``` ### Return value An `Acl` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.2/acl/Acl/prototype/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.prototype.lookup() The **`lookup(ipAddress)`** method returns the name associated with the `Acl` instance. ## Syntax ```js acl.lookup(ipAddress) ``` ### Parameters - `ipAddress` _: string_ - IPv4 or IPv6 address to lookup ### Return value An Object of the form `{ action: 'ALLOW' | 'BlOCK', prefix: string }`, where `prefix` is the IP address prefix that was matched in the ACL. ## Example ```js /// import { Acl } from 'fastly:acl'; addEventListener('fetch', async (evt) => { const myAcl = Acl.open('myacl'); const match = await myAcl.lookup(evt.client.address); evt.respondWith(new Response(match?.action === 'BLOCK' ? 'blocked' : 'allowed')); }); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. >**Note**: Dynamic backends are by default disabled at the Fastly service level. Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request dynamic backends on Fastly Services. To disable the usage of dynamic backends, see [enforceExplicitBackends](../enforceExplicitBackends.mdx). ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. - `grpc` _: boolean_ _**optional**_ - **_Experimental feature_** - When enabled, sets that this backend is to be used for gRPC traffic. - _Warning: When using this experimental feature, no guarantees are provided for behaviours for backends that do not provide gRPC traffic._ All optional generic options can have their defaults set via [`setDefaultDynamicBackendConfig()`](../setDefaultDynamicBackendConfig.mdx). This includes all configuration options above except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. ### Return value A new `Backend` object. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/exists.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.exists() The **`Backend.exists()`** method returns a boolean indicating if a Backend with the given name exists or not. ## Syntax ```js exists(name) ``` ### Return value A boolean indicating if a Backend with the given name exists or not. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/fromName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.fromName() Returns the `Backend` instance with the given name, if one exists. If one does not exist, an error is thrown. ## Syntax ```js fromName(name) ``` ### Return value A `Backend` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.health() :::info This method is deprecated, use [`Backend.prototype.health`](./prototype/health.mdx) instead. ::: The **`Backend.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js Backend.health(backend) ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/betweenBytesTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.betweenBytesTimeout The read-only **`betweenBytesTimeout`** property of a `Backend` instance is an integer number providing the between bytes timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/connectTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.connectTimeout The read-only **`connectTimeout`** property of a `Backend` instance is an integer number providing the connect timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/firstByteTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.firstByteTimeout The read-only **`firstByteTimeout`** property of a `Backend` instance is an integer number providing the first byte timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.health() The **`Backend.prototype.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js health() ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/hostOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.hostOverride The read-only **`hostOverride`** property of a `Backend` instance is the host header override string used when sending requests to this backend. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/httpKeepaliveTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.httpKeepaliveTime The read-only **`httpKeepaliveTime`** property of a `Backend` instance is the HTTP keepalive time for this backend in milliseconds, or 0 if no keepalive is set. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/isDynamic.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isDynamic The read-only **`isDynamic`** property of a `Backend` instance is a boolean indicating if the backend was dynamically created for this service. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/isSSL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isSSL The read-only **`isSSL`** property of a `Backend` instance is a boolean indicating if the backend is using an SSL connection. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # name The read-only **`name`** property of the backend returns the backend name string. ## Value A `string`. ## Description Provides the name of the backend. ## Examples ### Using name The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.port The read-only **`port`** property of a `Backend` instance is the port number of this backend. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/target.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.target The read-only **`target`** property of a `Backend` instance is the host string this backend is configured to use. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/tcpKeepalive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tcpKeepalive The read-only **`tcpKeepalive`** property of a `Backend` instance returns an object providing the TCP keepalive configuration, if any, otherwise returning `null` if TCP keepalive is not enabled. This object has the following properties: - `timeSecs` _: number or null._ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number or null._ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number or null._ - Number of probes to send to the backend before it is considered dead. ## Value A `Object` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/tlsMaxVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMaxVersion The read-only **`tlsMaxVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/tlsMinVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMinVersion The read-only **`tlsMinVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/toName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.toName() :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toName()`** method returns the name associated with the `Backend` instance. ## Syntax ```js toName() ``` ### Return value A string which contains the name of the Backend. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toString :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends :::info This method is deprecated, and dynamic backends are now always supported when enabled at the service level. See [`enforceExplicitBackends`](./enforceExplicitBackends.mdx) instead. ::: The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: By default, while dynamic backends are allowed in the SDK, they are by default disabled at the Fastly service level. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/enforceExplicitBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enforceExplicitBackends Call this function to enforce the security property of explicitly-defined backends, even when dynamic backends are enabled at the Fastly service level. By default, if dynamic backends are supported for the Fastly service, they will be automatically used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a potential security concern since third-party JavaScript code may send arbitrary requests, including sensitive/secret data, off to destinations that the JavaScript project was not intending. When calling this function, an optional default backend name can be provided. >**Note**: This is a separate option to the service-level dynamic backend support for Fastly services, which is by deault disabled for Fastly services. The **`enforceExplicitBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: Dynamic Backends are disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled or disabled on Fastly Services. ## Syntax ```js enforceExplicitBackends(defaultBackend?) ``` ### Parameters - `defaultBackend` _: string_ _**optional**_ - An optional default backend string name to use in `fetch()` requests. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/backend/setDefaultDynamicBackendConfig.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setDefaultDynamicBackendConfig() The **`setDefaultDynamicBackendConfig()`** allows setting backend configuration defaults that should apply to any newly created dynamic backends via the `new Backend()` constructor. ### Parameters - `defaultDynamicBackendConfig` - : An Object which contains the generic configuration options to apply to newly created Backends. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. ## Syntax ```js setDefaultDynamicBackendConfig(defaultConfig) ``` ### Return value None. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, with timeouts and TLS options provided from the default backend configuration options. import { allowDynamicBackends } from "fastly:experimental"; import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! // Timeouts and TLS configuration still get set from the default backend configuration above. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.age The **`age`** method of the `CacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.body The **`body`** method of the `CacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this `CacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.close The **`close`** method of the `CacheEntry` interface closes the connection to the cache for this `CacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.hits The **`hits`** method of the `CacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.length The **`length`** method of the `CacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.maxAge The **`maxAge`** method of the `CacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `CacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.state The **`state`** method of the `CacheEntry` interface returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.userMetadata The **`userMetadata`** method of the `CacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheState/found.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.found The **`found`** method of the `CacheState` interface returns `true` if a cached item was located. Even if an cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. ## Syntax ```js found() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item was located or not. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheState/mustInsertOrUpdate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.mustInsertOrUpdate The **`mustInsertOrUpdate`** method of the `CacheState` interface returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. ## Syntax ```js mustInsertOrUpdate() ``` ### Parameters None. ### Return value A `boolean` which represents whether a fresh cached item was found not. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheState/stale.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.stale The **`stale`** method of the `CacheState` interface returns `true` if the cached item is stale. A cached item is stale if its age is greater than its `maxAge` period. ## Syntax ```js stale() ``` ### Parameters None. ### Return value A `boolean` which represents whether the cached item is stale or not. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CacheState/usable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.usable The **`usable`** method of the `CacheState` interface returns `true` if the cached item is usable. A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. ## Syntax ```js usable() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item is usable or not. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CoreCache/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.insert Performs a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. ## Syntax ```js insert(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item’s contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CoreCache/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.lookup Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. ## Syntax ```js lookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns `CacheEntry` if a usable cached item was found, otherwise returns `null`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/CoreCache/transactionLookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.transactionLookup Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. Request Collapsing: If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, just one of the callers will be instructed to insert the item into the cache as part of the transaction. The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. Revalidation: Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. ## Syntax ```js transactionLookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns an instance of `TransactionCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, and return a message stating whether the entry was in the Fastly Cache or not. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); return new Response(page ? `${path} is in the cache` : `${path} is not in the cache`, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key`. If no entry is found (or has expired), the supplied `set` function is executed and its result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - The function to execute if and only if the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The maximum number of seconds to store the supplied entry in the cache. - `length` _: number_ __optional__ - The length of the value being stored within the cache. This is only used when the `value` is a `ReadableStream`. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/SimpleCache/purge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.purge purge the entry associated with the key `key` from the cache. ## Syntax ```js purge(key, options) ``` ### Parameters - `key` _: string_ - The key to purge from within the cache. - `options` _: object_ - `scope` _: string_ - : Where to purge the content from. - Possible values are: - "global" - This will remove the content from all of Fastly. - "pop" - This will remove the content from the POP that contains the currently executing instance. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `purge` querystring parameter, we purge the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('purge')) { SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.age The **`age`** method of the `TransactionCacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.body The **`body`** method of the `TransactionCacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `TransactionCacheEntry`. An error will be thrown if a stream is already active for this `TransactionCacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.cancel The **`cancel`** method of the `TransactionCacheEntry` interface cancels an obligation to provide an object to the cache. ## Syntax ```js cancel() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.close The **`close`** method of the `TransactionCacheEntry` interface closes the connection to the cache for this `TransactionCacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.hits The **`hits`** method of the `TransactionCacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insert Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. ## Syntax ```js insert(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/insertAndStreamBack.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insertAndStreamBack Perform a transaction cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. ## Syntax ```js insertAndStreamBack(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns an array where the first item is a `FastlyBody` instance and the second item is a `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.length The **`length`** method of the `TransactionCacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.maxAge The **`maxAge`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.state The **`state`** method of the `TransactionCacheEntry` interface returns a `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/update.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.update Perform an update of the cache item's metadata. ## Syntax ```js update(options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache/TransactionCacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.userMetadata The **`userMetadata`** method of the `TransactionCacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.2/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) new CacheOverride(init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. This options is also the default when providing an init object directly as the first argument. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. - `beforeSend` _:Function_ _**optional**_ - `(request: Request) => void | PromiseLike` - Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. - See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) in the Fastly cache interfaces documentation for details. - `afterSend` _: Function_ _**optional**_ - `(response: Response) => void | CacheOptions | PromiseLike` - Callback to be invoked after a response has been sent, but before it is stored into the cache. - Where `CacheOptions` contains: - `cache` _: boolean | 'uncacheable'_ _**optional**_ - Whether to cache this response. By default, leaving this field empty, responses will be cached based on their cache header information. - Setting this to true or false will override this default cache behaviour, setting in the cache or not setting in the cache, even if the default behaviour would have been otherwise. - Setting to 'uncacheable' the response will not only not be cached, but the cache will record that the originating request led to an uncacheable response, so that future cache lookups will result in immediately going to the backend, rather than attempting to coordinate concurrent requests to reduce backend traffic. - See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) for more details on the mechanism that `uncacheable` disables. - `bodyTransformFn` _: Function_ _**optional**_ - `(body: Uint8Array) => Uint8Array | PromiseLike` - Provide a function to be used for transforming the response body prior to caching. - Body transformations are performed by specifying a transform, rather than by directly working with the body during the onAfterSend callback function, because not every response contains a fresh body: 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because they do not retransmit the body. - For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will be applied to it. The original backend body is passed in to the transform function, and the function is expected to return the new body. - See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) in the Fastly cache interfaces documentation for details. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/compute/purgeSurrogateKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # purgeSurrogateKey The **`purgeSurrogateKey()`** function is used to purge the given surrogate key string from Fastly's cache. There are two purge modes: soft purge and hard purge, with hard purge as the default which clears all items from the cache immediately. When using a soft purge, stale entries are maintained in the cache, reducing orgin load, while also enabling stale revalidations. See the [Fastly Purge Documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) for more information on caching and purge operations. ## Syntax ```js purgeSurrogateKey(surrogateKey, soft?) ``` ### Parameters - `surrogateKey` _: string_ - The surrogate key string - `soft?` _: boolean_ - Enables a soft purge, retaining stale entries in the cache. Default is a hard purge. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/compute/vCpuTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # vCpuTime The **`vCpuTime()`** function provides the vCPU time used by the current request handler in milliseconds. ## Syntax ```js vCpuTime() ``` ### Parameters None. ### Return value `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Defines a config store instance using the resource link name. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have a resource link named "animals" (which is linked to a config store) and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.lookup() Look up the data associated with a particular User-Agent string. ## Syntax ```js lookup(userAgent) ``` ### Return value If there is data associated with the User-Agent, a `Device` instance is returned. Otherwise, `null` is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/brand.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.brand The read-only **`brand`** property of the `Device` interface is either a string stating the brand of the device, which can be different from the manufacturer of that device. If no brand is known, the value will be `null`. ## Value Either a string value if a brand is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/hardwareType.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.hardwareType The read-only **`hardwareType`** property of the `Device` interface is either a string stating the hardware type of the device, or `null` if the hardware type is not known. A string representation of the device's primary platform hardware. The most commonly used device types are also identified via boolean variables. Because a device may have multiple device types and this variable only has the primary type, we recommend using the boolean variables for logic and using this string representation for logging. ## Value Either a string value if a hardware type is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/isBot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isBot The read-only **`isBot`** property of the `Device` interface is either a boolean stating if the device is a bot, or `null` if the this is not known. ## Value Either a boolean stating if the device is a bot, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/isDesktop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isDesktop The read-only **`isDesktop`** property of the `Device` interface is either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ## Value Either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/isGameConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isGameConsole The read-only **`isGameConsole`** property of the `Device` interface is either a boolean stating if the device is a video game console, or `null` if the this is not known. ## Value Either a boolean stating if the device is a video game console, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/isMediaPlayer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMediaPlayer The read-only **`isMediaPlayer`** property of the `Device` interface is either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ## Value Either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/isMobile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMobile The read-only **`isMobile`** property of the `Device` interface is either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ## Value Either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/isSmartTV.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isSmartTV The read-only **`isSmartTV`** property of the `Device` interface is either a boolean stating if the device is a smart TV, or `null` if the this is not known. ## Value Either a boolean stating if the device is a smart TV, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/isTablet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTablet The read-only **`isTablet`** property of the `Device` interface is either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ## Value Either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/isTouchscreen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTouchscreen The read-only **`isTouchscreen`** property of the `Device` interface is either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ## Value Either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/model.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.model The read-only **`model`** property of the `Device` interface is either a string stating the model of the device, or `null` if the model is not known. ## Value Either a string value if a model is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.name The read-only **`name`** property of the `Device` interface is either a string stating the name of the device, or `null` if the name is not known. ## Value Either a string value if a name is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/device/Device/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toJSON The `toJSON()` method of the Device interface is a serializer; it returns a JSON representation of the Device object. To get a JSON string, you can use `JSON.stringify(device)` directly; it will call `toJSON()` automatically. ## Syntax ```js toJSON() ``` ### Return value A JSON object that is the serialization of the Device object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Dictionary()` :::info This Class is deprecated ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/edge-rate-limiter/EdgeRateLimiter/EdgeRateLimiter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `EdgeRateLimiter()` The **`EdgeRateLimiter` constructor** lets you open an epen a [ERL](https://docs.fastly.com/products/edge-rate-limiting) with the given ratecounter and penaltybox. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new EdgeRateLimiter(rateCounter, penaltyBox) ``` > **Note:** `EdgeRateLimiter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `rateCounter` _: RateCounter_ - The RateCounter instance to associate with this EdgeRateLimiter instance - `penaltyBox` _: PenaltyBox_ - The PenaltyBox instance which should be associated with this EdgeRateLimiter instance ### Return value A new `EdgeRateLimiter` object. ### Exceptions - `TypeError` - Thrown if the provided rateCounter value is not an instance of RateCounter - Thrown if the provided penaltyBox value is not an instance of PenaltyBox ================================================ FILE: documentation/versioned_docs/version-3.39.2/edge-rate-limiter/EdgeRateLimiter/prototype/checkRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EdgeRateLimiter.prototype.checkRate Increment an entry in the rate counter and check if the entry has exceeded some average number of requests per second (RPS) over the given window. If the entry is over the RPS limit for the window, add to the penaltybox for the given `timeToLive`. Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ## Syntax ```js checkRate(entry, delta, window, limit, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to increment and check - `delta` _: number_ - The amount to increment the `entry` by - `window` _: number_ - The time period to check across, has to be either 1 second, 10 seconds, or 60 seconds - `limit` _: number_ - The requests-per-second limit - `timeToLive` _: number_ - In minutes, how long the entry should be added into the penalty-box - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `true` if the entry has exceeded the average RPS for the window, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive finite number. - Thrown if the provided `window` value is not either, 1, 10, or 60. - Thrown if the provided `limit` value is not a positive finite number. - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.39.2/edge-rate-limiter/PenaltyBox/PenaltyBox.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `PenaltyBox()` The **`PenaltyBox` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for adding and checking if some entry is in the dataset. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new PenaltyBox(name) ``` > **Note:** `PenaltyBox()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a PenaltyBox with the given name ### Return value A new `PenaltyBox` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.2/edge-rate-limiter/PenaltyBox/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.add Add an `entry` into the PenaltyBox for the duration of the given `timeToLive`. ## Syntax ```js add(entry, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `timeToLive` _: number_ - In minutes, how long the entry should be added into the PenaltyBox - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.39.2/edge-rate-limiter/PenaltyBox/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.has Check if the given entry is contained in in the PenaltyBox instance. ## Syntax ```js has(entry) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up ### Return value Returns `true` if the entry is contained in the PenaltyBox instance, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.2/edge-rate-limiter/RateCounter/RateCounter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `RateCounter()` The **`RateCounter` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for counting and rate calculations. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new RateCounter(name) ``` > **Note:** `RateCounter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a RateCounter with the given name ### Return value A new `RateCounter` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.2/edge-rate-limiter/RateCounter/prototype/increment.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.increment Increment the given `entry` in the RateCounter instance with the given `delta` value. ## Syntax ```js increment(entry, delta) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `delta` _: number_ - The amount to increment the entry by ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive, finite number. ================================================ FILE: documentation/versioned_docs/version-3.39.2/edge-rate-limiter/RateCounter/prototype/lookupCount.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupCount Look up the current rate for the given `entry` and the given `duration`. ## Syntax ```js lookupCount(entry, duration) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `duration` _: number_ - The duration to lookup alongside the entry, has to be either, 10, 20, 30, 40, 50, or 60 seconds. ### Return value Returns a number which is the count for the given `entry` and `duration` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `duration` value is not either, 10, 20, 30, 40, 50 or 60. ================================================ FILE: documentation/versioned_docs/version-3.39.2/edge-rate-limiter/RateCounter/prototype/lookupRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupRate Look up the current rate for the given `entry` and the given `window`. ## Syntax ```js lookupRate(entry, window) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `window` _: number_ - The window to look up alongside the entry, has to be either 1 second, 10 seconds, or 60 seconds ### Return value Returns a number which is the rate for the given `entry` and `window` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `window` value is not either, 1, 10, or 60. ================================================ FILE: documentation/versioned_docs/version-3.39.2/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabledOrConfig` _: boolean_ - Whether or not to allow Dynamic Backends or - `enabledOrConfig` _: object_ - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to https://www.fastly.com/ and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/experimental/mapAndLogError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapAndLogError The **`mapAndLogError()`** function calls `mapError` on an `Error` object and sends the output to standard error. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapAndLogError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value `undefined`. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { mapAndLogError(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | mapAndLogError(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/experimental/mapError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapError The **`mapError()`** function extracts information from an `Error` object as a human-readable array of strings. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value Returns an array of `string`s. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { console.error(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | console.error(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/experimental/sdkVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sdkVersion The read-only **`sdkVersion`** property is a string whose indicates what JavaScript SDK version is being used. ## Value A string value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object`, or `null` if no geolocation data was found. The object contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Blob/Blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob() The **`Blob()`** constructor creates a `Blob` object, which represents a file-like object of immutable, raw data. ## Syntax ```js new Blob() new Blob(array) new Blob(array, options) ``` > **Note:** `Blob()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `array` _**optional**_ - : An array of values to include in the `Blob`. These can be [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx), [`Blob`](../../globals/Blob/Blob.mdx), or strings. If any of these elements is a [`Blob`](../../globals/Blob/Blob.mdx), its content (and not the object itself) is copied into the Blob being constructed. - `options` _**optional**_ - : An object containing optional attributes for the `Blob`. - `type` - : A string indicating the MIME type of the data. The default value is the empty string `""`. - `endings` - : A string indicating how to handle line endings in the data. This can be either `"transparent"` (default) to keep line endings unchanged, or `"native"` to convert line endings to the platform's native line endings (e.g., `\r\n` on Windows). ### Return value A new `Blob` object containing the specified data. ## Description `Blob` objects represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting its functionality and expanding it to support files on the user's system. To construct a `Blob` from other non-blob objects and data, use the `Blob()` constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](../../globals/Blob/prototype/slice.mdx) method. The `type` property of a `Blob` object will match the MIME type specified in the constructor's `options` parameter, defaulting to an empty string if not specified. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Blob/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.arrayBuffer() The **`arrayBuffer()`** method of the `Blob` interface returns a `Promise` that resolves with an `ArrayBuffer` containing the entire contents of the `Blob` as binary data. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A `Promise` that resolves with an `ArrayBuffer` containing the blob's data. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Blob/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.size The **`size`** read-only property of the `Blob` interface returns the size of the `Blob` in bytes. ## Value A number representing the size of the `Blob` in bytes. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Blob/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.slice() The **`slice()`** method of the `Blob` interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. ## Syntax ```js slice() slice(start) slice(start, end) slice(start, end, contentType) ``` ### Parameters - `start` _**optional**_ - : The 0-based index of the first byte to include in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is 0. - `end` _**optional**_ - : The 0-based index of the first byte that will not be included in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is `size`. - `contentType` _**optional**_ - : A string indicating the content type to assign to the new `Blob`. The default value is an empty string. ### Return value A new `Blob` object containing the specified subset of data. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Blob/prototype/stream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.stream() The **`stream()`** method of the `Blob` interface returns a `ReadableStream` that can be used to read the contents of the `Blob`. ## Syntax ```js stream() ``` ### Parameters None. ### Return value A `ReadableStream` that provides the data contained within the `Blob`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Blob/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.text() The **`text()`** method of the `Blob` interface returns a `Promise` that resolves with a string containing the contents of the blob, interpreted as UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a string containing the blob's data as a text string. The data is always interpreted as UTF-8. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Blob/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.type The **`type`** read-only property of the `Blob` interface returns the MIME type of the `Blob`. ## Value A string indicating the MIME type of the `Blob`. If the type cannot be determined, this returns an empty string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/EcKeyImportParams/EcKeyImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcKeyImportParams The **`EcKeyImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as ECDSA. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/EcdsaParams/EcdsaParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcdsaParams The **`EcdsaParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `hash` - : A string. An identifier for the digest algorithm to use. This should be one of the following: - `SHA-256`: selects the SHA-256 algorithm. - `SHA-384`: selects the SHA-384 algorithm. - `SHA-512`: selects the SHA-512 algorithm. > **Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. While these fields are always defined on Compute, they may be *null* when not available in testing environments such as Viceroy. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : Either `null`, or a [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. - `FetchEvent.client.tlsJA3MD5` _**readonly**_ - : Either `null` or a string representation of the JA3 hash of the TLS ClientHello message. - `FetchEvent.client.tlsCipherOpensslName` _**readonly**_ - : Either `null` or a string representation of the cipher suite used to secure the client TLS connection. - `FetchEvent.client.tlsProtocol` _**readonly**_ - : Either `null` or a string representation of the TLS protocol version used to secure the client TLS connection. - `FetchEvent.client.tlsClientCertificate` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw client certificate in the mutual TLS handshake message. It is in PEM format. Returns an empty ArrayBuffer if this is not mTLS or available. - `FetchEvent.client.tlsClientHello` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw bytes sent by the client in the TLS ClientHello message. - `FetchEvent.client.tlsJA4` _**readonly**_ - : Either `null` or a string representation of the JA4 fingerprint of the TLS ClientHello message. - `FetchEvent.client.h2Fingerprint` _**readonly**_ - : Either `null` or a string representation of the HTTP/2 fingerprint for HTTP/2 connections. Returns `null` for HTTP/1.1 connections. - `FetchEvent.client.ohFingerprint` _**readonly**_ - : Either `null` or a string representation of the Original Header fingerprint based on the order and presence of request headers. - `FetchEvent.server` _**readonly**_ - : Information about the server receiving the request for the Fastly Compute service. - `FetchEvent.server.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the server which received the request. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.sendEarlyHints()`](./prototype/sendEarlyHints.mdx) - : Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FetchEvent/prototype/sendEarlyHints.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.sendEarlyHints() The **`sendEarlyHints()`** method allows you to send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response back to the client which made the incoming request to your application. ## Syntax ```js sendEarlyHints(headers) ``` ### Parameters - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../Headers/Headers.mdx) object or object literal of [`String`](../../String/String.mdx) key/value pairs. ### Return value Always returns `undefined`. ### Examples ```js event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'] ]); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/FormData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData() The **`FormData()`** constructor creates a new `FormData` object. ## Syntax ```js new FormData() new FormData(form) ``` > **Note:** `FormData()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `form` _**optional**_ - : An HTML `` element — when specified, the `FormData` object will be populated with the form's current key/value pairs using the name property of each element for the keys and their submitted value for the values. File input elements are handled specially: their values are taken from the files selected by the user in the upload control. ### Return value A new `FormData` object, pre-populated with form data if the optional `form` parameter was provided. ## Description The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using methods such as `fetch()`. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also append additional data to the `FormData` object after it's created using its various methods. A `FormData` object can be used in a number of ways with other APIs: 1. It can be sent with the `fetch()` API 2. It works seamlessly with the `Request` and `Response` objects - it can be used directly as the body of a `Request` object 3. It can be obtained from a `Response` object using the `formData()` method 4. It can be passed directly to the `URLSearchParams` constructor The transmitted data is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to `"multipart/form-data"`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.append() The **`append()`** method of the `FormData` interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. ## Syntax ```js append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.delete() The **`delete()`** method of the `FormData` interface removes all key/value pairs with the given name from the `FormData` object. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.entries() The **`entries()`** method of the `FormData` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator yields a new array for each key/value pair, with the first element being the key and the second element being the value. ## Syntax ```js entries() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.forEach() The **`forEach()`** method of the `FormData` interface executes the provided callback function once for each key/value pair in the `FormData` object. ## Syntax ```js forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each entry in the object. The function will be passed the following arguments: - `value` - : The value of the current entry. - `key` - : The key of the current entry. - `formData` - : The `FormData` object being traversed. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.get() The **`get()`** method of the `FormData` interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the [`getAll()`](../../../globals/FormData/prototype/getAll.mdx) method instead. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value A `FormDataEntryValue` containing the value. If the key does not exist, it returns `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/prototype/getAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.getAll() The **`getAll()`** method of the `FormData` interface returns all the values associated with a given key from within a `FormData` object. ## Syntax ```js getAll(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value An array of `FormDataEntryValue` items containing all values with the given key. If the key doesn't exist, an empty array is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.has() The **`has()`** method of the `FormData` interface returns a boolean indicating whether a `FormData` object contains a key/value pair with the given name. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the key you want to test for existence. ### Return value `true` if a key/value pair with the specified name exists; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.keys() The **`keys()`** method of the `FormData` interface returns an iterator allowing iteration through all keys contained in this object. The iterator yields the key for each value. ## Syntax ```js keys() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.set() The **`set()`** method of the `FormData` interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and [`append()`](../../../globals/FormData/prototype/append.mdx) is that if the specified key already exists, `set()` overwrites all existing values with the new one, whereas `append()` appends the new value onto the end of the existing values. ## Syntax ```js set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/FormData/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.values() The **`values()`** method of the `FormData` interface returns an iterator allowing iteration through all values contained in this object. The iterator yields the value for each key/value pair. ## Syntax ```js values() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name is not the name of an HTTP header, this method throws a `TypeError`. The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/prototype/getSetCookie.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.getSetCookie() The **`getSetCookie()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns an array of all the values of the `Set-Cookie` headers, returning an empty list if none are present. ## Syntax ```js getSetCookie() ``` ### Return value `String[]` representing the list of `Set-Cookie` headers. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2 or greater than π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex where x is a number very close to 0, you should get an answer very close to 1 + x, because limx0ex1x=1. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, a `ReadableStream` object, a [`Blob`](../../globals/Blob/Blob.mdx) object, or a [`FormData`](../../globals/FormData/FormData.mdx) object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_, see [`CacheOverride`](../../fastly:cache-override/CacheOverride/CacheOverride.mdx). - `cacheKey` _**Fastly-specific**_ - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.blob() The **`blob()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/clone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.clone() The **`clone()`** method of the `Request` interface creates a copy of the current `Request` object. Like the underlying `ReadableStream.tee`` api, the `body` of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Beware when you construct a `Request` from a stream and then `clone` it. `clone()` throws a `TypeError` if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) If you intend to modify the request, you may prefer the `Request` constructor. ## Syntax ```js clone() ``` ### Parameters None. ### Return value A `Request` object, which is an exact copy of the `Request` that `clone()` was called on. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.formData() The **`formData()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. - `SyntaxError` - : Thrown if the request's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Request` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Request instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - [`Blob`](../../globals/Blob/Blob.mdx) - [`FormData`](../../globals/FormData/FormData.mdx) - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.blob() The **`blob()`** method of the [`Response`](../Response.mdx) interface takes a [`Response`](../Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.formData() The **`formData()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. - `SyntaxError` - : Thrown if the response's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/ip.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ip The **`ip`** getter of the `Response` interface returns the IP address associated with the request, as either an IPv6 or IPv4 string. In the case where no IP address is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with an IP, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.port The **`port`** getter of the `Response` interface returns the port associated with the request, as a number. In the case where no port is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with a port, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Response` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Response instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - For ECDSA: Pass an [`EcKeyImportParams`](../../EcKeyImportParams/EcKeyImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](https://en.wikipedia.org/wiki/HZ_(character_encoding)). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Explicit Backends Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service. This `backend` option is then a special Fastly-specific fetch option that is provided to the `fetch()` call: ```js fetch('https://origin.com/path', { backend: 'origin' }); ``` Backends are configured using the Fastly service backend configuration, see the [Backend documentation](https://developer.fastly.com/reference/api/services/backend/) for more information. ## Dynamic Backends Dynamic backends are a compute feature that allow services to define backends for themselves. If the `backend` option is not provided when making `fetch()` requests, a backend will be automatically created by extracting the protocol, host, and port from the provided URL. In addition, custom backend configuration options can then also be provided through the [`Backend()`](../fastly:backend/Backend/Backend.mdx) constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ - `imageOptimizerOptions` _**Fastly-specific**_, see [`imageOptimizerOptions`](../fastly:image-optimizer/imageOptimizerOptions.mdx). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-3.39.2/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/after.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # after The `after` method inserts content after the closing tag of the element. ## Syntax ```js element.after(content); element.after(content, options); ``` ### Parameters - `content` _: string_ - The content to insert after the element's closing tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.after("World"); // Result:
Hello
World ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # append The `append` method inserts content at the end of the element's content. ## Syntax ```js element.append(content); element.append(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the end of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.append(", World"); // Result:
Hello, World
``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/before.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # before The `before` method inserts content before the opening tag of the element. ## Syntax ```js element.before(content); element.before(content, options); ``` ### Parameters - `content` _: string_ - The content to insert before the element's opening tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.before("Well"); // Result: Well
Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/hasAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # hasAttribute The `hasAttribute` method returns a `boolean` value indicating whether the specified attribute is present on the element. ## Syntax ```js element.hasAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to check for. ### Return value A boolean value indicating whether the attribute is present. ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/prepend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # prepend The `prepend` method inserts content at the beginning of the element's content. ## Syntax ```js element.prepend(content); element.prepend(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the beginning of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.prepend("Well, "); // Result:
Well, Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/removeAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # removeAttribute The `removeAttribute` method removes the specified attribute from the element. ## Syntax ```js element.removeAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to remove. ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/replaceChildren.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceChildren The `replaceChildren` method replaces the element's children with new content. ## Syntax ```js element.replaceChildren(content); element.replaceChildren(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element's children with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceChildren("Greetings!"); // Result:
Greetings!
``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/replaceWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceWith The `replaceWith` method replaces the element with new content. ## Syntax ```js element.replaceWith(content); element.replaceWith(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceWith("

Greetings!

"); // Result:

Greetings!

``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/selector.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # selector The `selector` read-only property is a `string` representing the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) that matches the element. ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/setAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setAttribute The `setAttribute` method sets the value of the specified attribute on the element. If the value already exists, it will be updated; otherwise, a new attribute with the specified name and value will be added to the element. ## Syntax ```js element.setAttribute(attributeName, value); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to set. - `value` _: string_ - The value to assign to the attribute. ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/Element/prototype/tag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # tag The `tag` read-only property is a `string` representing the tag name of the element. ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/HTMLRewritingStream/HTMLRewritingStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `HTMLRewritingStream()` The **`HTMLRewritingStream`** lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback. This callback can manipulate the attributes of the element, and add or remove content from the immediate context. ## Syntax ```js new HTMLRewritingStream() ``` ### Return value A new `HTMLRewritingStream` object. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/html-rewriter/HTMLRewritingStream/prototype/onElement.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # onElement ▸ **onElement**`(selector: string, handler: (element: Element) => void): this` Registers an element handler with the [`HTMLRewritingStream`] that will be called for each [`Element`] that matches the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) `selector`. Elements added by handlers will not be processed by other handlers. ## Syntax ```js .onElement(selector, handler) ``` ### Parameters - `selector` _: string_ - A CSS selector that determines the elements for which `handler` will be called - The following types of CSS selector are supported: Currently the rewriter supports the following CSS selectors: | Pattern | Description | |----------------------|----------------------------------------------------------------------------| | `*` | Any element | | `E` | All elements of type `E` | | `E F` | `F` elements inside `E` elements | | `E > F` | `F` elements directly inside `E` elements | | `E:nth-child(n)` | The n-th child of type `E` | | `E:first-child` | First child of type `E` | | `E:nth-of-type(n)` | The n-th sibling of type `E` | | `E:first-of-type` | First sibling of type `E` | | `E:not(s)` | Type `E` elements not matching selector `s` | | `E.myclass` | Type `E` elements with class `"myclass"` | | `E#myid` | Type `E` elements with ID `"myid"` | | `E[attr]` | Type `E` elements with attribute `attr` | | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | | `E[attr="val" i]` | Type `E` elements where `attr` is `"val"`, case-insensitive | | `E[attr="val" s]` | Type `E` elements where `attr` is `"val"`, case-sensitive | | `E[attr~="val"]` | Type `E` elements where `attr` contains `"val"` in a space-separated list | | `E[attr`|`;="val"]`| Type `E` elements where `attr` is hyphen-separated and starts with `"val"` | | `E[attr^="val"]` | Type `E` elements where `attr` starts with `"val"` | | `E[attr$="val"]` | Type `E` elements where `attr` ends with `"val"` | | `E[attr*="val"]` | Type `E` elements where `attr` contains `"val"` | - `handler` _: (element: Element) => void_ - A callback function that will be called once for each element that matches `selector` ### Return value The `HTMLRewritingStream`, so multiple calls to `onElement` can be chained. ### Exceptions - `Error` - If the provided `selector` is not a valid CSS selector. - If the provided `handler` is not a function. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/Auto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Auto` Enumerator options for [`imageOptimizerOptions.auto`](./imageOptimizerOptions.mdx). ## Constants - `AVIF` (`"avif"`) If the browser's Accept header indicates compatibility, deliver an AVIF image. - `WEBP` (`"webp"`) If the browser's Accept header indicates compatibility, deliver a WebP image. ## Examples ```js import { Auto, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, auto: Auto.AVIF }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/BWAlgorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `BWAlgorithm` Enumerator options for [`imageOptimizerOptions.bw`](./imageOptimizerOptions.mdx). ## Constants - `Threshold` (`"threshold"`) Uses a luminance threshold to convert the image to black and white. - `Atkinson` (`"atkinson"`) Uses [Atkinson dithering](https://en.wikipedia.org/wiki/Atkinson_dithering) to convert the image to black and white. ## Examples ```js import { Region, BWAlgorithm } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, bw: BWAlgorithm.Threshold }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/CropMode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CropMode` Enumerator options for [`imageOptimizerOptions.crop.mode`](./imageOptimizerOptions.mdx) and `imageOptimizerOptions.precrop.mode`. ## Constants - `Smart` (`"smart"`) Enables content-aware algorithms to attempt to crop the image to the desired aspect ratio while intelligently focusing on the most important visual content, including the detection of faces. - `Safe` (`"safe"`) Allow cropping out-of-bounds regions. ## Examples ```js import { CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Smart, } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/Disable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Disable` Enumerator options for [`imageOptimizerOptions.disable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Prevent images being resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Disable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, disable: Disable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/Enable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Enable` Enumerator options for [`imageOptimizerOptions.enable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Allow images to be resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Enable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, enable: Enable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/Fit.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Fit` Enumerator options for [`imageOptimizerOptions.fit`](./imageOptimizerOptions.mdx). ## Constants - `Bounds` (`"bounds"`) Resize the image to fit entirely within the specified region, making one dimension smaller if needed. - `Cover` (`"cover"`) Resize the image to entirely cover the specified region, making one dimension larger if needed. - `Crop` (`"crop"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Fit, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 150, height; 150, fit: Fit.Bounds }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/Format.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Format` Enumerator options for [`imageOptimizerOptions.format`](./imageOptimizerOptions.mdx). ## Constants - `Auto` (`"auto"`) Automatically use the best format based on browser support and image/transform characteristics - `AVIF` (`"avif"`) AVIF - `BJPG` (`"bjpg"`) Baseline JPEG - `GIF` (`"gif"`) Graphics Interchange Format - `JPG` (`"jpg"`) JPEG - `JXL` (`"jxl"`) JPEGXL - `MP4` (`"mp4"`) MP4 (H.264) - `PJPG` (`"pjpg"`) Progressive JPEG - `PJXL` (`"pjxl"`) Progressive JPEGXL - `PNG` (`"png"`) Portable Network Graphics - `PNG8` (`"png8"`) Portable Network Graphics palette image with 256 colors and 8-bit transparency - `SVG` (`"svg"`) Scalable Vector Graphics - `WEBP` (`"webp"`) WebP - `WEBPLL` (`"webpll"`) WebP (Lossless) - `WEBPLY` (`"webply"`) WebP (Lossy) ## Examples ```js import { Format, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/Metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Metadata` Enumerator options for [`imageOptimizerOptions.metadata`](./imageOptimizerOptions.mdx). ## Constants - `Copyright` (`"copyright"`) Preserve [copyright notice](https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#copyright-notice), creator, credit line, licensor, and web statement of rights fields. - `C2PA` (`"c2pa"`) Preserve the [C2PA manifest](https://c2pa.org/) and add any transformations performed by Fastly Image Optimizer. - `CopyRightAndC2PA` (`"copyright,c2pa"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Metadata, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, metadata: Metadata.Copyright }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/Optimize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Optimize` Enumerator options for [`imageOptimizerOptions.optimize`](./imageOptimizerOptions.mdx). ## Constants - `Low` (`"low"`) Output image quality will be similar to the input image quality. - `Medium` (`"medium"`) More optimization is allowed. We attempt to preserve the visual quality of the input image. - `High` (`"high"`) Minor visual artifacts may be visible. This produces the smallest file. ## Examples ```js import { Optimize, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, optimize: Optimize.High }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/Orient.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Orient` Enumerator options for [`imageOptimizerOptions.orient`](./imageOptimizerOptions.mdx). ## Constants - `Default` (`"1"`) - `FlipHorizontal` (`"2"`) - `FlipHorizontalAndVertical` (`"3"`) - `FlipVertical` (`"4"`) - `FlipHorizontalOrientLeft` (`"5"`) - `OrientRight` (`"6"`) - `FlipHorizontalOrientRight` (`"7"`) - `OrientLeft` (`"8"`) ## Examples ```js import { Orient, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, orient: Orient.FlipHorizontal }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/Profile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Profile` Enumerator options for [`imageOptimizerOptions.profile`](./imageOptimizerOptions.mdx). ## Constants - `Baseline` (`"baseline"`) The profile recommended for video conferencing and mobile applications. (Default) - `Main` (`"main"`) The profile recommended for standard-definition broadcasts. - `High` (`"high"`) The profile recommended for high-definition broadcasts. ## Examples ```js import { Profile, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, profile: Profile.Main }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/Region.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Region` Enumerator options for [`imageOptimizerOptions.region`](./imageOptimizerOptions.mdx). ## Constants - `UsEast` (`"us_east"`) - `UsCentral` (`"us_central"`) - `UsWest` (`"us_west"`) - `EuCentral` (`"eu_central"`) - `EuWest` (`"eu_west"`) - `Asia` (`"asia"`) - `Australia` (`"australia"`) ## Examples ```js import { Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/ResizeFilter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ResizeFilter` Enumerator options for [`imageOptimizerOptions.resizeFilter`](./imageOptimizerOptions.mdx). ## Constants - `Nearest` (`"nearest"`) Uses the value of nearby translated pixel values. - `Bilinear` (`"bilinear"`) Uses an average of a 2x2 environment of pixels. - `Linear` (`"linear"`) Same as `Bilenear`. - `Bicubic` (`"bicubic"`) Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. - `Cubic` (`"cubic"`) Same as `Bicubic`. - `Lanczos2` (`"lanczos2"`) Uses the Lanczos filter to increase the ability to detect edges and linear features within an image and uses sinc resampling to provide the best possible reconstruction. - `Lanczos3` (`"lanczos3"`) Lanczos3 uses a better approximation of the sinc resampling function. (Default) - `Lanczos` (`"lanczos"`) Same as `Lanczos3`. ## Examples ```js import { ResizeFilter, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, resizeFilter: ResizeFilter.Linear }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/image-optimizer/imageOptimizerOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `imageOptimizerOptions` Options specified in the [`Request`](../globals/Request/Request.mdx) constructor for running the [Fastly Image Optimizer](https://docs.fastly.com/products/image-optimizer). More detailed documentation on all Image Optimizer options is available in the [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/). ## Parameters All parameters other than `region` are optional. - `region`: _[`Region`](./Region.mdx)_ Where image optimizations should occur. - `auto`: _[`Auto`](./Auto.mdx)_ Enable optimization features automatically. - `bgColor`: _[`Color`](#color)_ Set the background color of an image. - `blur`: _`number` (0.5-1000) or [`Percentage`](#percentage)_ Set the blurriness of the output image. - `brightness`: _`number` (-100-100)_ Set the brightness of the output image. - `bw`: _[`BWAlgorithm`](./BWAlgorithm.mdx)_ Convert an image to black and white. - `canvas`: _`Object`_ Increase the size of the canvas around an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `contrast`: _`number` (-100-100)_ Set the contrast of the output image. - `crop`: _`Object`_ Remove pixels from an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `mode` (optional): _[`CropMode`](./CropMode.mdx)_ - `disable`: _[`Disable`](./Disable.mdx)_ Disable functionality that is enabled by default. - `dpr`: `number` Ratio between physical pixels and logical pixels. - `enable`: _[`Enable`](./Enable.mdx)_ Enable functionality that is disabled by default. - `fit`: _[`Fit`](./Fit.mdx)_ Set how the image will fit within the size bounds provided. - `format`: _[`Format`](./Format.mdx)_ Specify the output format to convert the image to. - `frame`: _`number` (must have the value 1)_ Extract the first frame from an animated image sequence. - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the height of the image. - `level`: _`String` containing one of the [allowed values](https://www.fastly.com/documentation/reference/io/level/#allowed-values)_ Specify the level constraints when converting to video. - `metadata`: _[`Metadata`](./Metadata.mdx)_ Control which metadata fields are preserved during transformation. - `optimize`: _[`Optimize`](./Optimize.mdx)_ Automatically apply optimal quality compression. - `orient`: _[`Orient`](./Orient.mdx)_ Change the cardinal orientation of the image. - `pad`: _[`Sides`](#sides)_ Add pixels to the edge of an image. - `precrop`: _`Object`_ Remove pixels from an image before any other transformations occur. - `size`: _[`Size`](#size)_ - `position`: _[`Position`](#position)_ - `mode`: _[`CropMode`](./CropMode.mdx)_ - `profile`: _[`Profile`](./Profile.mdx)_ Specify the profile class of application when converting to video. - `quality`: _`integer` (1-100)_ Optimize the image to the given compression level for lossy file formatted images. - `resizeFilter`: _[`ResizeFilter`](./ResizeFilter.mdx)_ Specify the resize filter used when resizing images. - `saturation`: _`number` (-100-100)_ Set the saturation of the output image. - `sharpen`: _`Object`_ Set the sharpness of the output image. - `amount`: _`number` (0-10)_ - `radius`: _`number` (0.5-1000)_ - `threshold`: _`integer` (0-255)_ - `trim`: _[`Sides`](#sides)_ Remove pixels from the edge of an image. - `viewbox`: _`number` (must have the value 1)_ Remove explicit width and height properties in SVG output. - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the width of the image. ## Types ### Color Either: - a 3 or 6 character hexadecimal string - an `Object` containing: - `r`: _`integer` (0-255)_ Red component - `g`: _`integer` (0-255)_ Green component - `b`: _`integer` (0-255)_ Blue component - `a` (optional): _`number` (0.0-1.0)_ Alpha component ### Percentage A `String` containing a number suffixed with a percent sign (%). ### Position An `Object` containing: - Exactly one of: - `x`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetX`: _`number` (interpreted as a percentage)_ - Exactly one of: - `y`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetY`: _`number` (interpreted as a percentage)_ ### Sides An `Object` containing `top`, `bottom`, `left`, and `right`, all of which are either an `integer` or [`Percentage`](#percentage). ### Size An `Object` containing either: - `absolute`: _`Object`_ - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `ratio`: _`Object`_ - `width`: _`number`_ - `height`: _`number`_ ## Examples ```js import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG, bgColor: { 'r': 100, 'g': 255, 'b': 9, 'a': 0.5 }, blur: '1%', brightness: -20, contrast: -20, height: 600, level: '4.0', orient: Orient.FlipVertical, saturation: 80, sharpen: { 'amount': 5, 'radius': 6, 'threshold': 44 }, canvas: { 'size': { 'absolute': { 'width': 400, 'height': 400 } } }, crop: { size: { absolute: { width: 200, height: 200 }, mode: CropMode.Safe } }, trim: { top: 10, left: 10, right: 10, bottom: 10 }, pad: { top: 30, left: 30, right: "1%", bottom: 30 } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a KV store instance using the resource link name. ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStore/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.delete Deletes the value associated with the key `key` in the KV store. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value Returns `undefined` ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - Does not exist ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then delete the entry. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') await files.delete('hello') const entry = await files.get('hello') if (entry) { return new Response(await entry.text()) } else { return new Response('no file named hello exists') } } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStore/prototype/list.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.list The **`list()`** can be used to list the keys of a store. ## Syntax ```js list(options?) ``` ### Parameters - `options` _: object_ _**optional**_ - List options supporting properties: - `cursor` _: string_ _**optional**_ - The cursor used to pick up from a previous iteration. - `limit` _: number_ _**optional**_ - The maximum number of keys to return. - `prefix` _: string_ _**optional**_ - List only those keys that start with the given string prefix. - `noSync` _: boolean_ _**optional**_ - Do not sync the key list first, instead provide a possibly out-of-date listing. May be faster but inconsistent. ### Return value Returns a `Promise` which resolves with `{ list: string[], cursor: string | undefined }`. ## Example In this example we list the keys of a KV Store named `'files'`, iterating 10 at a time, counting the total; ```js /// import { KVStore } from 'fastly:kv-store'; async function app(event) { const files = new KVStore('files'); let cursor, list, total = 0; do { ({ cursor, list } = await files.list({ limit: 10, cursor })); total += list?.length; } while (list); return new Response(`Iterated ${total} entries`); } addEventListener('fetch', (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value, options?) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. - `options` _: object_ _**optional**_ - An insert options parameter, supporting: - `metadata` _: ArrayBuffer | TypedArray | DataView_ _**optional**_ - Binary metadata associated with the entry, may be up to 1000 bytes. - `ttl` _: number_ _**optional**_ - TTL for the entry - `mode` _: 'overwrite' | 'add' | 'append' | 'prepend'_ _**optional**_ - Insert mode, defaults to 'overwrite' - `gen` _: number_ _**optional**_ - 'generation' header specific to the version of an entry key ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - `TypeError` - If the provided `gen`: - Is not an number ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStoreEntry/prototype/metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadata() The `metadata()` method of the `KVStoreEntry` interface provides the binary metadata associated with the `KVStoreEntry`. The metadata binary may be up to 1000 bytes, and is returned as a `Uint8Array` TypedArray buffer, if metadata is set, or null otherwise. ## Syntax ```js metadata() ``` ### Parameters None. ### Return value A `Promise` that resolves to a `Uint8Array` buffer object. ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStoreEntry/prototype/metadataText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadataText() The `metadataText()` method of the `KVStoreEntry` interface provides a String interpretation of binary metadata associated with the `KVStoreEntry`. If the binary data is not a valid string, an encoding error will be thrown. ## Syntax ```js metadataText() ``` ### Parameters None. ### Return value A `Promise` that resolves to a String. ================================================ FILE: documentation/versioned_docs/version-3.39.2/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; const logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; let logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/logger/configureConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # configureConsole The **`configureConsole()`** function allows configuring the behaviour of the `console` global JS logger. ## Syntax ```js configureConsole(loggingOptions) ``` ### Parameters - `loggingOptions` _: object_ - - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ## Examples In this example, we disable prefixing for `console.log` and use `stderr` output for `console.error`: ```js import { configureConsole } from "fastly:logger"; configureConsole({ prefixing: false, stderr: true }); async function handleRequest(event) { console.log(JSON.stringify(event.request.headers)); const url = new URL(event.request.url); try { validate(url); } catch (e) { console.error(`Validation error: ${e}`); return new Response('Bad Request', { status: 400 }); } return new Response('OK'); } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v2 to v3` ## SimpleCache.delete renamed to SimpleCache.purge and requires purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using `SimpleCache.delete` to `SimpleCache.purge` with the same purging behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a Secret Store instance using the resource link name. ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/secret-store/SecretStore/fromBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fromBytes The **`fromBytes()`** function is used to create an in-memory secret from an array buffer. >**Note**: This API should be avoided when possible, by instead using [SecretStore.prototype.get](./prototype/get.mdx) to obtain secure secrets. ## Syntax ```js fromBytes(new Uint8Array([1, 2, 3])) ``` ### Parameters None. ### Return value Returns a `SecretStoreEntry`. ================================================ FILE: documentation/versioned_docs/version-3.39.2/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/secret-store/SecretStoreEntry/prototype/rawBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.rawBytes ▸ **rawBytes**(): `Uint8Array` Returns the raw byte contents of the SecretStoreEntry instance as a Uint8Array. ## Syntax ```js rawBytes() ``` ### Parameters None. ### Return value A Uint8Array ### Exceptions The `rawBytes()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ================================================ FILE: documentation/versioned_docs/version-3.39.2/security/inspect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # inspect The **`inspect()`** function inspects a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). ## Syntax ```js inspect(request, config); ``` ### Parameters - `request` _: Request_ - The Request to get a WAF determination for. - `config` _: object_ - `corp` _: string_ - Set a corp name for the configuration. - This parameter is currently required. - `workspace` _: string_ - Set a workspace name for the configuration. - This parameter is currently required. - `overrideClientIp` _: string_ - Specify an explicit client IP address to inspect. - By default, `inspect` will use the IP address that made the request to the running Compute service, but you may want to use a different IP when service chaining or if requests are proxied from outside of Fastly’s network. ### Return value Returns an `Object` with the `inspect` response, with the following fields: - `waf_response` _: number_ - Security status code. - `redirect_url` _: string | null_ - A redirect URL returned from Security. - `tags` _: string[]_ - Tags returned by Security. - `verdict` _: string_ - The outcome of inspecting a request with Security. It can be one of the following: - `"allow"` - Security indicated that this request is allowed. - `"block"` - Security indicated that this request should be blocked. - `"unauthorized"` - Security indicated that this service is not authorized to inspect a request. - Other verdicts may be returned but not currently documented. - `decision_ms` _: number_ - How long Security spent determining its verdict, in milliseconds. ## Examples ```js /// import { inspect } from "fastly:security"; async function app(event) { const res = inspect(event.request, { corp: "mycorp", workspace: "myws" }); switch (res.verdict) { case "allow": return await fetch(event.request); case "block": return new Response("Request Blocked", { status: 400 }); case "unauthorized": return new Response("Unauthorized", { status: 401 }); default: return new Response("idk", { status: 500 }); } } addEventListener("fetch", (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/shielding/Shield/Shield.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Shield()` Load information about the given shield. Returns an object representing the shield if it is active, or throws an exception if the string is malformed or the shield doesn’t exist. Shield names are defined on [this webpage](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations), in the “shield code” column. For example, the string “pdx-or-us” will look up our Portland, OR, USA shield site, while “paris-fr” will look up our Paris site. If you are using a major cloud provider for your primary origin site, consider looking at the “Recommended for” column, to find the Fastly POP most closely located to the given cloud provider. ## Syntax ```js new Shield(name) ``` > **Note:** `Shield()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Exceptions - `TypeError` - Thrown if no Shield exists with the provided name ## Examples In this example, we create a Shield instance for the Sydney, Australia shield POP. If the code is running on that shield POP, it fetches directly from origin. Otherwise, it routes the request through the shield using an encrypted connection. ```js /// import { Shield } from "fastly:shielding"; async function app(event) { const shield = new Shield('wsi-australia-au'); // If running on the shield POP, fetch from the origin directly if (shield.runningOn()) { return await fetch('https://http-me.fastly.com/anything', { backend: 'httpme' }); } // Otherwise, route the request through the shield using an encrypted connection return await fetch(event.request, { backend: shield.encryptedBackend() }); } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.2/shielding/Shield/prototype/encryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.encryptedBackend ▸ **encryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an encrypted connection to the POP. For reference, this is almost always the backend that you want to use. Only use [`Shield::unencryptedBackend`](./unencryptedBackend.mdx) in situations in which you are 100% sure that all the data you will send and receive over the backend is already encrypted. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.39.2/shielding/Shield/prototype/runningOn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.runningOn ▸ **runningOn**(): `boolean` Returns whether we are currently operating on the given shield. Technically, this may also return true in very isolated incidents in which Fastly is routing traffic from the target shield POP to the POP that this code is running on, but in these situations the results should be approximately identical. (For example, it may be the case that you are asking to shield to ‘pdx-or-us’. But, for load balancing, performance, or other reasons, Fastly is temporarily shifting shielding traffic from Portland to Seattle. In that case, this function may return true for hosts running on ‘bfi-wa-us’, our Seattle site, because effectively the shield has moved to that location. This should give you a slightly faster experience than the alternative, in which this function would return false, you would try to forward your traffic to the Portland site, and then that traffic would be caught and redirected back to Seattle.) ================================================ FILE: documentation/versioned_docs/version-3.39.2/shielding/Shield/prototype/unencryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.unencryptedBackend ▸ **unencryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an unencrypted connection to the POP. Generally speaking, we encourage users to use [`Shield::encryptedBackend`](./encryptedBackend.mdx) instead of this function. Data sent over this backend – the unencrypted version – will be sent over the open internet, with no protections. In most cases, this is not what you want. However, in some cases – such as when you want to ship large data blobs that you know are already encrypted — using these backends can prevent a double-encryption performance penalty. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.39.2/websocket/createWebsocketHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createWebsocketHandoff The **`createWebsocketHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Websocket, to the declared backend. ## Syntax ```js createWebsocketHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Websocket. - `backend` _: string_ - The name of the backend that Websocket should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Websocket. ```js import { createWebsocketHandoff } from "fastly:websocket"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createWebsocketHandoff(event.request, 'websocket_backend'); } else { return new Response('oopsie, make a request to /stream for some websocket goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/acl/Acl/open.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.open() Opens the ACL with the given name, returning a new `Acl` instance with the given name on success. ## Syntax ```js Acl.open(name) ``` ### Return value An `Acl` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.3/acl/Acl/prototype/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.prototype.lookup() The **`lookup(ipAddress)`** method returns the name associated with the `Acl` instance. ## Syntax ```js acl.lookup(ipAddress) ``` ### Parameters - `ipAddress` _: string_ - IPv4 or IPv6 address to lookup ### Return value An Object of the form `{ action: 'ALLOW' | 'BlOCK', prefix: string }`, where `prefix` is the IP address prefix that was matched in the ACL. ## Example ```js /// import { Acl } from 'fastly:acl'; addEventListener('fetch', async (evt) => { const myAcl = Acl.open('myacl'); const match = await myAcl.lookup(evt.client.address); evt.respondWith(new Response(match?.action === 'BLOCK' ? 'blocked' : 'allowed')); }); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. >**Note**: Dynamic backends are by default disabled at the Fastly service level. Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request dynamic backends on Fastly Services. To disable the usage of dynamic backends, see [enforceExplicitBackends](../enforceExplicitBackends.mdx). ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. - `grpc` _: boolean_ _**optional**_ - **_Experimental feature_** - When enabled, sets that this backend is to be used for gRPC traffic. - _Warning: When using this experimental feature, no guarantees are provided for behaviours for backends that do not provide gRPC traffic._ All optional generic options can have their defaults set via [`setDefaultDynamicBackendConfig()`](../setDefaultDynamicBackendConfig.mdx). This includes all configuration options above except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. ### Return value A new `Backend` object. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/exists.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.exists() The **`Backend.exists()`** method returns a boolean indicating if a Backend with the given name exists or not. ## Syntax ```js exists(name) ``` ### Return value A boolean indicating if a Backend with the given name exists or not. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/fromName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.fromName() Returns the `Backend` instance with the given name, if one exists. If one does not exist, an error is thrown. ## Syntax ```js fromName(name) ``` ### Return value A `Backend` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.health() :::info This method is deprecated, use [`Backend.prototype.health`](./prototype/health.mdx) instead. ::: The **`Backend.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js Backend.health(backend) ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/betweenBytesTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.betweenBytesTimeout The read-only **`betweenBytesTimeout`** property of a `Backend` instance is an integer number providing the between bytes timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/connectTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.connectTimeout The read-only **`connectTimeout`** property of a `Backend` instance is an integer number providing the connect timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/firstByteTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.firstByteTimeout The read-only **`firstByteTimeout`** property of a `Backend` instance is an integer number providing the first byte timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.health() The **`Backend.prototype.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js health() ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/hostOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.hostOverride The read-only **`hostOverride`** property of a `Backend` instance is the host header override string used when sending requests to this backend. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/httpKeepaliveTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.httpKeepaliveTime The read-only **`httpKeepaliveTime`** property of a `Backend` instance is the HTTP keepalive time for this backend in milliseconds, or 0 if no keepalive is set. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/isDynamic.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isDynamic The read-only **`isDynamic`** property of a `Backend` instance is a boolean indicating if the backend was dynamically created for this service. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/isSSL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isSSL The read-only **`isSSL`** property of a `Backend` instance is a boolean indicating if the backend is using an SSL connection. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # name The read-only **`name`** property of the backend returns the backend name string. ## Value A `string`. ## Description Provides the name of the backend. ## Examples ### Using name The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.port The read-only **`port`** property of a `Backend` instance is the port number of this backend. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/target.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.target The read-only **`target`** property of a `Backend` instance is the host string this backend is configured to use. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/tcpKeepalive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tcpKeepalive The read-only **`tcpKeepalive`** property of a `Backend` instance returns an object providing the TCP keepalive configuration, if any, otherwise returning `null` if TCP keepalive is not enabled. This object has the following properties: - `timeSecs` _: number or null._ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number or null._ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number or null._ - Number of probes to send to the backend before it is considered dead. ## Value A `Object` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/tlsMaxVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMaxVersion The read-only **`tlsMaxVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/tlsMinVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMinVersion The read-only **`tlsMinVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/toName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.toName() :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toName()`** method returns the name associated with the `Backend` instance. ## Syntax ```js toName() ``` ### Return value A string which contains the name of the Backend. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toString :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends :::info This method is deprecated, and dynamic backends are now always supported when enabled at the service level. See [`enforceExplicitBackends`](./enforceExplicitBackends.mdx) instead. ::: The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: By default, while dynamic backends are allowed in the SDK, they are by default disabled at the Fastly service level. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/enforceExplicitBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enforceExplicitBackends Call this function to enforce the security property of explicitly-defined backends, even when dynamic backends are enabled at the Fastly service level. By default, if dynamic backends are supported for the Fastly service, they will be automatically used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a potential security concern since third-party JavaScript code may send arbitrary requests, including sensitive/secret data, off to destinations that the JavaScript project was not intending. When calling this function, an optional default backend name can be provided. >**Note**: This is a separate option to the service-level dynamic backend support for Fastly services, which is by deault disabled for Fastly services. The **`enforceExplicitBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: Dynamic Backends are disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled or disabled on Fastly Services. ## Syntax ```js enforceExplicitBackends(defaultBackend?) ``` ### Parameters - `defaultBackend` _: string_ _**optional**_ - An optional default backend string name to use in `fetch()` requests. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/backend/setDefaultDynamicBackendConfig.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setDefaultDynamicBackendConfig() The **`setDefaultDynamicBackendConfig()`** allows setting backend configuration defaults that should apply to any newly created dynamic backends via the `new Backend()` constructor. ### Parameters - `defaultDynamicBackendConfig` - : An Object which contains the generic configuration options to apply to newly created Backends. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. ## Syntax ```js setDefaultDynamicBackendConfig(defaultConfig) ``` ### Return value None. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, with timeouts and TLS options provided from the default backend configuration options. import { allowDynamicBackends } from "fastly:experimental"; import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! // Timeouts and TLS configuration still get set from the default backend configuration above. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.age The **`age`** method of the `CacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.body The **`body`** method of the `CacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this `CacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.close The **`close`** method of the `CacheEntry` interface closes the connection to the cache for this `CacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.hits The **`hits`** method of the `CacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.length The **`length`** method of the `CacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.maxAge The **`maxAge`** method of the `CacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `CacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.state The **`state`** method of the `CacheEntry` interface returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.userMetadata The **`userMetadata`** method of the `CacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheState/found.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.found The **`found`** method of the `CacheState` interface returns `true` if a cached item was located. Even if an cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. ## Syntax ```js found() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item was located or not. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheState/mustInsertOrUpdate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.mustInsertOrUpdate The **`mustInsertOrUpdate`** method of the `CacheState` interface returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. ## Syntax ```js mustInsertOrUpdate() ``` ### Parameters None. ### Return value A `boolean` which represents whether a fresh cached item was found not. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheState/stale.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.stale The **`stale`** method of the `CacheState` interface returns `true` if the cached item is stale. A cached item is stale if its age is greater than its `maxAge` period. ## Syntax ```js stale() ``` ### Parameters None. ### Return value A `boolean` which represents whether the cached item is stale or not. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CacheState/usable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.usable The **`usable`** method of the `CacheState` interface returns `true` if the cached item is usable. A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. ## Syntax ```js usable() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item is usable or not. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CoreCache/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.insert Performs a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. ## Syntax ```js insert(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item’s contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CoreCache/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.lookup Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. ## Syntax ```js lookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns `CacheEntry` if a usable cached item was found, otherwise returns `null`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/CoreCache/transactionLookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.transactionLookup Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. Request Collapsing: If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, just one of the callers will be instructed to insert the item into the cache as part of the transaction. The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. Revalidation: Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. ## Syntax ```js transactionLookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns an instance of `TransactionCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, and return a message stating whether the entry was in the Fastly Cache or not. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); return new Response(page ? `${path} is in the cache` : `${path} is not in the cache`, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key`. If no entry is found (or has expired), the supplied `set` function is executed and its result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - The function to execute if and only if the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The maximum number of seconds to store the supplied entry in the cache. - `length` _: number_ __optional__ - The length of the value being stored within the cache. This is only used when the `value` is a `ReadableStream`. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/SimpleCache/purge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.purge purge the entry associated with the key `key` from the cache. ## Syntax ```js purge(key, options) ``` ### Parameters - `key` _: string_ - The key to purge from within the cache. - `options` _: object_ - `scope` _: string_ - : Where to purge the content from. - Possible values are: - "global" - This will remove the content from all of Fastly. - "pop" - This will remove the content from the POP that contains the currently executing instance. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `purge` querystring parameter, we purge the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('purge')) { SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.age The **`age`** method of the `TransactionCacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.body The **`body`** method of the `TransactionCacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `TransactionCacheEntry`. An error will be thrown if a stream is already active for this `TransactionCacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.cancel The **`cancel`** method of the `TransactionCacheEntry` interface cancels an obligation to provide an object to the cache. ## Syntax ```js cancel() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.close The **`close`** method of the `TransactionCacheEntry` interface closes the connection to the cache for this `TransactionCacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.hits The **`hits`** method of the `TransactionCacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insert Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. ## Syntax ```js insert(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/insertAndStreamBack.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insertAndStreamBack Perform a transaction cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. ## Syntax ```js insertAndStreamBack(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns an array where the first item is a `FastlyBody` instance and the second item is a `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.length The **`length`** method of the `TransactionCacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.maxAge The **`maxAge`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.state The **`state`** method of the `TransactionCacheEntry` interface returns a `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/update.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.update Perform an update of the cache item's metadata. ## Syntax ```js update(options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache/TransactionCacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.userMetadata The **`userMetadata`** method of the `TransactionCacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.39.3/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) new CacheOverride(init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. This options is also the default when providing an init object directly as the first argument. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. - `beforeSend` _:Function_ _**optional**_ - `(request: Request) => void | PromiseLike` - Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. - See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) in the Fastly cache interfaces documentation for details. - `afterSend` _: Function_ _**optional**_ - `(response: Response) => void | CacheOptions | PromiseLike` - Callback to be invoked after a response has been sent, but before it is stored into the cache. - Where `CacheOptions` contains: - `cache` _: boolean | 'uncacheable'_ _**optional**_ - Whether to cache this response. By default, leaving this field empty, responses will be cached based on their cache header information. - Setting this to true or false will override this default cache behaviour, setting in the cache or not setting in the cache, even if the default behaviour would have been otherwise. - Setting to 'uncacheable' the response will not only not be cached, but the cache will record that the originating request led to an uncacheable response, so that future cache lookups will result in immediately going to the backend, rather than attempting to coordinate concurrent requests to reduce backend traffic. - See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) for more details on the mechanism that `uncacheable` disables. - `bodyTransformFn` _: Function_ _**optional**_ - `(body: Uint8Array) => Uint8Array | PromiseLike` - Provide a function to be used for transforming the response body prior to caching. - Body transformations are performed by specifying a transform, rather than by directly working with the body during the onAfterSend callback function, because not every response contains a fresh body: 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because they do not retransmit the body. - For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will be applied to it. The original backend body is passed in to the transform function, and the function is expected to return the new body. - See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) in the Fastly cache interfaces documentation for details. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/compute/purgeSurrogateKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # purgeSurrogateKey The **`purgeSurrogateKey()`** function is used to purge the given surrogate key string from Fastly's cache. There are two purge modes: soft purge and hard purge, with hard purge as the default which clears all items from the cache immediately. When using a soft purge, stale entries are maintained in the cache, reducing orgin load, while also enabling stale revalidations. See the [Fastly Purge Documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) for more information on caching and purge operations. ## Syntax ```js purgeSurrogateKey(surrogateKey, soft?) ``` ### Parameters - `surrogateKey` _: string_ - The surrogate key string - `soft?` _: boolean_ - Enables a soft purge, retaining stale entries in the cache. Default is a hard purge. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/compute/vCpuTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # vCpuTime The **`vCpuTime()`** function provides the vCPU time used by the current request handler in milliseconds. ## Syntax ```js vCpuTime() ``` ### Parameters None. ### Return value `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Defines a config store instance using the resource link name. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have a resource link named "animals" (which is linked to a config store) and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.lookup() Look up the data associated with a particular User-Agent string. ## Syntax ```js lookup(userAgent) ``` ### Return value If there is data associated with the User-Agent, a `Device` instance is returned. Otherwise, `null` is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/brand.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.brand The read-only **`brand`** property of the `Device` interface is either a string stating the brand of the device, which can be different from the manufacturer of that device. If no brand is known, the value will be `null`. ## Value Either a string value if a brand is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/hardwareType.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.hardwareType The read-only **`hardwareType`** property of the `Device` interface is either a string stating the hardware type of the device, or `null` if the hardware type is not known. A string representation of the device's primary platform hardware. The most commonly used device types are also identified via boolean variables. Because a device may have multiple device types and this variable only has the primary type, we recommend using the boolean variables for logic and using this string representation for logging. ## Value Either a string value if a hardware type is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/isBot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isBot The read-only **`isBot`** property of the `Device` interface is either a boolean stating if the device is a bot, or `null` if the this is not known. ## Value Either a boolean stating if the device is a bot, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/isDesktop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isDesktop The read-only **`isDesktop`** property of the `Device` interface is either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ## Value Either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/isGameConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isGameConsole The read-only **`isGameConsole`** property of the `Device` interface is either a boolean stating if the device is a video game console, or `null` if the this is not known. ## Value Either a boolean stating if the device is a video game console, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/isMediaPlayer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMediaPlayer The read-only **`isMediaPlayer`** property of the `Device` interface is either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ## Value Either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/isMobile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMobile The read-only **`isMobile`** property of the `Device` interface is either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ## Value Either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/isSmartTV.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isSmartTV The read-only **`isSmartTV`** property of the `Device` interface is either a boolean stating if the device is a smart TV, or `null` if the this is not known. ## Value Either a boolean stating if the device is a smart TV, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/isTablet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTablet The read-only **`isTablet`** property of the `Device` interface is either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ## Value Either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/isTouchscreen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTouchscreen The read-only **`isTouchscreen`** property of the `Device` interface is either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ## Value Either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/model.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.model The read-only **`model`** property of the `Device` interface is either a string stating the model of the device, or `null` if the model is not known. ## Value Either a string value if a model is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.name The read-only **`name`** property of the `Device` interface is either a string stating the name of the device, or `null` if the name is not known. ## Value Either a string value if a name is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/device/Device/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toJSON The `toJSON()` method of the Device interface is a serializer; it returns a JSON representation of the Device object. To get a JSON string, you can use `JSON.stringify(device)` directly; it will call `toJSON()` automatically. ## Syntax ```js toJSON() ``` ### Return value A JSON object that is the serialization of the Device object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Dictionary()` :::info This Class is deprecated ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/edge-rate-limiter/EdgeRateLimiter/EdgeRateLimiter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `EdgeRateLimiter()` The **`EdgeRateLimiter` constructor** lets you open an epen a [ERL](https://docs.fastly.com/products/edge-rate-limiting) with the given ratecounter and penaltybox. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new EdgeRateLimiter(rateCounter, penaltyBox) ``` > **Note:** `EdgeRateLimiter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `rateCounter` _: RateCounter_ - The RateCounter instance to associate with this EdgeRateLimiter instance - `penaltyBox` _: PenaltyBox_ - The PenaltyBox instance which should be associated with this EdgeRateLimiter instance ### Return value A new `EdgeRateLimiter` object. ### Exceptions - `TypeError` - Thrown if the provided rateCounter value is not an instance of RateCounter - Thrown if the provided penaltyBox value is not an instance of PenaltyBox ================================================ FILE: documentation/versioned_docs/version-3.39.3/edge-rate-limiter/EdgeRateLimiter/prototype/checkRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EdgeRateLimiter.prototype.checkRate Increment an entry in the rate counter and check if the entry has exceeded some average number of requests per second (RPS) over the given window. If the entry is over the RPS limit for the window, add to the penaltybox for the given `timeToLive`. Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ## Syntax ```js checkRate(entry, delta, window, limit, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to increment and check - `delta` _: number_ - The amount to increment the `entry` by - `window` _: number_ - The time period to check across, has to be either 1 second, 10 seconds, or 60 seconds - `limit` _: number_ - The requests-per-second limit - `timeToLive` _: number_ - In minutes, how long the entry should be added into the penalty-box - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `true` if the entry has exceeded the average RPS for the window, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive finite number. - Thrown if the provided `window` value is not either, 1, 10, or 60. - Thrown if the provided `limit` value is not a positive finite number. - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.39.3/edge-rate-limiter/PenaltyBox/PenaltyBox.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `PenaltyBox()` The **`PenaltyBox` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for adding and checking if some entry is in the dataset. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new PenaltyBox(name) ``` > **Note:** `PenaltyBox()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a PenaltyBox with the given name ### Return value A new `PenaltyBox` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.3/edge-rate-limiter/PenaltyBox/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.add Add an `entry` into the PenaltyBox for the duration of the given `timeToLive`. ## Syntax ```js add(entry, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `timeToLive` _: number_ - In minutes, how long the entry should be added into the PenaltyBox - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.39.3/edge-rate-limiter/PenaltyBox/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.has Check if the given entry is contained in in the PenaltyBox instance. ## Syntax ```js has(entry) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up ### Return value Returns `true` if the entry is contained in the PenaltyBox instance, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.3/edge-rate-limiter/RateCounter/RateCounter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `RateCounter()` The **`RateCounter` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for counting and rate calculations. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new RateCounter(name) ``` > **Note:** `RateCounter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a RateCounter with the given name ### Return value A new `RateCounter` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.39.3/edge-rate-limiter/RateCounter/prototype/increment.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.increment Increment the given `entry` in the RateCounter instance with the given `delta` value. ## Syntax ```js increment(entry, delta) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `delta` _: number_ - The amount to increment the entry by ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive, finite number. ================================================ FILE: documentation/versioned_docs/version-3.39.3/edge-rate-limiter/RateCounter/prototype/lookupCount.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupCount Look up the current rate for the given `entry` and the given `duration`. ## Syntax ```js lookupCount(entry, duration) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `duration` _: number_ - The duration to lookup alongside the entry, has to be either, 10, 20, 30, 40, 50, or 60 seconds. ### Return value Returns a number which is the count for the given `entry` and `duration` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `duration` value is not either, 10, 20, 30, 40, 50 or 60. ================================================ FILE: documentation/versioned_docs/version-3.39.3/edge-rate-limiter/RateCounter/prototype/lookupRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupRate Look up the current rate for the given `entry` and the given `window`. ## Syntax ```js lookupRate(entry, window) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `window` _: number_ - The window to look up alongside the entry, has to be either 1 second, 10 seconds, or 60 seconds ### Return value Returns a number which is the rate for the given `entry` and `window` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `window` value is not either, 1, 10, or 60. ================================================ FILE: documentation/versioned_docs/version-3.39.3/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabledOrConfig` _: boolean_ - Whether or not to allow Dynamic Backends or - `enabledOrConfig` _: object_ - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to https://www.fastly.com/ and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/experimental/mapAndLogError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapAndLogError The **`mapAndLogError()`** function calls `mapError` on an `Error` object and sends the output to standard error. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapAndLogError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value `undefined`. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { mapAndLogError(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | mapAndLogError(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/experimental/mapError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapError The **`mapError()`** function extracts information from an `Error` object as a human-readable array of strings. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value Returns an array of `string`s. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { console.error(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | console.error(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/experimental/sdkVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sdkVersion The read-only **`sdkVersion`** property is a string whose indicates what JavaScript SDK version is being used. ## Value A string value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object`, or `null` if no geolocation data was found. The object contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Blob/Blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob() The **`Blob()`** constructor creates a `Blob` object, which represents a file-like object of immutable, raw data. ## Syntax ```js new Blob() new Blob(array) new Blob(array, options) ``` > **Note:** `Blob()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `array` _**optional**_ - : An array of values to include in the `Blob`. These can be [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx), [`Blob`](../../globals/Blob/Blob.mdx), or strings. If any of these elements is a [`Blob`](../../globals/Blob/Blob.mdx), its content (and not the object itself) is copied into the Blob being constructed. - `options` _**optional**_ - : An object containing optional attributes for the `Blob`. - `type` - : A string indicating the MIME type of the data. The default value is the empty string `""`. - `endings` - : A string indicating how to handle line endings in the data. This can be either `"transparent"` (default) to keep line endings unchanged, or `"native"` to convert line endings to the platform's native line endings (e.g., `\r\n` on Windows). ### Return value A new `Blob` object containing the specified data. ## Description `Blob` objects represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting its functionality and expanding it to support files on the user's system. To construct a `Blob` from other non-blob objects and data, use the `Blob()` constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](../../globals/Blob/prototype/slice.mdx) method. The `type` property of a `Blob` object will match the MIME type specified in the constructor's `options` parameter, defaulting to an empty string if not specified. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Blob/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.arrayBuffer() The **`arrayBuffer()`** method of the `Blob` interface returns a `Promise` that resolves with an `ArrayBuffer` containing the entire contents of the `Blob` as binary data. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A `Promise` that resolves with an `ArrayBuffer` containing the blob's data. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Blob/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.size The **`size`** read-only property of the `Blob` interface returns the size of the `Blob` in bytes. ## Value A number representing the size of the `Blob` in bytes. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Blob/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.slice() The **`slice()`** method of the `Blob` interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. ## Syntax ```js slice() slice(start) slice(start, end) slice(start, end, contentType) ``` ### Parameters - `start` _**optional**_ - : The 0-based index of the first byte to include in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is 0. - `end` _**optional**_ - : The 0-based index of the first byte that will not be included in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is `size`. - `contentType` _**optional**_ - : A string indicating the content type to assign to the new `Blob`. The default value is an empty string. ### Return value A new `Blob` object containing the specified subset of data. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Blob/prototype/stream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.stream() The **`stream()`** method of the `Blob` interface returns a `ReadableStream` that can be used to read the contents of the `Blob`. ## Syntax ```js stream() ``` ### Parameters None. ### Return value A `ReadableStream` that provides the data contained within the `Blob`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Blob/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.text() The **`text()`** method of the `Blob` interface returns a `Promise` that resolves with a string containing the contents of the blob, interpreted as UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a string containing the blob's data as a text string. The data is always interpreted as UTF-8. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Blob/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.type The **`type`** read-only property of the `Blob` interface returns the MIME type of the `Blob`. ## Value A string indicating the MIME type of the `Blob`. If the type cannot be determined, this returns an empty string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/EcKeyImportParams/EcKeyImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcKeyImportParams The **`EcKeyImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as ECDSA. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/EcdsaParams/EcdsaParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcdsaParams The **`EcdsaParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `hash` - : A string. An identifier for the digest algorithm to use. This should be one of the following: - `SHA-256`: selects the SHA-256 algorithm. - `SHA-384`: selects the SHA-384 algorithm. - `SHA-512`: selects the SHA-512 algorithm. > **Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. While these fields are always defined on Compute, they may be *null* when not available in testing environments such as Viceroy. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : Either `null`, or a [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. - `FetchEvent.client.tlsJA3MD5` _**readonly**_ - : Either `null` or a string representation of the JA3 hash of the TLS ClientHello message. - `FetchEvent.client.tlsCipherOpensslName` _**readonly**_ - : Either `null` or a string representation of the cipher suite used to secure the client TLS connection. - `FetchEvent.client.tlsProtocol` _**readonly**_ - : Either `null` or a string representation of the TLS protocol version used to secure the client TLS connection. - `FetchEvent.client.tlsClientCertificate` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw client certificate in the mutual TLS handshake message. It is in PEM format. Returns an empty ArrayBuffer if this is not mTLS or available. - `FetchEvent.client.tlsClientHello` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw bytes sent by the client in the TLS ClientHello message. - `FetchEvent.client.tlsJA4` _**readonly**_ - : Either `null` or a string representation of the JA4 fingerprint of the TLS ClientHello message. - `FetchEvent.client.h2Fingerprint` _**readonly**_ - : Either `null` or a string representation of the HTTP/2 fingerprint for HTTP/2 connections. Returns `null` for HTTP/1.1 connections. - `FetchEvent.client.ohFingerprint` _**readonly**_ - : Either `null` or a string representation of the Original Header fingerprint based on the order and presence of request headers. - `FetchEvent.server` _**readonly**_ - : Information about the server receiving the request for the Fastly Compute service. - `FetchEvent.server.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the server which received the request. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.sendEarlyHints()`](./prototype/sendEarlyHints.mdx) - : Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FetchEvent/prototype/sendEarlyHints.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.sendEarlyHints() The **`sendEarlyHints()`** method allows you to send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response back to the client which made the incoming request to your application. ## Syntax ```js sendEarlyHints(headers) ``` ### Parameters - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../Headers/Headers.mdx) object or object literal of [`String`](../../String/String.mdx) key/value pairs. ### Return value Always returns `undefined`. ### Examples ```js event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'] ]); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/FormData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData() The **`FormData()`** constructor creates a new `FormData` object. ## Syntax ```js new FormData() new FormData(form) ``` > **Note:** `FormData()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `form` _**optional**_ - : An HTML `` element — when specified, the `FormData` object will be populated with the form's current key/value pairs using the name property of each element for the keys and their submitted value for the values. File input elements are handled specially: their values are taken from the files selected by the user in the upload control. ### Return value A new `FormData` object, pre-populated with form data if the optional `form` parameter was provided. ## Description The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using methods such as `fetch()`. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also append additional data to the `FormData` object after it's created using its various methods. A `FormData` object can be used in a number of ways with other APIs: 1. It can be sent with the `fetch()` API 2. It works seamlessly with the `Request` and `Response` objects - it can be used directly as the body of a `Request` object 3. It can be obtained from a `Response` object using the `formData()` method 4. It can be passed directly to the `URLSearchParams` constructor The transmitted data is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to `"multipart/form-data"`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.append() The **`append()`** method of the `FormData` interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. ## Syntax ```js append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.delete() The **`delete()`** method of the `FormData` interface removes all key/value pairs with the given name from the `FormData` object. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.entries() The **`entries()`** method of the `FormData` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator yields a new array for each key/value pair, with the first element being the key and the second element being the value. ## Syntax ```js entries() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.forEach() The **`forEach()`** method of the `FormData` interface executes the provided callback function once for each key/value pair in the `FormData` object. ## Syntax ```js forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each entry in the object. The function will be passed the following arguments: - `value` - : The value of the current entry. - `key` - : The key of the current entry. - `formData` - : The `FormData` object being traversed. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.get() The **`get()`** method of the `FormData` interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the [`getAll()`](../../../globals/FormData/prototype/getAll.mdx) method instead. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value A `FormDataEntryValue` containing the value. If the key does not exist, it returns `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/prototype/getAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.getAll() The **`getAll()`** method of the `FormData` interface returns all the values associated with a given key from within a `FormData` object. ## Syntax ```js getAll(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value An array of `FormDataEntryValue` items containing all values with the given key. If the key doesn't exist, an empty array is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.has() The **`has()`** method of the `FormData` interface returns a boolean indicating whether a `FormData` object contains a key/value pair with the given name. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the key you want to test for existence. ### Return value `true` if a key/value pair with the specified name exists; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.keys() The **`keys()`** method of the `FormData` interface returns an iterator allowing iteration through all keys contained in this object. The iterator yields the key for each value. ## Syntax ```js keys() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.set() The **`set()`** method of the `FormData` interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and [`append()`](../../../globals/FormData/prototype/append.mdx) is that if the specified key already exists, `set()` overwrites all existing values with the new one, whereas `append()` appends the new value onto the end of the existing values. ## Syntax ```js set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/FormData/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.values() The **`values()`** method of the `FormData` interface returns an iterator allowing iteration through all values contained in this object. The iterator yields the value for each key/value pair. ## Syntax ```js values() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name is not the name of an HTTP header, this method throws a `TypeError`. The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/prototype/getSetCookie.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.getSetCookie() The **`getSetCookie()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns an array of all the values of the `Set-Cookie` headers, returning an empty list if none are present. ## Syntax ```js getSetCookie() ``` ### Return value `String[]` representing the list of `Set-Cookie` headers. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2 or greater than π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex where x is a number very close to 0, you should get an answer very close to 1 + x, because limx0ex1x=1. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, a `ReadableStream` object, a [`Blob`](../../globals/Blob/Blob.mdx) object, or a [`FormData`](../../globals/FormData/FormData.mdx) object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_, see [`CacheOverride`](../../fastly:cache-override/CacheOverride/CacheOverride.mdx). - `cacheKey` _**Fastly-specific**_ - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.blob() The **`blob()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/clone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.clone() The **`clone()`** method of the `Request` interface creates a copy of the current `Request` object. Like the underlying `ReadableStream.tee`` api, the `body` of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Beware when you construct a `Request` from a stream and then `clone` it. `clone()` throws a `TypeError` if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) If you intend to modify the request, you may prefer the `Request` constructor. ## Syntax ```js clone() ``` ### Parameters None. ### Return value A `Request` object, which is an exact copy of the `Request` that `clone()` was called on. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.formData() The **`formData()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. - `SyntaxError` - : Thrown if the request's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Request` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Request instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - [`Blob`](../../globals/Blob/Blob.mdx) - [`FormData`](../../globals/FormData/FormData.mdx) - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.blob() The **`blob()`** method of the [`Response`](../Response.mdx) interface takes a [`Response`](../Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.formData() The **`formData()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. - `SyntaxError` - : Thrown if the response's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/ip.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ip The **`ip`** getter of the `Response` interface returns the IP address associated with the request, as either an IPv6 or IPv4 string. In the case where no IP address is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with an IP, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `string`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.port The **`port`** getter of the `Response` interface returns the port associated with the request, as a number. In the case where no port is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with a port, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `number`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Response` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Response instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - For ECDSA: Pass an [`EcKeyImportParams`](../../EcKeyImportParams/EcKeyImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](https://en.wikipedia.org/wiki/HZ_(character_encoding)). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Explicit Backends Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service. This `backend` option is then a special Fastly-specific fetch option that is provided to the `fetch()` call: ```js fetch('https://origin.com/path', { backend: 'origin' }); ``` Backends are configured using the Fastly service backend configuration, see the [Backend documentation](https://developer.fastly.com/reference/api/services/backend/) for more information. ## Dynamic Backends Dynamic backends are a compute feature that allow services to define backends for themselves. If the `backend` option is not provided when making `fetch()` requests, a backend will be automatically created by extracting the protocol, host, and port from the provided URL. In addition, custom backend configuration options can then also be provided through the [`Backend()`](../fastly:backend/Backend/Backend.mdx) constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ - `imageOptimizerOptions` _**Fastly-specific**_, see [`imageOptimizerOptions`](../fastly:image-optimizer/imageOptimizerOptions.mdx). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-3.39.3/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/after.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # after The `after` method inserts content after the closing tag of the element. ## Syntax ```js element.after(content); element.after(content, options); ``` ### Parameters - `content` _: string_ - The content to insert after the element's closing tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.after("World"); // Result:
Hello
World ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # append The `append` method inserts content at the end of the element's content. ## Syntax ```js element.append(content); element.append(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the end of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.append(", World"); // Result:
Hello, World
``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/before.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # before The `before` method inserts content before the opening tag of the element. ## Syntax ```js element.before(content); element.before(content, options); ``` ### Parameters - `content` _: string_ - The content to insert before the element's opening tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.before("Well"); // Result: Well
Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/hasAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # hasAttribute The `hasAttribute` method returns a `boolean` value indicating whether the specified attribute is present on the element. ## Syntax ```js element.hasAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to check for. ### Return value A boolean value indicating whether the attribute is present. ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/prepend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # prepend The `prepend` method inserts content at the beginning of the element's content. ## Syntax ```js element.prepend(content); element.prepend(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the beginning of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.prepend("Well, "); // Result:
Well, Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/removeAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # removeAttribute The `removeAttribute` method removes the specified attribute from the element. ## Syntax ```js element.removeAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to remove. ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/replaceChildren.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceChildren The `replaceChildren` method replaces the element's children with new content. ## Syntax ```js element.replaceChildren(content); element.replaceChildren(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element's children with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceChildren("Greetings!"); // Result:
Greetings!
``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/replaceWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceWith The `replaceWith` method replaces the element with new content. ## Syntax ```js element.replaceWith(content); element.replaceWith(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceWith("

Greetings!

"); // Result:

Greetings!

``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/selector.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # selector The `selector` read-only property is a `string` representing the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) that matches the element. ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/setAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setAttribute The `setAttribute` method sets the value of the specified attribute on the element. If the value already exists, it will be updated; otherwise, a new attribute with the specified name and value will be added to the element. ## Syntax ```js element.setAttribute(attributeName, value); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to set. - `value` _: string_ - The value to assign to the attribute. ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/Element/prototype/tag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # tag The `tag` read-only property is a `string` representing the tag name of the element. ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/HTMLRewritingStream/HTMLRewritingStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `HTMLRewritingStream()` The **`HTMLRewritingStream`** lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback. This callback can manipulate the attributes of the element, and add or remove content from the immediate context. ## Syntax ```js new HTMLRewritingStream() ``` ### Return value A new `HTMLRewritingStream` object. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/html-rewriter/HTMLRewritingStream/prototype/onElement.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # onElement ▸ **onElement**`(selector: string, handler: (element: Element) => void): this` Registers an element handler with the [`HTMLRewritingStream`] that will be called for each [`Element`] that matches the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) `selector`. Elements added by handlers will not be processed by other handlers. ## Syntax ```js .onElement(selector, handler) ``` ### Parameters - `selector` _: string_ - A CSS selector that determines the elements for which `handler` will be called - The following types of CSS selector are supported: Currently the rewriter supports the following CSS selectors: | Pattern | Description | |----------------------|----------------------------------------------------------------------------| | `*` | Any element | | `E` | All elements of type `E` | | `E F` | `F` elements inside `E` elements | | `E > F` | `F` elements directly inside `E` elements | | `E:nth-child(n)` | The n-th child of type `E` | | `E:first-child` | First child of type `E` | | `E:nth-of-type(n)` | The n-th sibling of type `E` | | `E:first-of-type` | First sibling of type `E` | | `E:not(s)` | Type `E` elements not matching selector `s` | | `E.myclass` | Type `E` elements with class `"myclass"` | | `E#myid` | Type `E` elements with ID `"myid"` | | `E[attr]` | Type `E` elements with attribute `attr` | | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | | `E[attr="val" i]` | Type `E` elements where `attr` is `"val"`, case-insensitive | | `E[attr="val" s]` | Type `E` elements where `attr` is `"val"`, case-sensitive | | `E[attr~="val"]` | Type `E` elements where `attr` contains `"val"` in a space-separated list | | `E[attr`|`;="val"]`| Type `E` elements where `attr` is hyphen-separated and starts with `"val"` | | `E[attr^="val"]` | Type `E` elements where `attr` starts with `"val"` | | `E[attr$="val"]` | Type `E` elements where `attr` ends with `"val"` | | `E[attr*="val"]` | Type `E` elements where `attr` contains `"val"` | - `handler` _: (element: Element) => void_ - A callback function that will be called once for each element that matches `selector` ### Return value The `HTMLRewritingStream`, so multiple calls to `onElement` can be chained. ### Exceptions - `Error` - If the provided `selector` is not a valid CSS selector. - If the provided `handler` is not a function. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/Auto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Auto` Enumerator options for [`imageOptimizerOptions.auto`](./imageOptimizerOptions.mdx). ## Constants - `AVIF` (`"avif"`) If the browser's Accept header indicates compatibility, deliver an AVIF image. - `WEBP` (`"webp"`) If the browser's Accept header indicates compatibility, deliver a WebP image. ## Examples ```js import { Auto, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, auto: Auto.AVIF }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/BWAlgorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `BWAlgorithm` Enumerator options for [`imageOptimizerOptions.bw`](./imageOptimizerOptions.mdx). ## Constants - `Threshold` (`"threshold"`) Uses a luminance threshold to convert the image to black and white. - `Atkinson` (`"atkinson"`) Uses [Atkinson dithering](https://en.wikipedia.org/wiki/Atkinson_dithering) to convert the image to black and white. ## Examples ```js import { Region, BWAlgorithm } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, bw: BWAlgorithm.Threshold }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/CropMode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CropMode` Enumerator options for [`imageOptimizerOptions.crop.mode`](./imageOptimizerOptions.mdx) and `imageOptimizerOptions.precrop.mode`. ## Constants - `Smart` (`"smart"`) Enables content-aware algorithms to attempt to crop the image to the desired aspect ratio while intelligently focusing on the most important visual content, including the detection of faces. - `Safe` (`"safe"`) Allow cropping out-of-bounds regions. ## Examples ```js import { CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Smart, } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/Disable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Disable` Enumerator options for [`imageOptimizerOptions.disable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Prevent images being resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Disable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, disable: Disable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/Enable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Enable` Enumerator options for [`imageOptimizerOptions.enable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Allow images to be resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Enable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, enable: Enable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/Fit.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Fit` Enumerator options for [`imageOptimizerOptions.fit`](./imageOptimizerOptions.mdx). ## Constants - `Bounds` (`"bounds"`) Resize the image to fit entirely within the specified region, making one dimension smaller if needed. - `Cover` (`"cover"`) Resize the image to entirely cover the specified region, making one dimension larger if needed. - `Crop` (`"crop"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Fit, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 150, height; 150, fit: Fit.Bounds }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/Format.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Format` Enumerator options for [`imageOptimizerOptions.format`](./imageOptimizerOptions.mdx). ## Constants - `Auto` (`"auto"`) Automatically use the best format based on browser support and image/transform characteristics - `AVIF` (`"avif"`) AVIF - `BJPG` (`"bjpg"`) Baseline JPEG - `GIF` (`"gif"`) Graphics Interchange Format - `JPG` (`"jpg"`) JPEG - `JXL` (`"jxl"`) JPEGXL - `MP4` (`"mp4"`) MP4 (H.264) - `PJPG` (`"pjpg"`) Progressive JPEG - `PJXL` (`"pjxl"`) Progressive JPEGXL - `PNG` (`"png"`) Portable Network Graphics - `PNG8` (`"png8"`) Portable Network Graphics palette image with 256 colors and 8-bit transparency - `SVG` (`"svg"`) Scalable Vector Graphics - `WEBP` (`"webp"`) WebP - `WEBPLL` (`"webpll"`) WebP (Lossless) - `WEBPLY` (`"webply"`) WebP (Lossy) ## Examples ```js import { Format, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/Metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Metadata` Enumerator options for [`imageOptimizerOptions.metadata`](./imageOptimizerOptions.mdx). ## Constants - `Copyright` (`"copyright"`) Preserve [copyright notice](https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#copyright-notice), creator, credit line, licensor, and web statement of rights fields. - `C2PA` (`"c2pa"`) Preserve the [C2PA manifest](https://c2pa.org/) and add any transformations performed by Fastly Image Optimizer. - `CopyRightAndC2PA` (`"copyright,c2pa"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Metadata, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, metadata: Metadata.Copyright }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/Optimize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Optimize` Enumerator options for [`imageOptimizerOptions.optimize`](./imageOptimizerOptions.mdx). ## Constants - `Low` (`"low"`) Output image quality will be similar to the input image quality. - `Medium` (`"medium"`) More optimization is allowed. We attempt to preserve the visual quality of the input image. - `High` (`"high"`) Minor visual artifacts may be visible. This produces the smallest file. ## Examples ```js import { Optimize, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, optimize: Optimize.High }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/Orient.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Orient` Enumerator options for [`imageOptimizerOptions.orient`](./imageOptimizerOptions.mdx). ## Constants - `Default` (`"1"`) - `FlipHorizontal` (`"2"`) - `FlipHorizontalAndVertical` (`"3"`) - `FlipVertical` (`"4"`) - `FlipHorizontalOrientLeft` (`"5"`) - `OrientRight` (`"6"`) - `FlipHorizontalOrientRight` (`"7"`) - `OrientLeft` (`"8"`) ## Examples ```js import { Orient, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, orient: Orient.FlipHorizontal }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/Profile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Profile` Enumerator options for [`imageOptimizerOptions.profile`](./imageOptimizerOptions.mdx). ## Constants - `Baseline` (`"baseline"`) The profile recommended for video conferencing and mobile applications. (Default) - `Main` (`"main"`) The profile recommended for standard-definition broadcasts. - `High` (`"high"`) The profile recommended for high-definition broadcasts. ## Examples ```js import { Profile, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, profile: Profile.Main }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/Region.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Region` Enumerator options for [`imageOptimizerOptions.region`](./imageOptimizerOptions.mdx). ## Constants - `UsEast` (`"us_east"`) - `UsCentral` (`"us_central"`) - `UsWest` (`"us_west"`) - `EuCentral` (`"eu_central"`) - `EuWest` (`"eu_west"`) - `Asia` (`"asia"`) - `Australia` (`"australia"`) ## Examples ```js import { Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/ResizeFilter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ResizeFilter` Enumerator options for [`imageOptimizerOptions.resizeFilter`](./imageOptimizerOptions.mdx). ## Constants - `Nearest` (`"nearest"`) Uses the value of nearby translated pixel values. - `Bilinear` (`"bilinear"`) Uses an average of a 2x2 environment of pixels. - `Linear` (`"linear"`) Same as `Bilenear`. - `Bicubic` (`"bicubic"`) Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. - `Cubic` (`"cubic"`) Same as `Bicubic`. - `Lanczos2` (`"lanczos2"`) Uses the Lanczos filter to increase the ability to detect edges and linear features within an image and uses sinc resampling to provide the best possible reconstruction. - `Lanczos3` (`"lanczos3"`) Lanczos3 uses a better approximation of the sinc resampling function. (Default) - `Lanczos` (`"lanczos"`) Same as `Lanczos3`. ## Examples ```js import { ResizeFilter, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, resizeFilter: ResizeFilter.Linear }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/image-optimizer/imageOptimizerOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `imageOptimizerOptions` Options specified in the [`Request`](../globals/Request/Request.mdx) constructor for running the [Fastly Image Optimizer](https://docs.fastly.com/products/image-optimizer). More detailed documentation on all Image Optimizer options is available in the [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/). ## Parameters All parameters other than `region` are optional. - `region`: _[`Region`](./Region.mdx)_ Where image optimizations should occur. - `auto`: _[`Auto`](./Auto.mdx)_ Enable optimization features automatically. - `bgColor`: _[`Color`](#color)_ Set the background color of an image. - `blur`: _`number` (0.5-1000) or [`Percentage`](#percentage)_ Set the blurriness of the output image. - `brightness`: _`number` (-100-100)_ Set the brightness of the output image. - `bw`: _[`BWAlgorithm`](./BWAlgorithm.mdx)_ Convert an image to black and white. - `canvas`: _`Object`_ Increase the size of the canvas around an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `contrast`: _`number` (-100-100)_ Set the contrast of the output image. - `crop`: _`Object`_ Remove pixels from an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `mode` (optional): _[`CropMode`](./CropMode.mdx)_ - `disable`: _[`Disable`](./Disable.mdx)_ Disable functionality that is enabled by default. - `dpr`: `number` Ratio between physical pixels and logical pixels. - `enable`: _[`Enable`](./Enable.mdx)_ Enable functionality that is disabled by default. - `fit`: _[`Fit`](./Fit.mdx)_ Set how the image will fit within the size bounds provided. - `format`: _[`Format`](./Format.mdx)_ Specify the output format to convert the image to. - `frame`: _`number` (must have the value 1)_ Extract the first frame from an animated image sequence. - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the height of the image. - `level`: _`String` containing one of the [allowed values](https://www.fastly.com/documentation/reference/io/level/#allowed-values)_ Specify the level constraints when converting to video. - `metadata`: _[`Metadata`](./Metadata.mdx)_ Control which metadata fields are preserved during transformation. - `optimize`: _[`Optimize`](./Optimize.mdx)_ Automatically apply optimal quality compression. - `orient`: _[`Orient`](./Orient.mdx)_ Change the cardinal orientation of the image. - `pad`: _[`Sides`](#sides)_ Add pixels to the edge of an image. - `precrop`: _`Object`_ Remove pixels from an image before any other transformations occur. - `size`: _[`Size`](#size)_ - `position`: _[`Position`](#position)_ - `mode`: _[`CropMode`](./CropMode.mdx)_ - `profile`: _[`Profile`](./Profile.mdx)_ Specify the profile class of application when converting to video. - `quality`: _`integer` (1-100)_ Optimize the image to the given compression level for lossy file formatted images. - `resizeFilter`: _[`ResizeFilter`](./ResizeFilter.mdx)_ Specify the resize filter used when resizing images. - `saturation`: _`number` (-100-100)_ Set the saturation of the output image. - `sharpen`: _`Object`_ Set the sharpness of the output image. - `amount`: _`number` (0-10)_ - `radius`: _`number` (0.5-1000)_ - `threshold`: _`integer` (0-255)_ - `trim`: _[`Sides`](#sides)_ Remove pixels from the edge of an image. - `viewbox`: _`number` (must have the value 1)_ Remove explicit width and height properties in SVG output. - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the width of the image. ## Types ### Color Either: - a 3 or 6 character hexadecimal string - an `Object` containing: - `r`: _`integer` (0-255)_ Red component - `g`: _`integer` (0-255)_ Green component - `b`: _`integer` (0-255)_ Blue component - `a` (optional): _`number` (0.0-1.0)_ Alpha component ### Percentage A `String` containing a number suffixed with a percent sign (%). ### Position An `Object` containing: - Exactly one of: - `x`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetX`: _`number` (interpreted as a percentage)_ - Exactly one of: - `y`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetY`: _`number` (interpreted as a percentage)_ ### Sides An `Object` containing `top`, `bottom`, `left`, and `right`, all of which are either an `integer` or [`Percentage`](#percentage). ### Size An `Object` containing either: - `absolute`: _`Object`_ - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `ratio`: _`Object`_ - `width`: _`number`_ - `height`: _`number`_ ## Examples ```js import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG, bgColor: { 'r': 100, 'g': 255, 'b': 9, 'a': 0.5 }, blur: '1%', brightness: -20, contrast: -20, height: 600, level: '4.0', orient: Orient.FlipVertical, saturation: 80, sharpen: { 'amount': 5, 'radius': 6, 'threshold': 44 }, canvas: { 'size': { 'absolute': { 'width': 400, 'height': 400 } } }, crop: { size: { absolute: { width: 200, height: 200 }, mode: CropMode.Safe } }, trim: { top: 10, left: 10, right: 10, bottom: 10 }, pad: { top: 30, left: 30, right: "1%", bottom: 30 } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a KV store instance using the resource link name. ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStore/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.delete Deletes the value associated with the key `key` in the KV store. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value Returns `undefined` ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - Does not exist ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then delete the entry. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') await files.delete('hello') const entry = await files.get('hello') if (entry) { return new Response(await entry.text()) } else { return new Response('no file named hello exists') } } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStore/prototype/list.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.list The **`list()`** can be used to list the keys of a store. ## Syntax ```js list(options?) ``` ### Parameters - `options` _: object_ _**optional**_ - List options supporting properties: - `cursor` _: string_ _**optional**_ - The cursor used to pick up from a previous iteration. - `limit` _: number_ _**optional**_ - The maximum number of keys to return. - `prefix` _: string_ _**optional**_ - List only those keys that start with the given string prefix. - `noSync` _: boolean_ _**optional**_ - Do not sync the key list first, instead provide a possibly out-of-date listing. May be faster but inconsistent. ### Return value Returns a `Promise` which resolves with `{ list: string[], cursor: string | undefined }`. ## Example In this example we list the keys of a KV Store named `'files'`, iterating 10 at a time, counting the total; ```js /// import { KVStore } from 'fastly:kv-store'; async function app(event) { const files = new KVStore('files'); let cursor, list, total = 0; do { ({ cursor, list } = await files.list({ limit: 10, cursor })); total += list?.length; } while (list); return new Response(`Iterated ${total} entries`); } addEventListener('fetch', (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value, options?) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. - `options` _: object_ _**optional**_ - An insert options parameter, supporting: - `metadata` _: ArrayBuffer | TypedArray | DataView_ _**optional**_ - Binary metadata associated with the entry, may be up to 1000 bytes. - `ttl` _: number_ _**optional**_ - TTL for the entry - `mode` _: 'overwrite' | 'add' | 'append' | 'prepend'_ _**optional**_ - Insert mode, defaults to 'overwrite' - `gen` _: number_ _**optional**_ - 'generation' header specific to the version of an entry key ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - `TypeError` - If the provided `gen`: - Is not an number ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStoreEntry/prototype/metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadata() The `metadata()` method of the `KVStoreEntry` interface provides the binary metadata associated with the `KVStoreEntry`. The metadata binary may be up to 1000 bytes, and is returned as a `Uint8Array` TypedArray buffer, if metadata is set, or null otherwise. ## Syntax ```js metadata() ``` ### Parameters None. ### Return value A `Promise` that resolves to a `Uint8Array` buffer object. ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStoreEntry/prototype/metadataText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadataText() The `metadataText()` method of the `KVStoreEntry` interface provides a String interpretation of binary metadata associated with the `KVStoreEntry`. If the binary data is not a valid string, an encoding error will be thrown. ## Syntax ```js metadataText() ``` ### Parameters None. ### Return value A `Promise` that resolves to a String. ================================================ FILE: documentation/versioned_docs/version-3.39.3/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; const logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; let logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/logger/configureConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # configureConsole The **`configureConsole()`** function allows configuring the behaviour of the `console` global JS logger. ## Syntax ```js configureConsole(loggingOptions) ``` ### Parameters - `loggingOptions` _: object_ - - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ## Examples In this example, we disable prefixing for `console.log` and use `stderr` output for `console.error`: ```js import { configureConsole } from "fastly:logger"; configureConsole({ prefixing: false, stderr: true }); async function handleRequest(event) { console.log(JSON.stringify(event.request.headers)); const url = new URL(event.request.url); try { validate(url); } catch (e) { console.error(`Validation error: ${e}`); return new Response('Bad Request', { status: 400 }); } return new Response('OK'); } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v2 to v3` ## SimpleCache.delete renamed to SimpleCache.purge and requires purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using `SimpleCache.delete` to `SimpleCache.purge` with the same purging behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a Secret Store instance using the resource link name. ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/secret-store/SecretStore/fromBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fromBytes The **`fromBytes()`** function is used to create an in-memory secret from an array buffer. >**Note**: This API should be avoided when possible, by instead using [SecretStore.prototype.get](./prototype/get.mdx) to obtain secure secrets. ## Syntax ```js fromBytes(new Uint8Array([1, 2, 3])) ``` ### Parameters None. ### Return value Returns a `SecretStoreEntry`. ================================================ FILE: documentation/versioned_docs/version-3.39.3/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/secret-store/SecretStoreEntry/prototype/rawBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.rawBytes ▸ **rawBytes**(): `Uint8Array` Returns the raw byte contents of the SecretStoreEntry instance as a Uint8Array. ## Syntax ```js rawBytes() ``` ### Parameters None. ### Return value A Uint8Array ### Exceptions The `rawBytes()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ================================================ FILE: documentation/versioned_docs/version-3.39.3/security/inspect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # inspect The **`inspect()`** function inspects a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). ## Syntax ```js inspect(request, config); ``` ### Parameters - `request` _: Request_ - The Request to get a WAF determination for. - `config` _: object_ - `corp` _: string_ - Set a corp name for the configuration. - This parameter is currently required. - `workspace` _: string_ - Set a workspace name for the configuration. - This parameter is currently required. - `overrideClientIp` _: string_ - Specify an explicit client IP address to inspect. - By default, `inspect` will use the IP address that made the request to the running Compute service, but you may want to use a different IP when service chaining or if requests are proxied from outside of Fastly’s network. ### Return value Returns an `Object` with the `inspect` response, with the following fields: - `waf_response` _: number_ - Security status code. - `redirect_url` _: string | null_ - A redirect URL returned from Security. - `tags` _: string[]_ - Tags returned by Security. - `verdict` _: string_ - The outcome of inspecting a request with Security. It can be one of the following: - `"allow"` - Security indicated that this request is allowed. - `"block"` - Security indicated that this request should be blocked. - `"unauthorized"` - Security indicated that this service is not authorized to inspect a request. - Other verdicts may be returned but not currently documented. - `decision_ms` _: number_ - How long Security spent determining its verdict, in milliseconds. ## Examples ```js /// import { inspect } from "fastly:security"; async function app(event) { const res = inspect(event.request, { corp: "mycorp", workspace: "myws" }); switch (res.verdict) { case "allow": return await fetch(event.request); case "block": return new Response("Request Blocked", { status: 400 }); case "unauthorized": return new Response("Unauthorized", { status: 401 }); default: return new Response("idk", { status: 500 }); } } addEventListener("fetch", (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/shielding/Shield/Shield.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Shield()` Load information about the given shield. Returns an object representing the shield if it is active, or throws an exception if the string is malformed or the shield doesn’t exist. Shield names are defined on [this webpage](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations), in the “shield code” column. For example, the string “pdx-or-us” will look up our Portland, OR, USA shield site, while “paris-fr” will look up our Paris site. If you are using a major cloud provider for your primary origin site, consider looking at the “Recommended for” column, to find the Fastly POP most closely located to the given cloud provider. ## Syntax ```js new Shield(name) ``` > **Note:** `Shield()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Exceptions - `TypeError` - Thrown if no Shield exists with the provided name ## Examples In this example, we create a Shield instance for the Sydney, Australia shield POP. If the code is running on that shield POP, it fetches directly from origin. Otherwise, it routes the request through the shield using an encrypted connection. ```js /// import { Shield } from "fastly:shielding"; async function app(event) { const shield = new Shield('wsi-australia-au'); // If running on the shield POP, fetch from the origin directly if (shield.runningOn()) { return await fetch('https://http-me.fastly.com/anything', { backend: 'httpme' }); } // Otherwise, route the request through the shield using an encrypted connection return await fetch(event.request, { backend: shield.encryptedBackend() }); } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.39.3/shielding/Shield/prototype/encryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.encryptedBackend ▸ **encryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an encrypted connection to the POP. For reference, this is almost always the backend that you want to use. Only use [`Shield::unencryptedBackend`](./unencryptedBackend.mdx) in situations in which you are 100% sure that all the data you will send and receive over the backend is already encrypted. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.39.3/shielding/Shield/prototype/runningOn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.runningOn ▸ **runningOn**(): `boolean` Returns whether we are currently operating on the given shield. Technically, this may also return true in very isolated incidents in which Fastly is routing traffic from the target shield POP to the POP that this code is running on, but in these situations the results should be approximately identical. (For example, it may be the case that you are asking to shield to ‘pdx-or-us’. But, for load balancing, performance, or other reasons, Fastly is temporarily shifting shielding traffic from Portland to Seattle. In that case, this function may return true for hosts running on ‘bfi-wa-us’, our Seattle site, because effectively the shield has moved to that location. This should give you a slightly faster experience than the alternative, in which this function would return false, you would try to forward your traffic to the Portland site, and then that traffic would be caught and redirected back to Seattle.) ================================================ FILE: documentation/versioned_docs/version-3.39.3/shielding/Shield/prototype/unencryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.unencryptedBackend ▸ **unencryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an unencrypted connection to the POP. Generally speaking, we encourage users to use [`Shield::encryptedBackend`](./encryptedBackend.mdx) instead of this function. Data sent over this backend – the unencrypted version – will be sent over the open internet, with no protections. In most cases, this is not what you want. However, in some cases – such as when you want to ship large data blobs that you know are already encrypted — using these backends can prevent a double-encryption performance penalty. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.39.3/websocket/createWebsocketHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createWebsocketHandoff The **`createWebsocketHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Websocket, to the declared backend. ## Syntax ```js createWebsocketHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Websocket. - `backend` _: string_ - The name of the backend that Websocket should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Websocket. ```js import { createWebsocketHandoff } from "fastly:websocket"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createWebsocketHandoff(event.request, 'websocket_backend'); } else { return new Response('oopsie, make a request to /stream for some websocket goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/acl/Acl/open.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.open() Opens the ACL with the given name, returning a new `Acl` instance with the given name on success. ## Syntax ```js Acl.open(name) ``` ### Return value An `Acl` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.0/acl/Acl/prototype/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.prototype.lookup() The **`lookup(ipAddress)`** method returns the name associated with the `Acl` instance. ## Syntax ```js acl.lookup(ipAddress) ``` ### Parameters - `ipAddress` _: string_ - IPv4 or IPv6 address to lookup ### Return value An Object of the form `{ action: 'ALLOW' | 'BlOCK', prefix: string }`, where `prefix` is the IP address prefix that was matched in the ACL. ## Example ```js /// import { Acl } from 'fastly:acl'; addEventListener('fetch', async (evt) => { const myAcl = Acl.open('myacl'); const match = await myAcl.lookup(evt.client.address); evt.respondWith(new Response(match?.action === 'BLOCK' ? 'blocked' : 'allowed')); }); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. >**Note**: Dynamic backends are by default disabled at the Fastly service level. Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request dynamic backends on Fastly Services. To disable the usage of dynamic backends, see [enforceExplicitBackends](../enforceExplicitBackends.mdx). ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. - `grpc` _: boolean_ _**optional**_ - **_Experimental feature_** - When enabled, sets that this backend is to be used for gRPC traffic. - _Warning: When using this experimental feature, no guarantees are provided for behaviours for backends that do not provide gRPC traffic._ All optional generic options can have their defaults set via [`setDefaultDynamicBackendConfig()`](../setDefaultDynamicBackendConfig.mdx). This includes all configuration options above except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. ### Return value A new `Backend` object. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/exists.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.exists() The **`Backend.exists()`** method returns a boolean indicating if a Backend with the given name exists or not. ## Syntax ```js exists(name) ``` ### Return value A boolean indicating if a Backend with the given name exists or not. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/fromName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.fromName() Returns the `Backend` instance with the given name, if one exists. If one does not exist, an error is thrown. ## Syntax ```js fromName(name) ``` ### Return value A `Backend` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.health() :::info This method is deprecated, use [`Backend.prototype.health`](./prototype/health.mdx) instead. ::: The **`Backend.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js Backend.health(backend) ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/betweenBytesTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.betweenBytesTimeout The read-only **`betweenBytesTimeout`** property of a `Backend` instance is an integer number providing the between bytes timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/connectTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.connectTimeout The read-only **`connectTimeout`** property of a `Backend` instance is an integer number providing the connect timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/firstByteTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.firstByteTimeout The read-only **`firstByteTimeout`** property of a `Backend` instance is an integer number providing the first byte timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.health() The **`Backend.prototype.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js health() ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/hostOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.hostOverride The read-only **`hostOverride`** property of a `Backend` instance is the host header override string used when sending requests to this backend. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/httpKeepaliveTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.httpKeepaliveTime The read-only **`httpKeepaliveTime`** property of a `Backend` instance is the HTTP keepalive time for this backend in milliseconds, or 0 if no keepalive is set. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/isDynamic.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isDynamic The read-only **`isDynamic`** property of a `Backend` instance is a boolean indicating if the backend was dynamically created for this service. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/isSSL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isSSL The read-only **`isSSL`** property of a `Backend` instance is a boolean indicating if the backend is using an SSL connection. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # name The read-only **`name`** property of the backend returns the backend name string. ## Value A `string`. ## Description Provides the name of the backend. ## Examples ### Using name The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.port The read-only **`port`** property of a `Backend` instance is the port number of this backend. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/target.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.target The read-only **`target`** property of a `Backend` instance is the host string this backend is configured to use. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/tcpKeepalive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tcpKeepalive The read-only **`tcpKeepalive`** property of a `Backend` instance returns an object providing the TCP keepalive configuration, if any, otherwise returning `null` if TCP keepalive is not enabled. This object has the following properties: - `timeSecs` _: number or null._ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number or null._ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number or null._ - Number of probes to send to the backend before it is considered dead. ## Value A `Object` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/tlsMaxVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMaxVersion The read-only **`tlsMaxVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/tlsMinVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMinVersion The read-only **`tlsMinVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/toName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.toName() :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toName()`** method returns the name associated with the `Backend` instance. ## Syntax ```js toName() ``` ### Return value A string which contains the name of the Backend. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toString :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends :::info This method is deprecated, and dynamic backends are now always supported when enabled at the service level. See [`enforceExplicitBackends`](./enforceExplicitBackends.mdx) instead. ::: The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: By default, while dynamic backends are allowed in the SDK, they are by default disabled at the Fastly service level. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/enforceExplicitBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enforceExplicitBackends Call this function to enforce the security property of explicitly-defined backends, even when dynamic backends are enabled at the Fastly service level. By default, if dynamic backends are supported for the Fastly service, they will be automatically used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a potential security concern since third-party JavaScript code may send arbitrary requests, including sensitive/secret data, off to destinations that the JavaScript project was not intending. When calling this function, an optional default backend name can be provided. >**Note**: This is a separate option to the service-level dynamic backend support for Fastly services, which is by deault disabled for Fastly services. The **`enforceExplicitBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: Dynamic Backends are disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled or disabled on Fastly Services. ## Syntax ```js enforceExplicitBackends(defaultBackend?) ``` ### Parameters - `defaultBackend` _: string_ _**optional**_ - An optional default backend string name to use in `fetch()` requests. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/backend/setDefaultDynamicBackendConfig.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setDefaultDynamicBackendConfig() The **`setDefaultDynamicBackendConfig()`** allows setting backend configuration defaults that should apply to any newly created dynamic backends via the `new Backend()` constructor. ### Parameters - `defaultDynamicBackendConfig` - : An Object which contains the generic configuration options to apply to newly created Backends. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. ## Syntax ```js setDefaultDynamicBackendConfig(defaultConfig) ``` ### Return value None. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, with timeouts and TLS options provided from the default backend configuration options. import { allowDynamicBackends } from "fastly:experimental"; import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! // Timeouts and TLS configuration still get set from the default backend configuration above. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.age The **`age`** method of the `CacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.body The **`body`** method of the `CacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this `CacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.close The **`close`** method of the `CacheEntry` interface closes the connection to the cache for this `CacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.hits The **`hits`** method of the `CacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.length The **`length`** method of the `CacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.maxAge The **`maxAge`** method of the `CacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `CacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.state The **`state`** method of the `CacheEntry` interface returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.userMetadata The **`userMetadata`** method of the `CacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheState/found.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.found The **`found`** method of the `CacheState` interface returns `true` if a cached item was located. Even if an cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. ## Syntax ```js found() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item was located or not. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheState/mustInsertOrUpdate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.mustInsertOrUpdate The **`mustInsertOrUpdate`** method of the `CacheState` interface returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. ## Syntax ```js mustInsertOrUpdate() ``` ### Parameters None. ### Return value A `boolean` which represents whether a fresh cached item was found not. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheState/stale.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.stale The **`stale`** method of the `CacheState` interface returns `true` if the cached item is stale. A cached item is stale if its age is greater than its `maxAge` period. ## Syntax ```js stale() ``` ### Parameters None. ### Return value A `boolean` which represents whether the cached item is stale or not. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CacheState/usable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.usable The **`usable`** method of the `CacheState` interface returns `true` if the cached item is usable. A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. ## Syntax ```js usable() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item is usable or not. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CoreCache/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.insert Performs a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. ## Syntax ```js insert(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item’s contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CoreCache/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.lookup Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. ## Syntax ```js lookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns `CacheEntry` if a usable cached item was found, otherwise returns `null`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/CoreCache/transactionLookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.transactionLookup Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. Request Collapsing: If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, just one of the callers will be instructed to insert the item into the cache as part of the transaction. The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. Revalidation: Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. ## Syntax ```js transactionLookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns an instance of `TransactionCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, and return a message stating whether the entry was in the Fastly Cache or not. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); return new Response(page ? `${path} is in the cache` : `${path} is not in the cache`, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key`. If no entry is found (or has expired), the supplied `set` function is executed and its result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - The function to execute if and only if the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The maximum number of seconds to store the supplied entry in the cache. - `length` _: number_ __optional__ - The length of the value being stored within the cache. This is only used when the `value` is a `ReadableStream`. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/SimpleCache/purge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.purge purge the entry associated with the key `key` from the cache. ## Syntax ```js purge(key, options) ``` ### Parameters - `key` _: string_ - The key to purge from within the cache. - `options` _: object_ - `scope` _: string_ - : Where to purge the content from. - Possible values are: - "global" - This will remove the content from all of Fastly. - "pop" - This will remove the content from the POP that contains the currently executing instance. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `purge` querystring parameter, we purge the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('purge')) { SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.age The **`age`** method of the `TransactionCacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.body The **`body`** method of the `TransactionCacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `TransactionCacheEntry`. An error will be thrown if a stream is already active for this `TransactionCacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.cancel The **`cancel`** method of the `TransactionCacheEntry` interface cancels an obligation to provide an object to the cache. ## Syntax ```js cancel() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.close The **`close`** method of the `TransactionCacheEntry` interface closes the connection to the cache for this `TransactionCacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.hits The **`hits`** method of the `TransactionCacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insert Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. ## Syntax ```js insert(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/insertAndStreamBack.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insertAndStreamBack Perform a transaction cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. ## Syntax ```js insertAndStreamBack(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns an array where the first item is a `FastlyBody` instance and the second item is a `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.length The **`length`** method of the `TransactionCacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.maxAge The **`maxAge`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.state The **`state`** method of the `TransactionCacheEntry` interface returns a `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/update.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.update Perform an update of the cache item's metadata. ## Syntax ```js update(options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache/TransactionCacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.userMetadata The **`userMetadata`** method of the `TransactionCacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.0/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) new CacheOverride(init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. This options is also the default when providing an init object directly as the first argument. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. - `beforeSend` _:Function_ _**optional**_ - `(request: Request) => void | PromiseLike` - Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. - See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) in the Fastly cache interfaces documentation for details. - `afterSend` _: Function_ _**optional**_ - `(response: Response) => void | CacheOptions | PromiseLike` - Callback to be invoked after a response has been sent, but before it is stored into the cache. - Where `CacheOptions` contains: - `cache` _: boolean | 'uncacheable'_ _**optional**_ - Whether to cache this response. By default, leaving this field empty, responses will be cached based on their cache header information. - Setting this to true or false will override this default cache behaviour, setting in the cache or not setting in the cache, even if the default behaviour would have been otherwise. - Setting to 'uncacheable' the response will not only not be cached, but the cache will record that the originating request led to an uncacheable response, so that future cache lookups will result in immediately going to the backend, rather than attempting to coordinate concurrent requests to reduce backend traffic. - See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) for more details on the mechanism that `uncacheable` disables. - `bodyTransformFn` _: Function_ _**optional**_ - `(body: Uint8Array) => Uint8Array | PromiseLike` - Provide a function to be used for transforming the response body prior to caching. - Body transformations are performed by specifying a transform, rather than by directly working with the body during the onAfterSend callback function, because not every response contains a fresh body: 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because they do not retransmit the body. - For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will be applied to it. The original backend body is passed in to the transform function, and the function is expected to return the new body. - See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) in the Fastly cache interfaces documentation for details. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/compute/purgeSurrogateKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # purgeSurrogateKey The **`purgeSurrogateKey()`** function is used to purge the given surrogate key string from Fastly's cache. There are two purge modes: soft purge and hard purge, with hard purge as the default which clears all items from the cache immediately. When using a soft purge, stale entries are maintained in the cache, reducing orgin load, while also enabling stale revalidations. See the [Fastly Purge Documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) for more information on caching and purge operations. ## Syntax ```js purgeSurrogateKey(surrogateKey, soft?) ``` ### Parameters - `surrogateKey` _: string_ - The surrogate key string - `soft?` _: boolean_ - Enables a soft purge, retaining stale entries in the cache. Default is a hard purge. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/compute/vCpuTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # vCpuTime The **`vCpuTime()`** function provides the vCPU time used by the current request handler in milliseconds. ## Syntax ```js vCpuTime() ``` ### Parameters None. ### Return value `number`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Defines a config store instance using the resource link name. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have a resource link named "animals" (which is linked to a config store) and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.lookup() Look up the data associated with a particular User-Agent string. ## Syntax ```js lookup(userAgent) ``` ### Return value If there is data associated with the User-Agent, a `Device` instance is returned. Otherwise, `null` is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/brand.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.brand The read-only **`brand`** property of the `Device` interface is either a string stating the brand of the device, which can be different from the manufacturer of that device. If no brand is known, the value will be `null`. ## Value Either a string value if a brand is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/hardwareType.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.hardwareType The read-only **`hardwareType`** property of the `Device` interface is either a string stating the hardware type of the device, or `null` if the hardware type is not known. A string representation of the device's primary platform hardware. The most commonly used device types are also identified via boolean variables. Because a device may have multiple device types and this variable only has the primary type, we recommend using the boolean variables for logic and using this string representation for logging. ## Value Either a string value if a hardware type is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/isBot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isBot The read-only **`isBot`** property of the `Device` interface is either a boolean stating if the device is a bot, or `null` if the this is not known. ## Value Either a boolean stating if the device is a bot, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/isDesktop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isDesktop The read-only **`isDesktop`** property of the `Device` interface is either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ## Value Either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/isGameConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isGameConsole The read-only **`isGameConsole`** property of the `Device` interface is either a boolean stating if the device is a video game console, or `null` if the this is not known. ## Value Either a boolean stating if the device is a video game console, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/isMediaPlayer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMediaPlayer The read-only **`isMediaPlayer`** property of the `Device` interface is either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ## Value Either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/isMobile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMobile The read-only **`isMobile`** property of the `Device` interface is either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ## Value Either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/isSmartTV.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isSmartTV The read-only **`isSmartTV`** property of the `Device` interface is either a boolean stating if the device is a smart TV, or `null` if the this is not known. ## Value Either a boolean stating if the device is a smart TV, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/isTablet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTablet The read-only **`isTablet`** property of the `Device` interface is either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ## Value Either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/isTouchscreen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTouchscreen The read-only **`isTouchscreen`** property of the `Device` interface is either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ## Value Either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/model.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.model The read-only **`model`** property of the `Device` interface is either a string stating the model of the device, or `null` if the model is not known. ## Value Either a string value if a model is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.name The read-only **`name`** property of the `Device` interface is either a string stating the name of the device, or `null` if the name is not known. ## Value Either a string value if a name is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/device/Device/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toJSON The `toJSON()` method of the Device interface is a serializer; it returns a JSON representation of the Device object. To get a JSON string, you can use `JSON.stringify(device)` directly; it will call `toJSON()` automatically. ## Syntax ```js toJSON() ``` ### Return value A JSON object that is the serialization of the Device object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Dictionary()` :::info This Class is deprecated ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/edge-rate-limiter/EdgeRateLimiter/EdgeRateLimiter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `EdgeRateLimiter()` The **`EdgeRateLimiter` constructor** lets you open an epen a [ERL](https://docs.fastly.com/products/edge-rate-limiting) with the given ratecounter and penaltybox. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new EdgeRateLimiter(rateCounter, penaltyBox) ``` > **Note:** `EdgeRateLimiter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `rateCounter` _: RateCounter_ - The RateCounter instance to associate with this EdgeRateLimiter instance - `penaltyBox` _: PenaltyBox_ - The PenaltyBox instance which should be associated with this EdgeRateLimiter instance ### Return value A new `EdgeRateLimiter` object. ### Exceptions - `TypeError` - Thrown if the provided rateCounter value is not an instance of RateCounter - Thrown if the provided penaltyBox value is not an instance of PenaltyBox ================================================ FILE: documentation/versioned_docs/version-3.40.0/edge-rate-limiter/EdgeRateLimiter/prototype/checkRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EdgeRateLimiter.prototype.checkRate Increment an entry in the rate counter and check if the entry has exceeded some average number of requests per second (RPS) over the given window. If the entry is over the RPS limit for the window, add to the penaltybox for the given `timeToLive`. Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ## Syntax ```js checkRate(entry, delta, window, limit, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to increment and check - `delta` _: number_ - The amount to increment the `entry` by - `window` _: number_ - The time period to check across, has to be either 1 second, 10 seconds, or 60 seconds - `limit` _: number_ - The requests-per-second limit - `timeToLive` _: number_ - In minutes, how long the entry should be added into the penalty-box - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `true` if the entry has exceeded the average RPS for the window, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive finite number. - Thrown if the provided `window` value is not either, 1, 10, or 60. - Thrown if the provided `limit` value is not a positive finite number. - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.40.0/edge-rate-limiter/PenaltyBox/PenaltyBox.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `PenaltyBox()` The **`PenaltyBox` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for adding and checking if some entry is in the dataset. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new PenaltyBox(name) ``` > **Note:** `PenaltyBox()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a PenaltyBox with the given name ### Return value A new `PenaltyBox` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.40.0/edge-rate-limiter/PenaltyBox/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.add Add an `entry` into the PenaltyBox for the duration of the given `timeToLive`. ## Syntax ```js add(entry, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `timeToLive` _: number_ - In minutes, how long the entry should be added into the PenaltyBox - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.40.0/edge-rate-limiter/PenaltyBox/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.has Check if the given entry is contained in in the PenaltyBox instance. ## Syntax ```js has(entry) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up ### Return value Returns `true` if the entry is contained in the PenaltyBox instance, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.40.0/edge-rate-limiter/RateCounter/RateCounter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `RateCounter()` The **`RateCounter` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for counting and rate calculations. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new RateCounter(name) ``` > **Note:** `RateCounter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a RateCounter with the given name ### Return value A new `RateCounter` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.40.0/edge-rate-limiter/RateCounter/prototype/increment.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.increment Increment the given `entry` in the RateCounter instance with the given `delta` value. ## Syntax ```js increment(entry, delta) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `delta` _: number_ - The amount to increment the entry by ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive, finite number. ================================================ FILE: documentation/versioned_docs/version-3.40.0/edge-rate-limiter/RateCounter/prototype/lookupCount.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupCount Look up the current rate for the given `entry` and the given `duration`. ## Syntax ```js lookupCount(entry, duration) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `duration` _: number_ - The duration to lookup alongside the entry, has to be either, 10, 20, 30, 40, 50, or 60 seconds. ### Return value Returns a number which is the count for the given `entry` and `duration` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `duration` value is not either, 10, 20, 30, 40, 50 or 60. ================================================ FILE: documentation/versioned_docs/version-3.40.0/edge-rate-limiter/RateCounter/prototype/lookupRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupRate Look up the current rate for the given `entry` and the given `window`. ## Syntax ```js lookupRate(entry, window) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `window` _: number_ - The window to look up alongside the entry, has to be either 1 second, 10 seconds, or 60 seconds ### Return value Returns a number which is the rate for the given `entry` and `window` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `window` value is not either, 1, 10, or 60. ================================================ FILE: documentation/versioned_docs/version-3.40.0/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabledOrConfig` _: boolean_ - Whether or not to allow Dynamic Backends or - `enabledOrConfig` _: object_ - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to https://www.fastly.com/ and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/experimental/mapAndLogError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapAndLogError The **`mapAndLogError()`** function calls `mapError` on an `Error` object and sends the output to standard error. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapAndLogError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value `undefined`. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { mapAndLogError(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | mapAndLogError(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/experimental/mapError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapError The **`mapError()`** function extracts information from an `Error` object as a human-readable array of strings. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value Returns an array of `string`s. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { console.error(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | console.error(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/experimental/sdkVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sdkVersion The read-only **`sdkVersion`** property is a string whose indicates what JavaScript SDK version is being used. ## Value A string value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/experimental/setReusableSandboxOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setReusableSandboxOptions The **`setReusableSandboxOptions()`** function configures the reuse of the same underlying sandbox for multiple requests, which can improve performance by avoiding the overhead of initializing a new sandbox for each request. ## Syntax ```js setReusableSandboxOptions(options) ``` ### Parameters - `options` _: Object_ - The configuration options for the reusable sandbox. - `maxRequests` _: number_ (default: `1`, `0` means unlimited) - The maximum number of requests that can be handled by a single sandbox before it is recycled. - `betweenRequestTimeoutMs` _: number_ (default: not specified) - The amount of time in milliseconds to wait between requests before recycling the sandbox. - `maxMemoryMiB` _: number_ (default: no limit) - The maximum amount of memory in MiB that the sandbox can use before it is recycled. - `sandboxTimeoutMs` _: number_ (default: no timeout) - The maximum amount of time in milliseconds that a sandbox can be active before it is recycled. ================================================ FILE: documentation/versioned_docs/version-3.40.0/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object`, or `null` if no geolocation data was found. The object contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Blob/Blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob() The **`Blob()`** constructor creates a `Blob` object, which represents a file-like object of immutable, raw data. ## Syntax ```js new Blob() new Blob(array) new Blob(array, options) ``` > **Note:** `Blob()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `array` _**optional**_ - : An array of values to include in the `Blob`. These can be [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx), [`Blob`](../../globals/Blob/Blob.mdx), or strings. If any of these elements is a [`Blob`](../../globals/Blob/Blob.mdx), its content (and not the object itself) is copied into the Blob being constructed. - `options` _**optional**_ - : An object containing optional attributes for the `Blob`. - `type` - : A string indicating the MIME type of the data. The default value is the empty string `""`. - `endings` - : A string indicating how to handle line endings in the data. This can be either `"transparent"` (default) to keep line endings unchanged, or `"native"` to convert line endings to the platform's native line endings (e.g., `\r\n` on Windows). ### Return value A new `Blob` object containing the specified data. ## Description `Blob` objects represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting its functionality and expanding it to support files on the user's system. To construct a `Blob` from other non-blob objects and data, use the `Blob()` constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](../../globals/Blob/prototype/slice.mdx) method. The `type` property of a `Blob` object will match the MIME type specified in the constructor's `options` parameter, defaulting to an empty string if not specified. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Blob/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.arrayBuffer() The **`arrayBuffer()`** method of the `Blob` interface returns a `Promise` that resolves with an `ArrayBuffer` containing the entire contents of the `Blob` as binary data. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A `Promise` that resolves with an `ArrayBuffer` containing the blob's data. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Blob/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.size The **`size`** read-only property of the `Blob` interface returns the size of the `Blob` in bytes. ## Value A number representing the size of the `Blob` in bytes. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Blob/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.slice() The **`slice()`** method of the `Blob` interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. ## Syntax ```js slice() slice(start) slice(start, end) slice(start, end, contentType) ``` ### Parameters - `start` _**optional**_ - : The 0-based index of the first byte to include in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is 0. - `end` _**optional**_ - : The 0-based index of the first byte that will not be included in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is `size`. - `contentType` _**optional**_ - : A string indicating the content type to assign to the new `Blob`. The default value is an empty string. ### Return value A new `Blob` object containing the specified subset of data. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Blob/prototype/stream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.stream() The **`stream()`** method of the `Blob` interface returns a `ReadableStream` that can be used to read the contents of the `Blob`. ## Syntax ```js stream() ``` ### Parameters None. ### Return value A `ReadableStream` that provides the data contained within the `Blob`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Blob/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.text() The **`text()`** method of the `Blob` interface returns a `Promise` that resolves with a string containing the contents of the blob, interpreted as UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a string containing the blob's data as a text string. The data is always interpreted as UTF-8. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Blob/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.type The **`type`** read-only property of the `Blob` interface returns the MIME type of the `Blob`. ## Value A string indicating the MIME type of the `Blob`. If the type cannot be determined, this returns an empty string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/EcKeyImportParams/EcKeyImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcKeyImportParams The **`EcKeyImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as ECDSA. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/EcdsaParams/EcdsaParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcdsaParams The **`EcdsaParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `hash` - : A string. An identifier for the digest algorithm to use. This should be one of the following: - `SHA-256`: selects the SHA-256 algorithm. - `SHA-384`: selects the SHA-384 algorithm. - `SHA-512`: selects the SHA-512 algorithm. > **Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. While these fields are always defined on Compute, they may be *null* when not available in testing environments such as Viceroy. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : Either `null`, or a [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. - `FetchEvent.client.tlsJA3MD5` _**readonly**_ - : Either `null` or a string representation of the JA3 hash of the TLS ClientHello message. - `FetchEvent.client.tlsCipherOpensslName` _**readonly**_ - : Either `null` or a string representation of the cipher suite used to secure the client TLS connection. - `FetchEvent.client.tlsProtocol` _**readonly**_ - : Either `null` or a string representation of the TLS protocol version used to secure the client TLS connection. - `FetchEvent.client.tlsClientCertificate` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw client certificate in the mutual TLS handshake message. It is in PEM format. Returns an empty ArrayBuffer if this is not mTLS or available. - `FetchEvent.client.tlsClientHello` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw bytes sent by the client in the TLS ClientHello message. - `FetchEvent.client.tlsJA4` _**readonly**_ - : Either `null` or a string representation of the JA4 fingerprint of the TLS ClientHello message. - `FetchEvent.client.h2Fingerprint` _**readonly**_ - : Either `null` or a string representation of the HTTP/2 fingerprint for HTTP/2 connections. Returns `null` for HTTP/1.1 connections. - `FetchEvent.client.ohFingerprint` _**readonly**_ - : Either `null` or a string representation of the Original Header fingerprint based on the order and presence of request headers. - `FetchEvent.server` _**readonly**_ - : Information about the server receiving the request for the Fastly Compute service. - `FetchEvent.server.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the server which received the request. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.sendEarlyHints()`](./prototype/sendEarlyHints.mdx) - : Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FetchEvent/prototype/sendEarlyHints.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.sendEarlyHints() The **`sendEarlyHints()`** method allows you to send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response back to the client which made the incoming request to your application. ## Syntax ```js sendEarlyHints(headers) ``` ### Parameters - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../Headers/Headers.mdx) object or object literal of [`String`](../../String/String.mdx) key/value pairs. ### Return value Always returns `undefined`. ### Examples ```js event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'] ]); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/FormData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData() The **`FormData()`** constructor creates a new `FormData` object. ## Syntax ```js new FormData() new FormData(form) ``` > **Note:** `FormData()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `form` _**optional**_ - : An HTML `` element — when specified, the `FormData` object will be populated with the form's current key/value pairs using the name property of each element for the keys and their submitted value for the values. File input elements are handled specially: their values are taken from the files selected by the user in the upload control. ### Return value A new `FormData` object, pre-populated with form data if the optional `form` parameter was provided. ## Description The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using methods such as `fetch()`. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also append additional data to the `FormData` object after it's created using its various methods. A `FormData` object can be used in a number of ways with other APIs: 1. It can be sent with the `fetch()` API 2. It works seamlessly with the `Request` and `Response` objects - it can be used directly as the body of a `Request` object 3. It can be obtained from a `Response` object using the `formData()` method 4. It can be passed directly to the `URLSearchParams` constructor The transmitted data is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to `"multipart/form-data"`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.append() The **`append()`** method of the `FormData` interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. ## Syntax ```js append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.delete() The **`delete()`** method of the `FormData` interface removes all key/value pairs with the given name from the `FormData` object. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.entries() The **`entries()`** method of the `FormData` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator yields a new array for each key/value pair, with the first element being the key and the second element being the value. ## Syntax ```js entries() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.forEach() The **`forEach()`** method of the `FormData` interface executes the provided callback function once for each key/value pair in the `FormData` object. ## Syntax ```js forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each entry in the object. The function will be passed the following arguments: - `value` - : The value of the current entry. - `key` - : The key of the current entry. - `formData` - : The `FormData` object being traversed. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.get() The **`get()`** method of the `FormData` interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the [`getAll()`](../../../globals/FormData/prototype/getAll.mdx) method instead. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value A `FormDataEntryValue` containing the value. If the key does not exist, it returns `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/prototype/getAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.getAll() The **`getAll()`** method of the `FormData` interface returns all the values associated with a given key from within a `FormData` object. ## Syntax ```js getAll(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value An array of `FormDataEntryValue` items containing all values with the given key. If the key doesn't exist, an empty array is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.has() The **`has()`** method of the `FormData` interface returns a boolean indicating whether a `FormData` object contains a key/value pair with the given name. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the key you want to test for existence. ### Return value `true` if a key/value pair with the specified name exists; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.keys() The **`keys()`** method of the `FormData` interface returns an iterator allowing iteration through all keys contained in this object. The iterator yields the key for each value. ## Syntax ```js keys() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.set() The **`set()`** method of the `FormData` interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and [`append()`](../../../globals/FormData/prototype/append.mdx) is that if the specified key already exists, `set()` overwrites all existing values with the new one, whereas `append()` appends the new value onto the end of the existing values. ## Syntax ```js set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/FormData/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.values() The **`values()`** method of the `FormData` interface returns an iterator allowing iteration through all values contained in this object. The iterator yields the value for each key/value pair. ## Syntax ```js values() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name is not the name of an HTTP header, this method throws a `TypeError`. The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/prototype/getSetCookie.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.getSetCookie() The **`getSetCookie()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns an array of all the values of the `Set-Cookie` headers, returning an empty list if none are present. ## Syntax ```js getSetCookie() ``` ### Return value `String[]` representing the list of `Set-Cookie` headers. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2 or greater than π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex where x is a number very close to 0, you should get an answer very close to 1 + x, because limx0ex1x=1. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, a `ReadableStream` object, a [`Blob`](../../globals/Blob/Blob.mdx) object, or a [`FormData`](../../globals/FormData/FormData.mdx) object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_, see [`CacheOverride`](../../fastly:cache-override/CacheOverride/CacheOverride.mdx). - `cacheKey` _**Fastly-specific**_ - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.blob() The **`blob()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/clone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.clone() The **`clone()`** method of the `Request` interface creates a copy of the current `Request` object. Like the underlying `ReadableStream.tee`` api, the `body` of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Beware when you construct a `Request` from a stream and then `clone` it. `clone()` throws a `TypeError` if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) If you intend to modify the request, you may prefer the `Request` constructor. ## Syntax ```js clone() ``` ### Parameters None. ### Return value A `Request` object, which is an exact copy of the `Request` that `clone()` was called on. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.formData() The **`formData()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. - `SyntaxError` - : Thrown if the request's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Request` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Request instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - [`Blob`](../../globals/Blob/Blob.mdx) - [`FormData`](../../globals/FormData/FormData.mdx) - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.blob() The **`blob()`** method of the [`Response`](../Response.mdx) interface takes a [`Response`](../Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.formData() The **`formData()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. - `SyntaxError` - : Thrown if the response's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/ip.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ip The **`ip`** getter of the `Response` interface returns the IP address associated with the request, as either an IPv6 or IPv4 string. In the case where no IP address is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with an IP, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `string`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.port The **`port`** getter of the `Response` interface returns the port associated with the request, as a number. In the case where no port is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with a port, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `number`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Response` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Response instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - For ECDSA: Pass an [`EcKeyImportParams`](../../EcKeyImportParams/EcKeyImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](https://en.wikipedia.org/wiki/HZ_(character_encoding)). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Explicit Backends Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service. This `backend` option is then a special Fastly-specific fetch option that is provided to the `fetch()` call: ```js fetch('https://origin.com/path', { backend: 'origin' }); ``` Backends are configured using the Fastly service backend configuration, see the [Backend documentation](https://developer.fastly.com/reference/api/services/backend/) for more information. ## Dynamic Backends Dynamic backends are a compute feature that allow services to define backends for themselves. If the `backend` option is not provided when making `fetch()` requests, a backend will be automatically created by extracting the protocol, host, and port from the provided URL. In addition, custom backend configuration options can then also be provided through the [`Backend()`](../fastly:backend/Backend/Backend.mdx) constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ - `imageOptimizerOptions` _**Fastly-specific**_, see [`imageOptimizerOptions`](../fastly:image-optimizer/imageOptimizerOptions.mdx). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-3.40.0/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/after.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # after The `after` method inserts content after the closing tag of the element. ## Syntax ```js element.after(content); element.after(content, options); ``` ### Parameters - `content` _: string_ - The content to insert after the element's closing tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.after("World"); // Result:
Hello
World ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # append The `append` method inserts content at the end of the element's content. ## Syntax ```js element.append(content); element.append(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the end of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.append(", World"); // Result:
Hello, World
``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/before.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # before The `before` method inserts content before the opening tag of the element. ## Syntax ```js element.before(content); element.before(content, options); ``` ### Parameters - `content` _: string_ - The content to insert before the element's opening tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.before("Well"); // Result: Well
Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/hasAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # hasAttribute The `hasAttribute` method returns a `boolean` value indicating whether the specified attribute is present on the element. ## Syntax ```js element.hasAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to check for. ### Return value A boolean value indicating whether the attribute is present. ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/prepend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # prepend The `prepend` method inserts content at the beginning of the element's content. ## Syntax ```js element.prepend(content); element.prepend(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the beginning of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.prepend("Well, "); // Result:
Well, Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/removeAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # removeAttribute The `removeAttribute` method removes the specified attribute from the element. ## Syntax ```js element.removeAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to remove. ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/replaceChildren.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceChildren The `replaceChildren` method replaces the element's children with new content. ## Syntax ```js element.replaceChildren(content); element.replaceChildren(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element's children with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceChildren("Greetings!"); // Result:
Greetings!
``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/replaceWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceWith The `replaceWith` method replaces the element with new content. ## Syntax ```js element.replaceWith(content); element.replaceWith(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceWith("

Greetings!

"); // Result:

Greetings!

``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/selector.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # selector The `selector` read-only property is a `string` representing the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) that matches the element. ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/setAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setAttribute The `setAttribute` method sets the value of the specified attribute on the element. If the value already exists, it will be updated; otherwise, a new attribute with the specified name and value will be added to the element. ## Syntax ```js element.setAttribute(attributeName, value); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to set. - `value` _: string_ - The value to assign to the attribute. ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/Element/prototype/tag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # tag The `tag` read-only property is a `string` representing the tag name of the element. ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/HTMLRewritingStream/HTMLRewritingStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `HTMLRewritingStream()` The **`HTMLRewritingStream`** lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback. This callback can manipulate the attributes of the element, and add or remove content from the immediate context. ## Syntax ```js new HTMLRewritingStream() ``` ### Return value A new `HTMLRewritingStream` object. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/html-rewriter/HTMLRewritingStream/prototype/onElement.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # onElement ▸ **onElement**`(selector: string, handler: (element: Element) => void): this` Registers an element handler with the [`HTMLRewritingStream`] that will be called for each [`Element`] that matches the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) `selector`. Elements added by handlers will not be processed by other handlers. ## Syntax ```js .onElement(selector, handler) ``` ### Parameters - `selector` _: string_ - A CSS selector that determines the elements for which `handler` will be called - The following types of CSS selector are supported: Currently the rewriter supports the following CSS selectors: | Pattern | Description | |----------------------|----------------------------------------------------------------------------| | `*` | Any element | | `E` | All elements of type `E` | | `E F` | `F` elements inside `E` elements | | `E > F` | `F` elements directly inside `E` elements | | `E:nth-child(n)` | The n-th child of type `E` | | `E:first-child` | First child of type `E` | | `E:nth-of-type(n)` | The n-th sibling of type `E` | | `E:first-of-type` | First sibling of type `E` | | `E:not(s)` | Type `E` elements not matching selector `s` | | `E.myclass` | Type `E` elements with class `"myclass"` | | `E#myid` | Type `E` elements with ID `"myid"` | | `E[attr]` | Type `E` elements with attribute `attr` | | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | | `E[attr="val" i]` | Type `E` elements where `attr` is `"val"`, case-insensitive | | `E[attr="val" s]` | Type `E` elements where `attr` is `"val"`, case-sensitive | | `E[attr~="val"]` | Type `E` elements where `attr` contains `"val"` in a space-separated list | | `E[attr`|`;="val"]`| Type `E` elements where `attr` is hyphen-separated and starts with `"val"` | | `E[attr^="val"]` | Type `E` elements where `attr` starts with `"val"` | | `E[attr$="val"]` | Type `E` elements where `attr` ends with `"val"` | | `E[attr*="val"]` | Type `E` elements where `attr` contains `"val"` | - `handler` _: (element: Element) => void_ - A callback function that will be called once for each element that matches `selector` ### Return value The `HTMLRewritingStream`, so multiple calls to `onElement` can be chained. ### Exceptions - `Error` - If the provided `selector` is not a valid CSS selector. - If the provided `handler` is not a function. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/Auto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Auto` Enumerator options for [`imageOptimizerOptions.auto`](./imageOptimizerOptions.mdx). ## Constants - `AVIF` (`"avif"`) If the browser's Accept header indicates compatibility, deliver an AVIF image. - `WEBP` (`"webp"`) If the browser's Accept header indicates compatibility, deliver a WebP image. ## Examples ```js import { Auto, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, auto: Auto.AVIF }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/BWAlgorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `BWAlgorithm` Enumerator options for [`imageOptimizerOptions.bw`](./imageOptimizerOptions.mdx). ## Constants - `Threshold` (`"threshold"`) Uses a luminance threshold to convert the image to black and white. - `Atkinson` (`"atkinson"`) Uses [Atkinson dithering](https://en.wikipedia.org/wiki/Atkinson_dithering) to convert the image to black and white. ## Examples ```js import { Region, BWAlgorithm } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, bw: BWAlgorithm.Threshold }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/CropMode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CropMode` Enumerator options for [`imageOptimizerOptions.crop.mode`](./imageOptimizerOptions.mdx) and `imageOptimizerOptions.precrop.mode`. ## Constants - `Smart` (`"smart"`) Enables content-aware algorithms to attempt to crop the image to the desired aspect ratio while intelligently focusing on the most important visual content, including the detection of faces. - `Safe` (`"safe"`) Allow cropping out-of-bounds regions. ## Examples ```js import { CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Smart, } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/Disable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Disable` Enumerator options for [`imageOptimizerOptions.disable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Prevent images being resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Disable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, disable: Disable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/Enable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Enable` Enumerator options for [`imageOptimizerOptions.enable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Allow images to be resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Enable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, enable: Enable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/Fit.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Fit` Enumerator options for [`imageOptimizerOptions.fit`](./imageOptimizerOptions.mdx). ## Constants - `Bounds` (`"bounds"`) Resize the image to fit entirely within the specified region, making one dimension smaller if needed. - `Cover` (`"cover"`) Resize the image to entirely cover the specified region, making one dimension larger if needed. - `Crop` (`"crop"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Fit, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 150, height; 150, fit: Fit.Bounds }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/Format.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Format` Enumerator options for [`imageOptimizerOptions.format`](./imageOptimizerOptions.mdx). ## Constants - `Auto` (`"auto"`) Automatically use the best format based on browser support and image/transform characteristics - `AVIF` (`"avif"`) AVIF - `BJPG` (`"bjpg"`) Baseline JPEG - `GIF` (`"gif"`) Graphics Interchange Format - `JPG` (`"jpg"`) JPEG - `JXL` (`"jxl"`) JPEGXL - `MP4` (`"mp4"`) MP4 (H.264) - `PJPG` (`"pjpg"`) Progressive JPEG - `PJXL` (`"pjxl"`) Progressive JPEGXL - `PNG` (`"png"`) Portable Network Graphics - `PNG8` (`"png8"`) Portable Network Graphics palette image with 256 colors and 8-bit transparency - `SVG` (`"svg"`) Scalable Vector Graphics - `WEBP` (`"webp"`) WebP - `WEBPLL` (`"webpll"`) WebP (Lossless) - `WEBPLY` (`"webply"`) WebP (Lossy) ## Examples ```js import { Format, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/Metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Metadata` Enumerator options for [`imageOptimizerOptions.metadata`](./imageOptimizerOptions.mdx). ## Constants - `Copyright` (`"copyright"`) Preserve [copyright notice](https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#copyright-notice), creator, credit line, licensor, and web statement of rights fields. - `C2PA` (`"c2pa"`) Preserve the [C2PA manifest](https://c2pa.org/) and add any transformations performed by Fastly Image Optimizer. - `CopyRightAndC2PA` (`"copyright,c2pa"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Metadata, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, metadata: Metadata.Copyright }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/Optimize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Optimize` Enumerator options for [`imageOptimizerOptions.optimize`](./imageOptimizerOptions.mdx). ## Constants - `Low` (`"low"`) Output image quality will be similar to the input image quality. - `Medium` (`"medium"`) More optimization is allowed. We attempt to preserve the visual quality of the input image. - `High` (`"high"`) Minor visual artifacts may be visible. This produces the smallest file. ## Examples ```js import { Optimize, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, optimize: Optimize.High }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/Orient.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Orient` Enumerator options for [`imageOptimizerOptions.orient`](./imageOptimizerOptions.mdx). ## Constants - `Default` (`"1"`) - `FlipHorizontal` (`"2"`) - `FlipHorizontalAndVertical` (`"3"`) - `FlipVertical` (`"4"`) - `FlipHorizontalOrientLeft` (`"5"`) - `OrientRight` (`"6"`) - `FlipHorizontalOrientRight` (`"7"`) - `OrientLeft` (`"8"`) ## Examples ```js import { Orient, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, orient: Orient.FlipHorizontal }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/Profile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Profile` Enumerator options for [`imageOptimizerOptions.profile`](./imageOptimizerOptions.mdx). ## Constants - `Baseline` (`"baseline"`) The profile recommended for video conferencing and mobile applications. (Default) - `Main` (`"main"`) The profile recommended for standard-definition broadcasts. - `High` (`"high"`) The profile recommended for high-definition broadcasts. ## Examples ```js import { Profile, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, profile: Profile.Main }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/Region.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Region` Enumerator options for [`imageOptimizerOptions.region`](./imageOptimizerOptions.mdx). ## Constants - `UsEast` (`"us_east"`) - `UsCentral` (`"us_central"`) - `UsWest` (`"us_west"`) - `EuCentral` (`"eu_central"`) - `EuWest` (`"eu_west"`) - `Asia` (`"asia"`) - `Australia` (`"australia"`) ## Examples ```js import { Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/ResizeFilter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ResizeFilter` Enumerator options for [`imageOptimizerOptions.resizeFilter`](./imageOptimizerOptions.mdx). ## Constants - `Nearest` (`"nearest"`) Uses the value of nearby translated pixel values. - `Bilinear` (`"bilinear"`) Uses an average of a 2x2 environment of pixels. - `Linear` (`"linear"`) Same as `Bilenear`. - `Bicubic` (`"bicubic"`) Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. - `Cubic` (`"cubic"`) Same as `Bicubic`. - `Lanczos2` (`"lanczos2"`) Uses the Lanczos filter to increase the ability to detect edges and linear features within an image and uses sinc resampling to provide the best possible reconstruction. - `Lanczos3` (`"lanczos3"`) Lanczos3 uses a better approximation of the sinc resampling function. (Default) - `Lanczos` (`"lanczos"`) Same as `Lanczos3`. ## Examples ```js import { ResizeFilter, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, resizeFilter: ResizeFilter.Linear }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/image-optimizer/imageOptimizerOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `imageOptimizerOptions` Options specified in the [`Request`](../globals/Request/Request.mdx) constructor for running the [Fastly Image Optimizer](https://docs.fastly.com/products/image-optimizer). More detailed documentation on all Image Optimizer options is available in the [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/). ## Parameters All parameters other than `region` are optional. - `region`: _[`Region`](./Region.mdx)_ Where image optimizations should occur. - `auto`: _[`Auto`](./Auto.mdx)_ Enable optimization features automatically. - `bgColor`: _[`Color`](#color)_ Set the background color of an image. - `blur`: _`number` (0.5-1000) or [`Percentage`](#percentage)_ Set the blurriness of the output image. - `brightness`: _`number` (-100-100)_ Set the brightness of the output image. - `bw`: _[`BWAlgorithm`](./BWAlgorithm.mdx)_ Convert an image to black and white. - `canvas`: _`Object`_ Increase the size of the canvas around an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `contrast`: _`number` (-100-100)_ Set the contrast of the output image. - `crop`: _`Object`_ Remove pixels from an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `mode` (optional): _[`CropMode`](./CropMode.mdx)_ - `disable`: _[`Disable`](./Disable.mdx)_ Disable functionality that is enabled by default. - `dpr`: `number` Ratio between physical pixels and logical pixels. - `enable`: _[`Enable`](./Enable.mdx)_ Enable functionality that is disabled by default. - `fit`: _[`Fit`](./Fit.mdx)_ Set how the image will fit within the size bounds provided. - `format`: _[`Format`](./Format.mdx)_ Specify the output format to convert the image to. - `frame`: _`number` (must have the value 1)_ Extract the first frame from an animated image sequence. - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the height of the image. - `level`: _`String` containing one of the [allowed values](https://www.fastly.com/documentation/reference/io/level/#allowed-values)_ Specify the level constraints when converting to video. - `metadata`: _[`Metadata`](./Metadata.mdx)_ Control which metadata fields are preserved during transformation. - `optimize`: _[`Optimize`](./Optimize.mdx)_ Automatically apply optimal quality compression. - `orient`: _[`Orient`](./Orient.mdx)_ Change the cardinal orientation of the image. - `pad`: _[`Sides`](#sides)_ Add pixels to the edge of an image. - `precrop`: _`Object`_ Remove pixels from an image before any other transformations occur. - `size`: _[`Size`](#size)_ - `position`: _[`Position`](#position)_ - `mode`: _[`CropMode`](./CropMode.mdx)_ - `profile`: _[`Profile`](./Profile.mdx)_ Specify the profile class of application when converting to video. - `quality`: _`integer` (1-100)_ Optimize the image to the given compression level for lossy file formatted images. - `resizeFilter`: _[`ResizeFilter`](./ResizeFilter.mdx)_ Specify the resize filter used when resizing images. - `saturation`: _`number` (-100-100)_ Set the saturation of the output image. - `sharpen`: _`Object`_ Set the sharpness of the output image. - `amount`: _`number` (0-10)_ - `radius`: _`number` (0.5-1000)_ - `threshold`: _`integer` (0-255)_ - `trim`: _[`Sides`](#sides)_ Remove pixels from the edge of an image. - `viewbox`: _`number` (must have the value 1)_ Remove explicit width and height properties in SVG output. - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the width of the image. ## Types ### Color Either: - a 3 or 6 character hexadecimal string - an `Object` containing: - `r`: _`integer` (0-255)_ Red component - `g`: _`integer` (0-255)_ Green component - `b`: _`integer` (0-255)_ Blue component - `a` (optional): _`number` (0.0-1.0)_ Alpha component ### Percentage A `String` containing a number suffixed with a percent sign (%). ### Position An `Object` containing: - Exactly one of: - `x`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetX`: _`number` (interpreted as a percentage)_ - Exactly one of: - `y`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetY`: _`number` (interpreted as a percentage)_ ### Sides An `Object` containing `top`, `bottom`, `left`, and `right`, all of which are either an `integer` or [`Percentage`](#percentage). ### Size An `Object` containing either: - `absolute`: _`Object`_ - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `ratio`: _`Object`_ - `width`: _`number`_ - `height`: _`number`_ ## Examples ```js import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG, bgColor: { 'r': 100, 'g': 255, 'b': 9, 'a': 0.5 }, blur: '1%', brightness: -20, contrast: -20, height: 600, level: '4.0', orient: Orient.FlipVertical, saturation: 80, sharpen: { 'amount': 5, 'radius': 6, 'threshold': 44 }, canvas: { 'size': { 'absolute': { 'width': 400, 'height': 400 } } }, crop: { size: { absolute: { width: 200, height: 200 }, mode: CropMode.Safe } }, trim: { top: 10, left: 10, right: 10, bottom: 10 }, pad: { top: 30, left: 30, right: "1%", bottom: 30 } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a KV store instance using the resource link name. ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStore/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.delete Deletes the value associated with the key `key` in the KV store. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value Returns `undefined` ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - Does not exist ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then delete the entry. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') await files.delete('hello') const entry = await files.get('hello') if (entry) { return new Response(await entry.text()) } else { return new Response('no file named hello exists') } } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStore/prototype/list.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.list The **`list()`** can be used to list the keys of a store. ## Syntax ```js list(options?) ``` ### Parameters - `options` _: object_ _**optional**_ - List options supporting properties: - `cursor` _: string_ _**optional**_ - The cursor used to pick up from a previous iteration. - `limit` _: number_ _**optional**_ - The maximum number of keys to return. - `prefix` _: string_ _**optional**_ - List only those keys that start with the given string prefix. - `noSync` _: boolean_ _**optional**_ - Do not sync the key list first, instead provide a possibly out-of-date listing. May be faster but inconsistent. ### Return value Returns a `Promise` which resolves with `{ list: string[], cursor: string | undefined }`. ## Example In this example we list the keys of a KV Store named `'files'`, iterating 10 at a time, counting the total; ```js /// import { KVStore } from 'fastly:kv-store'; async function app(event) { const files = new KVStore('files'); let cursor, list, total = 0; do { ({ cursor, list } = await files.list({ limit: 10, cursor })); total += list?.length; } while (list); return new Response(`Iterated ${total} entries`); } addEventListener('fetch', (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value, options?) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. - `options` _: object_ _**optional**_ - An insert options parameter, supporting: - `metadata` _: ArrayBuffer | TypedArray | DataView_ _**optional**_ - Binary metadata associated with the entry, may be up to 1000 bytes. - `ttl` _: number_ _**optional**_ - TTL for the entry - `mode` _: 'overwrite' | 'add' | 'append' | 'prepend'_ _**optional**_ - Insert mode, defaults to 'overwrite' - `gen` _: number_ _**optional**_ - 'generation' header specific to the version of an entry key ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - `TypeError` - If the provided `gen`: - Is not an number ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStoreEntry/prototype/metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadata() The `metadata()` method of the `KVStoreEntry` interface provides the binary metadata associated with the `KVStoreEntry`. The metadata binary may be up to 1000 bytes, and is returned as a `Uint8Array` TypedArray buffer, if metadata is set, or null otherwise. ## Syntax ```js metadata() ``` ### Parameters None. ### Return value A `Promise` that resolves to a `Uint8Array` buffer object. ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStoreEntry/prototype/metadataText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadataText() The `metadataText()` method of the `KVStoreEntry` interface provides a String interpretation of binary metadata associated with the `KVStoreEntry`. If the binary data is not a valid string, an encoding error will be thrown. ## Syntax ```js metadataText() ``` ### Parameters None. ### Return value A `Promise` that resolves to a String. ================================================ FILE: documentation/versioned_docs/version-3.40.0/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; const logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; let logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/logger/configureConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # configureConsole The **`configureConsole()`** function allows configuring the behaviour of the `console` global JS logger. ## Syntax ```js configureConsole(loggingOptions) ``` ### Parameters - `loggingOptions` _: object_ - - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ## Examples In this example, we disable prefixing for `console.log` and use `stderr` output for `console.error`: ```js import { configureConsole } from "fastly:logger"; configureConsole({ prefixing: false, stderr: true }); async function handleRequest(event) { console.log(JSON.stringify(event.request.headers)); const url = new URL(event.request.url); try { validate(url); } catch (e) { console.error(`Validation error: ${e}`); return new Response('Bad Request', { status: 400 }); } return new Response('OK'); } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v2 to v3` ## SimpleCache.delete renamed to SimpleCache.purge and requires purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using `SimpleCache.delete` to `SimpleCache.purge` with the same purging behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a Secret Store instance using the resource link name. ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/secret-store/SecretStore/fromBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fromBytes The **`fromBytes()`** function is used to create an in-memory secret from an array buffer. >**Note**: This API should be avoided when possible, by instead using [SecretStore.prototype.get](./prototype/get.mdx) to obtain secure secrets. ## Syntax ```js fromBytes(new Uint8Array([1, 2, 3])) ``` ### Parameters None. ### Return value Returns a `SecretStoreEntry`. ================================================ FILE: documentation/versioned_docs/version-3.40.0/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/secret-store/SecretStoreEntry/prototype/rawBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.rawBytes ▸ **rawBytes**(): `Uint8Array` Returns the raw byte contents of the SecretStoreEntry instance as a Uint8Array. ## Syntax ```js rawBytes() ``` ### Parameters None. ### Return value A Uint8Array ### Exceptions The `rawBytes()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ================================================ FILE: documentation/versioned_docs/version-3.40.0/security/inspect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # inspect The **`inspect()`** function inspects a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). ## Syntax ```js inspect(request, config); ``` ### Parameters - `request` _: Request_ - The Request to get a WAF determination for. - `config` _: object_ - `corp` _: string_ - Set a corp name for the configuration. - This parameter is currently required. - `workspace` _: string_ - Set a workspace name for the configuration. - This parameter is currently required. - `overrideClientIp` _: string_ - Specify an explicit client IP address to inspect. - By default, `inspect` will use the IP address that made the request to the running Compute service, but you may want to use a different IP when service chaining or if requests are proxied from outside of Fastly’s network. ### Return value Returns an `Object` with the `inspect` response, with the following fields: - `waf_response` _: number_ - Security status code. - `redirect_url` _: string | null_ - A redirect URL returned from Security. - `tags` _: string[]_ - Tags returned by Security. - `verdict` _: string_ - The outcome of inspecting a request with Security. It can be one of the following: - `"allow"` - Security indicated that this request is allowed. - `"block"` - Security indicated that this request should be blocked. - `"unauthorized"` - Security indicated that this service is not authorized to inspect a request. - Other verdicts may be returned but not currently documented. - `decision_ms` _: number_ - How long Security spent determining its verdict, in milliseconds. ## Examples ```js /// import { inspect } from "fastly:security"; async function app(event) { const res = inspect(event.request, { corp: "mycorp", workspace: "myws" }); switch (res.verdict) { case "allow": return await fetch(event.request); case "block": return new Response("Request Blocked", { status: 400 }); case "unauthorized": return new Response("Unauthorized", { status: 401 }); default: return new Response("idk", { status: 500 }); } } addEventListener("fetch", (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/shielding/Shield/Shield.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Shield()` Load information about the given shield. Returns an object representing the shield if it is active, or throws an exception if the string is malformed or the shield doesn’t exist. Shield names are defined on [this webpage](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations), in the “shield code” column. For example, the string “pdx-or-us” will look up our Portland, OR, USA shield site, while “paris-fr” will look up our Paris site. If you are using a major cloud provider for your primary origin site, consider looking at the “Recommended for” column, to find the Fastly POP most closely located to the given cloud provider. ## Syntax ```js new Shield(name) ``` > **Note:** `Shield()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Exceptions - `TypeError` - Thrown if no Shield exists with the provided name ## Examples In this example, we create a Shield instance for the Sydney, Australia shield POP. If the code is running on that shield POP, it fetches directly from origin. Otherwise, it routes the request through the shield using an encrypted connection. ```js /// import { Shield } from "fastly:shielding"; async function app(event) { const shield = new Shield('wsi-australia-au'); // If running on the shield POP, fetch from the origin directly if (shield.runningOn()) { return await fetch('https://http-me.fastly.com/anything', { backend: 'httpme' }); } // Otherwise, route the request through the shield using an encrypted connection return await fetch(event.request, { backend: shield.encryptedBackend() }); } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.0/shielding/Shield/prototype/encryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.encryptedBackend ▸ **encryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an encrypted connection to the POP. For reference, this is almost always the backend that you want to use. Only use [`Shield::unencryptedBackend`](./unencryptedBackend.mdx) in situations in which you are 100% sure that all the data you will send and receive over the backend is already encrypted. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.40.0/shielding/Shield/prototype/runningOn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.runningOn ▸ **runningOn**(): `boolean` Returns whether we are currently operating on the given shield. Technically, this may also return true in very isolated incidents in which Fastly is routing traffic from the target shield POP to the POP that this code is running on, but in these situations the results should be approximately identical. (For example, it may be the case that you are asking to shield to ‘pdx-or-us’. But, for load balancing, performance, or other reasons, Fastly is temporarily shifting shielding traffic from Portland to Seattle. In that case, this function may return true for hosts running on ‘bfi-wa-us’, our Seattle site, because effectively the shield has moved to that location. This should give you a slightly faster experience than the alternative, in which this function would return false, you would try to forward your traffic to the Portland site, and then that traffic would be caught and redirected back to Seattle.) ================================================ FILE: documentation/versioned_docs/version-3.40.0/shielding/Shield/prototype/unencryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.unencryptedBackend ▸ **unencryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an unencrypted connection to the POP. Generally speaking, we encourage users to use [`Shield::encryptedBackend`](./encryptedBackend.mdx) instead of this function. Data sent over this backend – the unencrypted version – will be sent over the open internet, with no protections. In most cases, this is not what you want. However, in some cases – such as when you want to ship large data blobs that you know are already encrypted — using these backends can prevent a double-encryption performance penalty. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.40.0/websocket/createWebsocketHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createWebsocketHandoff The **`createWebsocketHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Websocket, to the declared backend. ## Syntax ```js createWebsocketHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Websocket. - `backend` _: string_ - The name of the backend that Websocket should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Websocket. ```js import { createWebsocketHandoff } from "fastly:websocket"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createWebsocketHandoff(event.request, 'websocket_backend'); } else { return new Response('oopsie, make a request to /stream for some websocket goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/acl/Acl/open.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.open() Opens the ACL with the given name, returning a new `Acl` instance with the given name on success. ## Syntax ```js Acl.open(name) ``` ### Return value An `Acl` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.1/acl/Acl/prototype/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.prototype.lookup() The **`lookup(ipAddress)`** method returns the name associated with the `Acl` instance. ## Syntax ```js acl.lookup(ipAddress) ``` ### Parameters - `ipAddress` _: string_ - IPv4 or IPv6 address to lookup ### Return value An Object of the form `{ action: 'ALLOW' | 'BlOCK', prefix: string }`, where `prefix` is the IP address prefix that was matched in the ACL. ## Example ```js /// import { Acl } from 'fastly:acl'; addEventListener('fetch', async (evt) => { const myAcl = Acl.open('myacl'); const match = await myAcl.lookup(evt.client.address); evt.respondWith(new Response(match?.action === 'BLOCK' ? 'blocked' : 'allowed')); }); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. >**Note**: Dynamic backends are by default disabled at the Fastly service level. Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request dynamic backends on Fastly Services. To disable the usage of dynamic backends, see [enforceExplicitBackends](../enforceExplicitBackends.mdx). ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. - `grpc` _: boolean_ _**optional**_ - **_Experimental feature_** - When enabled, sets that this backend is to be used for gRPC traffic. - _Warning: When using this experimental feature, no guarantees are provided for behaviours for backends that do not provide gRPC traffic._ All optional generic options can have their defaults set via [`setDefaultDynamicBackendConfig()`](../setDefaultDynamicBackendConfig.mdx). This includes all configuration options above except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. ### Return value A new `Backend` object. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/exists.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.exists() The **`Backend.exists()`** method returns a boolean indicating if a Backend with the given name exists or not. ## Syntax ```js exists(name) ``` ### Return value A boolean indicating if a Backend with the given name exists or not. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/fromName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.fromName() Returns the `Backend` instance with the given name, if one exists. If one does not exist, an error is thrown. ## Syntax ```js fromName(name) ``` ### Return value A `Backend` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.health() :::info This method is deprecated, use [`Backend.prototype.health`](./prototype/health.mdx) instead. ::: The **`Backend.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js Backend.health(backend) ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/betweenBytesTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.betweenBytesTimeout The read-only **`betweenBytesTimeout`** property of a `Backend` instance is an integer number providing the between bytes timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/connectTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.connectTimeout The read-only **`connectTimeout`** property of a `Backend` instance is an integer number providing the connect timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/firstByteTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.firstByteTimeout The read-only **`firstByteTimeout`** property of a `Backend` instance is an integer number providing the first byte timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.health() The **`Backend.prototype.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js health() ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/hostOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.hostOverride The read-only **`hostOverride`** property of a `Backend` instance is the host header override string used when sending requests to this backend. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/httpKeepaliveTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.httpKeepaliveTime The read-only **`httpKeepaliveTime`** property of a `Backend` instance is the HTTP keepalive time for this backend in milliseconds, or 0 if no keepalive is set. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/isDynamic.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isDynamic The read-only **`isDynamic`** property of a `Backend` instance is a boolean indicating if the backend was dynamically created for this service. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/isSSL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isSSL The read-only **`isSSL`** property of a `Backend` instance is a boolean indicating if the backend is using an SSL connection. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # name The read-only **`name`** property of the backend returns the backend name string. ## Value A `string`. ## Description Provides the name of the backend. ## Examples ### Using name The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.port The read-only **`port`** property of a `Backend` instance is the port number of this backend. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/target.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.target The read-only **`target`** property of a `Backend` instance is the host string this backend is configured to use. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/tcpKeepalive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tcpKeepalive The read-only **`tcpKeepalive`** property of a `Backend` instance returns an object providing the TCP keepalive configuration, if any, otherwise returning `null` if TCP keepalive is not enabled. This object has the following properties: - `timeSecs` _: number or null._ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number or null._ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number or null._ - Number of probes to send to the backend before it is considered dead. ## Value A `Object` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/tlsMaxVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMaxVersion The read-only **`tlsMaxVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/tlsMinVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMinVersion The read-only **`tlsMinVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/toName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.toName() :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toName()`** method returns the name associated with the `Backend` instance. ## Syntax ```js toName() ``` ### Return value A string which contains the name of the Backend. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toString :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends :::info This method is deprecated, and dynamic backends are now always supported when enabled at the service level. See [`enforceExplicitBackends`](./enforceExplicitBackends.mdx) instead. ::: The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: By default, while dynamic backends are allowed in the SDK, they are by default disabled at the Fastly service level. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/enforceExplicitBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enforceExplicitBackends Call this function to enforce the security property of explicitly-defined backends, even when dynamic backends are enabled at the Fastly service level. By default, if dynamic backends are supported for the Fastly service, they will be automatically used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a potential security concern since third-party JavaScript code may send arbitrary requests, including sensitive/secret data, off to destinations that the JavaScript project was not intending. When calling this function, an optional default backend name can be provided. >**Note**: This is a separate option to the service-level dynamic backend support for Fastly services, which is by deault disabled for Fastly services. The **`enforceExplicitBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: Dynamic Backends are disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled or disabled on Fastly Services. ## Syntax ```js enforceExplicitBackends(defaultBackend?) ``` ### Parameters - `defaultBackend` _: string_ _**optional**_ - An optional default backend string name to use in `fetch()` requests. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/backend/setDefaultDynamicBackendConfig.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setDefaultDynamicBackendConfig() The **`setDefaultDynamicBackendConfig()`** allows setting backend configuration defaults that should apply to any newly created dynamic backends via the `new Backend()` constructor. ### Parameters - `defaultDynamicBackendConfig` - : An Object which contains the generic configuration options to apply to newly created Backends. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. ## Syntax ```js setDefaultDynamicBackendConfig(defaultConfig) ``` ### Return value None. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, with timeouts and TLS options provided from the default backend configuration options. import { allowDynamicBackends } from "fastly:experimental"; import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! // Timeouts and TLS configuration still get set from the default backend configuration above. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.age The **`age`** method of the `CacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.body The **`body`** method of the `CacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this `CacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.close The **`close`** method of the `CacheEntry` interface closes the connection to the cache for this `CacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.hits The **`hits`** method of the `CacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.length The **`length`** method of the `CacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.maxAge The **`maxAge`** method of the `CacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `CacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.state The **`state`** method of the `CacheEntry` interface returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.userMetadata The **`userMetadata`** method of the `CacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheState/found.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.found The **`found`** method of the `CacheState` interface returns `true` if a cached item was located. Even if an cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. ## Syntax ```js found() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item was located or not. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheState/mustInsertOrUpdate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.mustInsertOrUpdate The **`mustInsertOrUpdate`** method of the `CacheState` interface returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. ## Syntax ```js mustInsertOrUpdate() ``` ### Parameters None. ### Return value A `boolean` which represents whether a fresh cached item was found not. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheState/stale.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.stale The **`stale`** method of the `CacheState` interface returns `true` if the cached item is stale. A cached item is stale if its age is greater than its `maxAge` period. ## Syntax ```js stale() ``` ### Parameters None. ### Return value A `boolean` which represents whether the cached item is stale or not. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CacheState/usable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.usable The **`usable`** method of the `CacheState` interface returns `true` if the cached item is usable. A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. ## Syntax ```js usable() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item is usable or not. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CoreCache/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.insert Performs a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. ## Syntax ```js insert(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item’s contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CoreCache/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.lookup Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. ## Syntax ```js lookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns `CacheEntry` if a usable cached item was found, otherwise returns `null`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/CoreCache/transactionLookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.transactionLookup Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. Request Collapsing: If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, just one of the callers will be instructed to insert the item into the cache as part of the transaction. The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. Revalidation: Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. ## Syntax ```js transactionLookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns an instance of `TransactionCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, and return a message stating whether the entry was in the Fastly Cache or not. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); return new Response(page ? `${path} is in the cache` : `${path} is not in the cache`, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key`. If no entry is found (or has expired), the supplied `set` function is executed and its result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - The function to execute if and only if the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The maximum number of seconds to store the supplied entry in the cache. - `length` _: number_ __optional__ - The length of the value being stored within the cache. This is only used when the `value` is a `ReadableStream`. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/SimpleCache/purge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.purge purge the entry associated with the key `key` from the cache. ## Syntax ```js purge(key, options) ``` ### Parameters - `key` _: string_ - The key to purge from within the cache. - `options` _: object_ - `scope` _: string_ - : Where to purge the content from. - Possible values are: - "global" - This will remove the content from all of Fastly. - "pop" - This will remove the content from the POP that contains the currently executing instance. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `purge` querystring parameter, we purge the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('purge')) { SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.age The **`age`** method of the `TransactionCacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.body The **`body`** method of the `TransactionCacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `TransactionCacheEntry`. An error will be thrown if a stream is already active for this `TransactionCacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.cancel The **`cancel`** method of the `TransactionCacheEntry` interface cancels an obligation to provide an object to the cache. ## Syntax ```js cancel() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.close The **`close`** method of the `TransactionCacheEntry` interface closes the connection to the cache for this `TransactionCacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.hits The **`hits`** method of the `TransactionCacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insert Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. ## Syntax ```js insert(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/insertAndStreamBack.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insertAndStreamBack Perform a transaction cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. ## Syntax ```js insertAndStreamBack(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns an array where the first item is a `FastlyBody` instance and the second item is a `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.length The **`length`** method of the `TransactionCacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.maxAge The **`maxAge`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.state The **`state`** method of the `TransactionCacheEntry` interface returns a `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/update.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.update Perform an update of the cache item's metadata. ## Syntax ```js update(options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache/TransactionCacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.userMetadata The **`userMetadata`** method of the `TransactionCacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.40.1/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) new CacheOverride(init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. This options is also the default when providing an init object directly as the first argument. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. - `beforeSend` _:Function_ _**optional**_ - `(request: Request) => void | PromiseLike` - Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. - See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) in the Fastly cache interfaces documentation for details. - `afterSend` _: Function_ _**optional**_ - `(response: Response) => void | CacheOptions | PromiseLike` - Callback to be invoked after a response has been sent, but before it is stored into the cache. - Where `CacheOptions` contains: - `cache` _: boolean | 'uncacheable'_ _**optional**_ - Whether to cache this response. By default, leaving this field empty, responses will be cached based on their cache header information. - Setting this to true or false will override this default cache behaviour, setting in the cache or not setting in the cache, even if the default behaviour would have been otherwise. - Setting to 'uncacheable' the response will not only not be cached, but the cache will record that the originating request led to an uncacheable response, so that future cache lookups will result in immediately going to the backend, rather than attempting to coordinate concurrent requests to reduce backend traffic. - See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) for more details on the mechanism that `uncacheable` disables. - `bodyTransformFn` _: Function_ _**optional**_ - `(body: Uint8Array) => Uint8Array | PromiseLike` - Provide a function to be used for transforming the response body prior to caching. - Body transformations are performed by specifying a transform, rather than by directly working with the body during the onAfterSend callback function, because not every response contains a fresh body: 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because they do not retransmit the body. - For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will be applied to it. The original backend body is passed in to the transform function, and the function is expected to return the new body. - See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) in the Fastly cache interfaces documentation for details. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/compute/purgeSurrogateKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # purgeSurrogateKey The **`purgeSurrogateKey()`** function is used to purge the given surrogate key string from Fastly's cache. There are two purge modes: soft purge and hard purge, with hard purge as the default which clears all items from the cache immediately. When using a soft purge, stale entries are maintained in the cache, reducing orgin load, while also enabling stale revalidations. See the [Fastly Purge Documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) for more information on caching and purge operations. ## Syntax ```js purgeSurrogateKey(surrogateKey, soft?) ``` ### Parameters - `surrogateKey` _: string_ - The surrogate key string - `soft?` _: boolean_ - Enables a soft purge, retaining stale entries in the cache. Default is a hard purge. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/compute/vCpuTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # vCpuTime The **`vCpuTime()`** function provides the vCPU time used by the current request handler in milliseconds. ## Syntax ```js vCpuTime() ``` ### Parameters None. ### Return value `number`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Defines a config store instance using the resource link name. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have a resource link named "animals" (which is linked to a config store) and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.lookup() Look up the data associated with a particular User-Agent string. ## Syntax ```js lookup(userAgent) ``` ### Return value If there is data associated with the User-Agent, a `Device` instance is returned. Otherwise, `null` is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/brand.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.brand The read-only **`brand`** property of the `Device` interface is either a string stating the brand of the device, which can be different from the manufacturer of that device. If no brand is known, the value will be `null`. ## Value Either a string value if a brand is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/hardwareType.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.hardwareType The read-only **`hardwareType`** property of the `Device` interface is either a string stating the hardware type of the device, or `null` if the hardware type is not known. A string representation of the device's primary platform hardware. The most commonly used device types are also identified via boolean variables. Because a device may have multiple device types and this variable only has the primary type, we recommend using the boolean variables for logic and using this string representation for logging. ## Value Either a string value if a hardware type is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/isBot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isBot The read-only **`isBot`** property of the `Device` interface is either a boolean stating if the device is a bot, or `null` if the this is not known. ## Value Either a boolean stating if the device is a bot, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/isDesktop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isDesktop The read-only **`isDesktop`** property of the `Device` interface is either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ## Value Either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/isGameConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isGameConsole The read-only **`isGameConsole`** property of the `Device` interface is either a boolean stating if the device is a video game console, or `null` if the this is not known. ## Value Either a boolean stating if the device is a video game console, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/isMediaPlayer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMediaPlayer The read-only **`isMediaPlayer`** property of the `Device` interface is either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ## Value Either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/isMobile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMobile The read-only **`isMobile`** property of the `Device` interface is either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ## Value Either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/isSmartTV.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isSmartTV The read-only **`isSmartTV`** property of the `Device` interface is either a boolean stating if the device is a smart TV, or `null` if the this is not known. ## Value Either a boolean stating if the device is a smart TV, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/isTablet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTablet The read-only **`isTablet`** property of the `Device` interface is either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ## Value Either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/isTouchscreen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTouchscreen The read-only **`isTouchscreen`** property of the `Device` interface is either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ## Value Either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/model.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.model The read-only **`model`** property of the `Device` interface is either a string stating the model of the device, or `null` if the model is not known. ## Value Either a string value if a model is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.name The read-only **`name`** property of the `Device` interface is either a string stating the name of the device, or `null` if the name is not known. ## Value Either a string value if a name is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/device/Device/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toJSON The `toJSON()` method of the Device interface is a serializer; it returns a JSON representation of the Device object. To get a JSON string, you can use `JSON.stringify(device)` directly; it will call `toJSON()` automatically. ## Syntax ```js toJSON() ``` ### Return value A JSON object that is the serialization of the Device object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Dictionary()` :::info This Class is deprecated ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/edge-rate-limiter/EdgeRateLimiter/EdgeRateLimiter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `EdgeRateLimiter()` The **`EdgeRateLimiter` constructor** lets you open an epen a [ERL](https://docs.fastly.com/products/edge-rate-limiting) with the given ratecounter and penaltybox. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new EdgeRateLimiter(rateCounter, penaltyBox) ``` > **Note:** `EdgeRateLimiter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `rateCounter` _: RateCounter_ - The RateCounter instance to associate with this EdgeRateLimiter instance - `penaltyBox` _: PenaltyBox_ - The PenaltyBox instance which should be associated with this EdgeRateLimiter instance ### Return value A new `EdgeRateLimiter` object. ### Exceptions - `TypeError` - Thrown if the provided rateCounter value is not an instance of RateCounter - Thrown if the provided penaltyBox value is not an instance of PenaltyBox ================================================ FILE: documentation/versioned_docs/version-3.40.1/edge-rate-limiter/EdgeRateLimiter/prototype/checkRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EdgeRateLimiter.prototype.checkRate Increment an entry in the rate counter and check if the entry has exceeded some average number of requests per second (RPS) over the given window. If the entry is over the RPS limit for the window, add to the penaltybox for the given `timeToLive`. Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ## Syntax ```js checkRate(entry, delta, window, limit, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to increment and check - `delta` _: number_ - The amount to increment the `entry` by - `window` _: number_ - The time period to check across, has to be either 1 second, 10 seconds, or 60 seconds - `limit` _: number_ - The requests-per-second limit - `timeToLive` _: number_ - In minutes, how long the entry should be added into the penalty-box - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `true` if the entry has exceeded the average RPS for the window, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive finite number. - Thrown if the provided `window` value is not either, 1, 10, or 60. - Thrown if the provided `limit` value is not a positive finite number. - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.40.1/edge-rate-limiter/PenaltyBox/PenaltyBox.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `PenaltyBox()` The **`PenaltyBox` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for adding and checking if some entry is in the dataset. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new PenaltyBox(name) ``` > **Note:** `PenaltyBox()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a PenaltyBox with the given name ### Return value A new `PenaltyBox` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.40.1/edge-rate-limiter/PenaltyBox/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.add Add an `entry` into the PenaltyBox for the duration of the given `timeToLive`. ## Syntax ```js add(entry, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `timeToLive` _: number_ - In minutes, how long the entry should be added into the PenaltyBox - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.40.1/edge-rate-limiter/PenaltyBox/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.has Check if the given entry is contained in in the PenaltyBox instance. ## Syntax ```js has(entry) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up ### Return value Returns `true` if the entry is contained in the PenaltyBox instance, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.40.1/edge-rate-limiter/RateCounter/RateCounter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `RateCounter()` The **`RateCounter` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for counting and rate calculations. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new RateCounter(name) ``` > **Note:** `RateCounter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a RateCounter with the given name ### Return value A new `RateCounter` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.40.1/edge-rate-limiter/RateCounter/prototype/increment.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.increment Increment the given `entry` in the RateCounter instance with the given `delta` value. ## Syntax ```js increment(entry, delta) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `delta` _: number_ - The amount to increment the entry by ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive, finite number. ================================================ FILE: documentation/versioned_docs/version-3.40.1/edge-rate-limiter/RateCounter/prototype/lookupCount.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupCount Look up the current rate for the given `entry` and the given `duration`. ## Syntax ```js lookupCount(entry, duration) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `duration` _: number_ - The duration to lookup alongside the entry, has to be either, 10, 20, 30, 40, 50, or 60 seconds. ### Return value Returns a number which is the count for the given `entry` and `duration` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `duration` value is not either, 10, 20, 30, 40, 50 or 60. ================================================ FILE: documentation/versioned_docs/version-3.40.1/edge-rate-limiter/RateCounter/prototype/lookupRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupRate Look up the current rate for the given `entry` and the given `window`. ## Syntax ```js lookupRate(entry, window) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `window` _: number_ - The window to look up alongside the entry, has to be either 1 second, 10 seconds, or 60 seconds ### Return value Returns a number which is the rate for the given `entry` and `window` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `window` value is not either, 1, 10, or 60. ================================================ FILE: documentation/versioned_docs/version-3.40.1/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabledOrConfig` _: boolean_ - Whether or not to allow Dynamic Backends or - `enabledOrConfig` _: object_ - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to https://www.fastly.com/ and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/experimental/mapAndLogError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapAndLogError The **`mapAndLogError()`** function calls `mapError` on an `Error` object and sends the output to standard error. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapAndLogError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value `undefined`. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { mapAndLogError(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | mapAndLogError(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/experimental/mapError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapError The **`mapError()`** function extracts information from an `Error` object as a human-readable array of strings. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value Returns an array of `string`s. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { console.error(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | console.error(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/experimental/sdkVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sdkVersion The read-only **`sdkVersion`** property is a string whose indicates what JavaScript SDK version is being used. ## Value A string value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/experimental/setReusableSandboxOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setReusableSandboxOptions The **`setReusableSandboxOptions()`** function configures the reuse of the same underlying sandbox for multiple requests, which can improve performance by avoiding the overhead of initializing a new sandbox for each request. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js setReusableSandboxOptions(options) ``` ### Parameters - `options` _: Object_ - The configuration options for the reusable sandbox. - `maxRequests` _: number_ (default: `1`, `0` means unlimited) - The maximum number of requests that can be handled by a single sandbox before it is recycled. - `betweenRequestTimeoutMs` _: number_ (default: not specified) - The amount of time in milliseconds to wait between requests before recycling the sandbox. - `maxMemoryMiB` _: number_ (default: no limit) - The maximum amount of memory in MiB that the sandbox can use before it is recycled. - `sandboxTimeoutMs` _: number_ (default: no timeout) - The maximum amount of time in milliseconds that a sandbox can be active before it is recycled. ================================================ FILE: documentation/versioned_docs/version-3.40.1/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object`, or `null` if no geolocation data was found. The object contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Blob/Blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob() The **`Blob()`** constructor creates a `Blob` object, which represents a file-like object of immutable, raw data. ## Syntax ```js new Blob() new Blob(array) new Blob(array, options) ``` > **Note:** `Blob()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `array` _**optional**_ - : An array of values to include in the `Blob`. These can be [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx), [`Blob`](../../globals/Blob/Blob.mdx), or strings. If any of these elements is a [`Blob`](../../globals/Blob/Blob.mdx), its content (and not the object itself) is copied into the Blob being constructed. - `options` _**optional**_ - : An object containing optional attributes for the `Blob`. - `type` - : A string indicating the MIME type of the data. The default value is the empty string `""`. - `endings` - : A string indicating how to handle line endings in the data. This can be either `"transparent"` (default) to keep line endings unchanged, or `"native"` to convert line endings to the platform's native line endings (e.g., `\r\n` on Windows). ### Return value A new `Blob` object containing the specified data. ## Description `Blob` objects represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting its functionality and expanding it to support files on the user's system. To construct a `Blob` from other non-blob objects and data, use the `Blob()` constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](../../globals/Blob/prototype/slice.mdx) method. The `type` property of a `Blob` object will match the MIME type specified in the constructor's `options` parameter, defaulting to an empty string if not specified. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Blob/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.arrayBuffer() The **`arrayBuffer()`** method of the `Blob` interface returns a `Promise` that resolves with an `ArrayBuffer` containing the entire contents of the `Blob` as binary data. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A `Promise` that resolves with an `ArrayBuffer` containing the blob's data. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Blob/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.size The **`size`** read-only property of the `Blob` interface returns the size of the `Blob` in bytes. ## Value A number representing the size of the `Blob` in bytes. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Blob/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.slice() The **`slice()`** method of the `Blob` interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. ## Syntax ```js slice() slice(start) slice(start, end) slice(start, end, contentType) ``` ### Parameters - `start` _**optional**_ - : The 0-based index of the first byte to include in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is 0. - `end` _**optional**_ - : The 0-based index of the first byte that will not be included in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is `size`. - `contentType` _**optional**_ - : A string indicating the content type to assign to the new `Blob`. The default value is an empty string. ### Return value A new `Blob` object containing the specified subset of data. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Blob/prototype/stream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.stream() The **`stream()`** method of the `Blob` interface returns a `ReadableStream` that can be used to read the contents of the `Blob`. ## Syntax ```js stream() ``` ### Parameters None. ### Return value A `ReadableStream` that provides the data contained within the `Blob`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Blob/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.text() The **`text()`** method of the `Blob` interface returns a `Promise` that resolves with a string containing the contents of the blob, interpreted as UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a string containing the blob's data as a text string. The data is always interpreted as UTF-8. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Blob/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.type The **`type`** read-only property of the `Blob` interface returns the MIME type of the `Blob`. ## Value A string indicating the MIME type of the `Blob`. If the type cannot be determined, this returns an empty string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/EcKeyImportParams/EcKeyImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcKeyImportParams The **`EcKeyImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as ECDSA. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/EcdsaParams/EcdsaParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcdsaParams The **`EcdsaParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `hash` - : A string. An identifier for the digest algorithm to use. This should be one of the following: - `SHA-256`: selects the SHA-256 algorithm. - `SHA-384`: selects the SHA-384 algorithm. - `SHA-512`: selects the SHA-512 algorithm. > **Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. While these fields are always defined on Compute, they may be *null* when not available in testing environments such as Viceroy. - `FetchEvent.client.requestId` _**readonly**_ - : A UUID generated by Compute for each request. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : Either `null`, or a [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. - `FetchEvent.client.tlsJA3MD5` _**readonly**_ - : Either `null` or a string representation of the JA3 hash of the TLS ClientHello message. - `FetchEvent.client.tlsCipherOpensslName` _**readonly**_ - : Either `null` or a string representation of the cipher suite used to secure the client TLS connection. - `FetchEvent.client.tlsProtocol` _**readonly**_ - : Either `null` or a string representation of the TLS protocol version used to secure the client TLS connection. - `FetchEvent.client.tlsClientCertificate` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw client certificate in the mutual TLS handshake message. It is in PEM format. Returns an empty ArrayBuffer if this is not mTLS or available. - `FetchEvent.client.tlsClientHello` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw bytes sent by the client in the TLS ClientHello message. - `FetchEvent.client.tlsJA4` _**readonly**_ - : Either `null` or a string representation of the JA4 fingerprint of the TLS ClientHello message. - `FetchEvent.client.h2Fingerprint` _**readonly**_ - : Either `null` or a string representation of the HTTP/2 fingerprint for HTTP/2 connections. Returns `null` for HTTP/1.1 connections. - `FetchEvent.client.ohFingerprint` _**readonly**_ - : Either `null` or a string representation of the Original Header fingerprint based on the order and presence of request headers. - `FetchEvent.server` _**readonly**_ - : Information about the server receiving the request for the Fastly Compute service. - `FetchEvent.server.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the server which received the request. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.sendEarlyHints()`](./prototype/sendEarlyHints.mdx) - : Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FetchEvent/prototype/sendEarlyHints.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.sendEarlyHints() The **`sendEarlyHints()`** method allows you to send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response back to the client which made the incoming request to your application. ## Syntax ```js sendEarlyHints(headers) ``` ### Parameters - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../Headers/Headers.mdx) object or object literal of [`String`](../../String/String.mdx) key/value pairs. ### Return value Always returns `undefined`. ### Examples ```js event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'] ]); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/FormData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData() The **`FormData()`** constructor creates a new `FormData` object. ## Syntax ```js new FormData() new FormData(form) ``` > **Note:** `FormData()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `form` _**optional**_ - : An HTML `` element — when specified, the `FormData` object will be populated with the form's current key/value pairs using the name property of each element for the keys and their submitted value for the values. File input elements are handled specially: their values are taken from the files selected by the user in the upload control. ### Return value A new `FormData` object, pre-populated with form data if the optional `form` parameter was provided. ## Description The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using methods such as `fetch()`. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also append additional data to the `FormData` object after it's created using its various methods. A `FormData` object can be used in a number of ways with other APIs: 1. It can be sent with the `fetch()` API 2. It works seamlessly with the `Request` and `Response` objects - it can be used directly as the body of a `Request` object 3. It can be obtained from a `Response` object using the `formData()` method 4. It can be passed directly to the `URLSearchParams` constructor The transmitted data is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to `"multipart/form-data"`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.append() The **`append()`** method of the `FormData` interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. ## Syntax ```js append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.delete() The **`delete()`** method of the `FormData` interface removes all key/value pairs with the given name from the `FormData` object. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.entries() The **`entries()`** method of the `FormData` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator yields a new array for each key/value pair, with the first element being the key and the second element being the value. ## Syntax ```js entries() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.forEach() The **`forEach()`** method of the `FormData` interface executes the provided callback function once for each key/value pair in the `FormData` object. ## Syntax ```js forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each entry in the object. The function will be passed the following arguments: - `value` - : The value of the current entry. - `key` - : The key of the current entry. - `formData` - : The `FormData` object being traversed. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.get() The **`get()`** method of the `FormData` interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the [`getAll()`](../../../globals/FormData/prototype/getAll.mdx) method instead. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value A `FormDataEntryValue` containing the value. If the key does not exist, it returns `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/prototype/getAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.getAll() The **`getAll()`** method of the `FormData` interface returns all the values associated with a given key from within a `FormData` object. ## Syntax ```js getAll(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value An array of `FormDataEntryValue` items containing all values with the given key. If the key doesn't exist, an empty array is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.has() The **`has()`** method of the `FormData` interface returns a boolean indicating whether a `FormData` object contains a key/value pair with the given name. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the key you want to test for existence. ### Return value `true` if a key/value pair with the specified name exists; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.keys() The **`keys()`** method of the `FormData` interface returns an iterator allowing iteration through all keys contained in this object. The iterator yields the key for each value. ## Syntax ```js keys() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.set() The **`set()`** method of the `FormData` interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and [`append()`](../../../globals/FormData/prototype/append.mdx) is that if the specified key already exists, `set()` overwrites all existing values with the new one, whereas `append()` appends the new value onto the end of the existing values. ## Syntax ```js set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/FormData/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.values() The **`values()`** method of the `FormData` interface returns an iterator allowing iteration through all values contained in this object. The iterator yields the value for each key/value pair. ## Syntax ```js values() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name is not the name of an HTTP header, this method throws a `TypeError`. The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/prototype/getSetCookie.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.getSetCookie() The **`getSetCookie()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns an array of all the values of the `Set-Cookie` headers, returning an empty list if none are present. ## Syntax ```js getSetCookie() ``` ### Return value `String[]` representing the list of `Set-Cookie` headers. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2 or greater than π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex where x is a number very close to 0, you should get an answer very close to 1 + x, because limx0ex1x=1. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, a `ReadableStream` object, a [`Blob`](../../globals/Blob/Blob.mdx) object, or a [`FormData`](../../globals/FormData/FormData.mdx) object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_, see [`CacheOverride`](../../fastly:cache-override/CacheOverride/CacheOverride.mdx). - `cacheKey` _**Fastly-specific**_ - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.blob() The **`blob()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/clone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.clone() The **`clone()`** method of the `Request` interface creates a copy of the current `Request` object. Like the underlying `ReadableStream.tee`` api, the `body` of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Beware when you construct a `Request` from a stream and then `clone` it. `clone()` throws a `TypeError` if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) If you intend to modify the request, you may prefer the `Request` constructor. ## Syntax ```js clone() ``` ### Parameters None. ### Return value A `Request` object, which is an exact copy of the `Request` that `clone()` was called on. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.formData() The **`formData()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. - `SyntaxError` - : Thrown if the request's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Request` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Request instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - [`Blob`](../../globals/Blob/Blob.mdx) - [`FormData`](../../globals/FormData/FormData.mdx) - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.blob() The **`blob()`** method of the [`Response`](../Response.mdx) interface takes a [`Response`](../Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.formData() The **`formData()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. - `SyntaxError` - : Thrown if the response's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/ip.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ip The **`ip`** getter of the `Response` interface returns the IP address associated with the request, as either an IPv6 or IPv4 string. In the case where no IP address is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with an IP, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `string`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.port The **`port`** getter of the `Response` interface returns the port associated with the request, as a number. In the case where no port is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with a port, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `number`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Response` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Response instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - For ECDSA: Pass an [`EcKeyImportParams`](../../EcKeyImportParams/EcKeyImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](https://en.wikipedia.org/wiki/HZ_(character_encoding)). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Explicit Backends Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service. This `backend` option is then a special Fastly-specific fetch option that is provided to the `fetch()` call: ```js fetch('https://origin.com/path', { backend: 'origin' }); ``` Backends are configured using the Fastly service backend configuration, see the [Backend documentation](https://developer.fastly.com/reference/api/services/backend/) for more information. ## Dynamic Backends Dynamic backends are a compute feature that allow services to define backends for themselves. If the `backend` option is not provided when making `fetch()` requests, a backend will be automatically created by extracting the protocol, host, and port from the provided URL. In addition, custom backend configuration options can then also be provided through the [`Backend()`](../fastly:backend/Backend/Backend.mdx) constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ - `imageOptimizerOptions` _**Fastly-specific**_, see [`imageOptimizerOptions`](../fastly:image-optimizer/imageOptimizerOptions.mdx). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-3.40.1/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/after.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # after The `after` method inserts content after the closing tag of the element. ## Syntax ```js element.after(content); element.after(content, options); ``` ### Parameters - `content` _: string_ - The content to insert after the element's closing tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.after("World"); // Result:
Hello
World ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # append The `append` method inserts content at the end of the element's content. ## Syntax ```js element.append(content); element.append(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the end of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.append(", World"); // Result:
Hello, World
``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/before.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # before The `before` method inserts content before the opening tag of the element. ## Syntax ```js element.before(content); element.before(content, options); ``` ### Parameters - `content` _: string_ - The content to insert before the element's opening tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.before("Well"); // Result: Well
Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/hasAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # hasAttribute The `hasAttribute` method returns a `boolean` value indicating whether the specified attribute is present on the element. ## Syntax ```js element.hasAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to check for. ### Return value A boolean value indicating whether the attribute is present. ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/prepend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # prepend The `prepend` method inserts content at the beginning of the element's content. ## Syntax ```js element.prepend(content); element.prepend(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the beginning of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.prepend("Well, "); // Result:
Well, Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/removeAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # removeAttribute The `removeAttribute` method removes the specified attribute from the element. ## Syntax ```js element.removeAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to remove. ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/replaceChildren.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceChildren The `replaceChildren` method replaces the element's children with new content. ## Syntax ```js element.replaceChildren(content); element.replaceChildren(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element's children with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceChildren("Greetings!"); // Result:
Greetings!
``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/replaceWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceWith The `replaceWith` method replaces the element with new content. ## Syntax ```js element.replaceWith(content); element.replaceWith(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceWith("

Greetings!

"); // Result:

Greetings!

``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/selector.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # selector The `selector` read-only property is a `string` representing the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) that matches the element. ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/setAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setAttribute The `setAttribute` method sets the value of the specified attribute on the element. If the value already exists, it will be updated; otherwise, a new attribute with the specified name and value will be added to the element. ## Syntax ```js element.setAttribute(attributeName, value); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to set. - `value` _: string_ - The value to assign to the attribute. ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/Element/prototype/tag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # tag The `tag` read-only property is a `string` representing the tag name of the element. ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/HTMLRewritingStream/HTMLRewritingStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `HTMLRewritingStream()` The **`HTMLRewritingStream`** lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback. This callback can manipulate the attributes of the element, and add or remove content from the immediate context. ## Syntax ```js new HTMLRewritingStream() ``` ### Return value A new `HTMLRewritingStream` object. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/html-rewriter/HTMLRewritingStream/prototype/onElement.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # onElement ▸ **onElement**`(selector: string, handler: (element: Element) => void): this` Registers an element handler with the [`HTMLRewritingStream`] that will be called for each [`Element`] that matches the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) `selector`. Elements added by handlers will not be processed by other handlers. ## Syntax ```js .onElement(selector, handler) ``` ### Parameters - `selector` _: string_ - A CSS selector that determines the elements for which `handler` will be called - The following types of CSS selector are supported: Currently the rewriter supports the following CSS selectors: | Pattern | Description | |----------------------|----------------------------------------------------------------------------| | `*` | Any element | | `E` | All elements of type `E` | | `E F` | `F` elements inside `E` elements | | `E > F` | `F` elements directly inside `E` elements | | `E:nth-child(n)` | The n-th child of type `E` | | `E:first-child` | First child of type `E` | | `E:nth-of-type(n)` | The n-th sibling of type `E` | | `E:first-of-type` | First sibling of type `E` | | `E:not(s)` | Type `E` elements not matching selector `s` | | `E.myclass` | Type `E` elements with class `"myclass"` | | `E#myid` | Type `E` elements with ID `"myid"` | | `E[attr]` | Type `E` elements with attribute `attr` | | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | | `E[attr="val" i]` | Type `E` elements where `attr` is `"val"`, case-insensitive | | `E[attr="val" s]` | Type `E` elements where `attr` is `"val"`, case-sensitive | | `E[attr~="val"]` | Type `E` elements where `attr` contains `"val"` in a space-separated list | | `E[attr`|`;="val"]`| Type `E` elements where `attr` is hyphen-separated and starts with `"val"` | | `E[attr^="val"]` | Type `E` elements where `attr` starts with `"val"` | | `E[attr$="val"]` | Type `E` elements where `attr` ends with `"val"` | | `E[attr*="val"]` | Type `E` elements where `attr` contains `"val"` | - `handler` _: (element: Element) => void_ - A callback function that will be called once for each element that matches `selector` ### Return value The `HTMLRewritingStream`, so multiple calls to `onElement` can be chained. ### Exceptions - `Error` - If the provided `selector` is not a valid CSS selector. - If the provided `handler` is not a function. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/Auto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Auto` Enumerator options for [`imageOptimizerOptions.auto`](./imageOptimizerOptions.mdx). ## Constants - `AVIF` (`"avif"`) If the browser's Accept header indicates compatibility, deliver an AVIF image. - `WEBP` (`"webp"`) If the browser's Accept header indicates compatibility, deliver a WebP image. ## Examples ```js import { Auto, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, auto: Auto.AVIF }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/BWAlgorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `BWAlgorithm` Enumerator options for [`imageOptimizerOptions.bw`](./imageOptimizerOptions.mdx). ## Constants - `Threshold` (`"threshold"`) Uses a luminance threshold to convert the image to black and white. - `Atkinson` (`"atkinson"`) Uses [Atkinson dithering](https://en.wikipedia.org/wiki/Atkinson_dithering) to convert the image to black and white. ## Examples ```js import { Region, BWAlgorithm } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, bw: BWAlgorithm.Threshold }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/CropMode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CropMode` Enumerator options for [`imageOptimizerOptions.crop.mode`](./imageOptimizerOptions.mdx) and `imageOptimizerOptions.precrop.mode`. ## Constants - `Smart` (`"smart"`) Enables content-aware algorithms to attempt to crop the image to the desired aspect ratio while intelligently focusing on the most important visual content, including the detection of faces. - `Safe` (`"safe"`) Allow cropping out-of-bounds regions. ## Examples ```js import { CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Smart, } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/Disable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Disable` Enumerator options for [`imageOptimizerOptions.disable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Prevent images being resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Disable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, disable: Disable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/Enable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Enable` Enumerator options for [`imageOptimizerOptions.enable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Allow images to be resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Enable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, enable: Enable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/Fit.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Fit` Enumerator options for [`imageOptimizerOptions.fit`](./imageOptimizerOptions.mdx). ## Constants - `Bounds` (`"bounds"`) Resize the image to fit entirely within the specified region, making one dimension smaller if needed. - `Cover` (`"cover"`) Resize the image to entirely cover the specified region, making one dimension larger if needed. - `Crop` (`"crop"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Fit, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 150, height; 150, fit: Fit.Bounds }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/Format.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Format` Enumerator options for [`imageOptimizerOptions.format`](./imageOptimizerOptions.mdx). ## Constants - `Auto` (`"auto"`) Automatically use the best format based on browser support and image/transform characteristics - `AVIF` (`"avif"`) AVIF - `BJPG` (`"bjpg"`) Baseline JPEG - `GIF` (`"gif"`) Graphics Interchange Format - `JPG` (`"jpg"`) JPEG - `JXL` (`"jxl"`) JPEGXL - `MP4` (`"mp4"`) MP4 (H.264) - `PJPG` (`"pjpg"`) Progressive JPEG - `PJXL` (`"pjxl"`) Progressive JPEGXL - `PNG` (`"png"`) Portable Network Graphics - `PNG8` (`"png8"`) Portable Network Graphics palette image with 256 colors and 8-bit transparency - `SVG` (`"svg"`) Scalable Vector Graphics - `WEBP` (`"webp"`) WebP - `WEBPLL` (`"webpll"`) WebP (Lossless) - `WEBPLY` (`"webply"`) WebP (Lossy) ## Examples ```js import { Format, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/Metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Metadata` Enumerator options for [`imageOptimizerOptions.metadata`](./imageOptimizerOptions.mdx). ## Constants - `Copyright` (`"copyright"`) Preserve [copyright notice](https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#copyright-notice), creator, credit line, licensor, and web statement of rights fields. - `C2PA` (`"c2pa"`) Preserve the [C2PA manifest](https://c2pa.org/) and add any transformations performed by Fastly Image Optimizer. - `CopyRightAndC2PA` (`"copyright,c2pa"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Metadata, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, metadata: Metadata.Copyright }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/Optimize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Optimize` Enumerator options for [`imageOptimizerOptions.optimize`](./imageOptimizerOptions.mdx). ## Constants - `Low` (`"low"`) Output image quality will be similar to the input image quality. - `Medium` (`"medium"`) More optimization is allowed. We attempt to preserve the visual quality of the input image. - `High` (`"high"`) Minor visual artifacts may be visible. This produces the smallest file. ## Examples ```js import { Optimize, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, optimize: Optimize.High }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/Orient.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Orient` Enumerator options for [`imageOptimizerOptions.orient`](./imageOptimizerOptions.mdx). ## Constants - `Default` (`"1"`) - `FlipHorizontal` (`"2"`) - `FlipHorizontalAndVertical` (`"3"`) - `FlipVertical` (`"4"`) - `FlipHorizontalOrientLeft` (`"5"`) - `OrientRight` (`"6"`) - `FlipHorizontalOrientRight` (`"7"`) - `OrientLeft` (`"8"`) ## Examples ```js import { Orient, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, orient: Orient.FlipHorizontal }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/Profile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Profile` Enumerator options for [`imageOptimizerOptions.profile`](./imageOptimizerOptions.mdx). ## Constants - `Baseline` (`"baseline"`) The profile recommended for video conferencing and mobile applications. (Default) - `Main` (`"main"`) The profile recommended for standard-definition broadcasts. - `High` (`"high"`) The profile recommended for high-definition broadcasts. ## Examples ```js import { Profile, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, profile: Profile.Main }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/Region.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Region` Enumerator options for [`imageOptimizerOptions.region`](./imageOptimizerOptions.mdx). ## Constants - `UsEast` (`"us_east"`) - `UsCentral` (`"us_central"`) - `UsWest` (`"us_west"`) - `EuCentral` (`"eu_central"`) - `EuWest` (`"eu_west"`) - `Asia` (`"asia"`) - `Australia` (`"australia"`) ## Examples ```js import { Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/ResizeFilter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ResizeFilter` Enumerator options for [`imageOptimizerOptions.resizeFilter`](./imageOptimizerOptions.mdx). ## Constants - `Nearest` (`"nearest"`) Uses the value of nearby translated pixel values. - `Bilinear` (`"bilinear"`) Uses an average of a 2x2 environment of pixels. - `Linear` (`"linear"`) Same as `Bilenear`. - `Bicubic` (`"bicubic"`) Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. - `Cubic` (`"cubic"`) Same as `Bicubic`. - `Lanczos2` (`"lanczos2"`) Uses the Lanczos filter to increase the ability to detect edges and linear features within an image and uses sinc resampling to provide the best possible reconstruction. - `Lanczos3` (`"lanczos3"`) Lanczos3 uses a better approximation of the sinc resampling function. (Default) - `Lanczos` (`"lanczos"`) Same as `Lanczos3`. ## Examples ```js import { ResizeFilter, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, resizeFilter: ResizeFilter.Linear }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/image-optimizer/imageOptimizerOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `imageOptimizerOptions` Options specified in the [`Request`](../globals/Request/Request.mdx) constructor for running the [Fastly Image Optimizer](https://docs.fastly.com/products/image-optimizer). More detailed documentation on all Image Optimizer options is available in the [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/). ## Parameters All parameters other than `region` are optional. - `region`: _[`Region`](./Region.mdx)_ Where image optimizations should occur. - `auto`: _[`Auto`](./Auto.mdx)_ Enable optimization features automatically. - `bgColor`: _[`Color`](#color)_ Set the background color of an image. - `blur`: _`number` (0.5-1000) or [`Percentage`](#percentage)_ Set the blurriness of the output image. - `brightness`: _`number` (-100-100)_ Set the brightness of the output image. - `bw`: _[`BWAlgorithm`](./BWAlgorithm.mdx)_ Convert an image to black and white. - `canvas`: _`Object`_ Increase the size of the canvas around an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `contrast`: _`number` (-100-100)_ Set the contrast of the output image. - `crop`: _`Object`_ Remove pixels from an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `mode` (optional): _[`CropMode`](./CropMode.mdx)_ - `disable`: _[`Disable`](./Disable.mdx)_ Disable functionality that is enabled by default. - `dpr`: `number` Ratio between physical pixels and logical pixels. - `enable`: _[`Enable`](./Enable.mdx)_ Enable functionality that is disabled by default. - `fit`: _[`Fit`](./Fit.mdx)_ Set how the image will fit within the size bounds provided. - `format`: _[`Format`](./Format.mdx)_ Specify the output format to convert the image to. - `frame`: _`number` (must have the value 1)_ Extract the first frame from an animated image sequence. - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the height of the image. - `level`: _`String` containing one of the [allowed values](https://www.fastly.com/documentation/reference/io/level/#allowed-values)_ Specify the level constraints when converting to video. - `metadata`: _[`Metadata`](./Metadata.mdx)_ Control which metadata fields are preserved during transformation. - `optimize`: _[`Optimize`](./Optimize.mdx)_ Automatically apply optimal quality compression. - `orient`: _[`Orient`](./Orient.mdx)_ Change the cardinal orientation of the image. - `pad`: _[`Sides`](#sides)_ Add pixels to the edge of an image. - `precrop`: _`Object`_ Remove pixels from an image before any other transformations occur. - `size`: _[`Size`](#size)_ - `position`: _[`Position`](#position)_ - `mode`: _[`CropMode`](./CropMode.mdx)_ - `profile`: _[`Profile`](./Profile.mdx)_ Specify the profile class of application when converting to video. - `quality`: _`integer` (1-100)_ Optimize the image to the given compression level for lossy file formatted images. - `resizeFilter`: _[`ResizeFilter`](./ResizeFilter.mdx)_ Specify the resize filter used when resizing images. - `saturation`: _`number` (-100-100)_ Set the saturation of the output image. - `sharpen`: _`Object`_ Set the sharpness of the output image. - `amount`: _`number` (0-10)_ - `radius`: _`number` (0.5-1000)_ - `threshold`: _`integer` (0-255)_ - `trim`: _[`Sides`](#sides)_ Remove pixels from the edge of an image. - `viewbox`: _`number` (must have the value 1)_ Remove explicit width and height properties in SVG output. - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the width of the image. ## Types ### Color Either: - a 3 or 6 character hexadecimal string - an `Object` containing: - `r`: _`integer` (0-255)_ Red component - `g`: _`integer` (0-255)_ Green component - `b`: _`integer` (0-255)_ Blue component - `a` (optional): _`number` (0.0-1.0)_ Alpha component ### Percentage A `String` containing a number suffixed with a percent sign (%). ### Position An `Object` containing: - Exactly one of: - `x`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetX`: _`number` (interpreted as a percentage)_ - Exactly one of: - `y`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetY`: _`number` (interpreted as a percentage)_ ### Sides An `Object` containing `top`, `bottom`, `left`, and `right`, all of which are either an `integer` or [`Percentage`](#percentage). ### Size An `Object` containing either: - `absolute`: _`Object`_ - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `ratio`: _`Object`_ - `width`: _`number`_ - `height`: _`number`_ ## Examples ```js import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG, bgColor: { 'r': 100, 'g': 255, 'b': 9, 'a': 0.5 }, blur: '1%', brightness: -20, contrast: -20, height: 600, level: '4.0', orient: Orient.FlipVertical, saturation: 80, sharpen: { 'amount': 5, 'radius': 6, 'threshold': 44 }, canvas: { 'size': { 'absolute': { 'width': 400, 'height': 400 } } }, crop: { size: { absolute: { width: 200, height: 200 }, mode: CropMode.Safe } }, trim: { top: 10, left: 10, right: 10, bottom: 10 }, pad: { top: 30, left: 30, right: "1%", bottom: 30 } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a KV store instance using the resource link name. ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStore/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.delete Deletes the value associated with the key `key` in the KV store. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value Returns `undefined` ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - Does not exist ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then delete the entry. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') await files.delete('hello') const entry = await files.get('hello') if (entry) { return new Response(await entry.text()) } else { return new Response('no file named hello exists') } } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStore/prototype/list.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.list The **`list()`** can be used to list the keys of a store. ## Syntax ```js list(options?) ``` ### Parameters - `options` _: object_ _**optional**_ - List options supporting properties: - `cursor` _: string_ _**optional**_ - The cursor used to pick up from a previous iteration. - `limit` _: number_ _**optional**_ - The maximum number of keys to return. - `prefix` _: string_ _**optional**_ - List only those keys that start with the given string prefix. - `noSync` _: boolean_ _**optional**_ - Do not sync the key list first, instead provide a possibly out-of-date listing. May be faster but inconsistent. ### Return value Returns a `Promise` which resolves with `{ list: string[], cursor: string | undefined }`. ## Example In this example we list the keys of a KV Store named `'files'`, iterating 10 at a time, counting the total; ```js /// import { KVStore } from 'fastly:kv-store'; async function app(event) { const files = new KVStore('files'); let cursor, list, total = 0; do { ({ cursor, list } = await files.list({ limit: 10, cursor })); total += list?.length; } while (list); return new Response(`Iterated ${total} entries`); } addEventListener('fetch', (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value, options?) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. - `options` _: object_ _**optional**_ - An insert options parameter, supporting: - `metadata` _: ArrayBuffer | TypedArray | DataView_ _**optional**_ - Binary metadata associated with the entry, may be up to 1000 bytes. - `ttl` _: number_ _**optional**_ - TTL for the entry - `mode` _: 'overwrite' | 'add' | 'append' | 'prepend'_ _**optional**_ - Insert mode, defaults to 'overwrite' - `gen` _: number_ _**optional**_ - 'generation' header specific to the version of an entry key ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - `TypeError` - If the provided `gen`: - Is not an number ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStoreEntry/prototype/metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadata() The `metadata()` method of the `KVStoreEntry` interface provides the binary metadata associated with the `KVStoreEntry`. The metadata binary may be up to 1000 bytes, and is returned as a `Uint8Array` TypedArray buffer, if metadata is set, or null otherwise. ## Syntax ```js metadata() ``` ### Parameters None. ### Return value A `Promise` that resolves to a `Uint8Array` buffer object. ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStoreEntry/prototype/metadataText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadataText() The `metadataText()` method of the `KVStoreEntry` interface provides a String interpretation of binary metadata associated with the `KVStoreEntry`. If the binary data is not a valid string, an encoding error will be thrown. ## Syntax ```js metadataText() ``` ### Parameters None. ### Return value A `Promise` that resolves to a String. ================================================ FILE: documentation/versioned_docs/version-3.40.1/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; const logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; let logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/logger/configureConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # configureConsole The **`configureConsole()`** function allows configuring the behaviour of the `console` global JS logger. ## Syntax ```js configureConsole(loggingOptions) ``` ### Parameters - `loggingOptions` _: object_ - - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ## Examples In this example, we disable prefixing for `console.log` and use `stderr` output for `console.error`: ```js import { configureConsole } from "fastly:logger"; configureConsole({ prefixing: false, stderr: true }); async function handleRequest(event) { console.log(JSON.stringify(event.request.headers)); const url = new URL(event.request.url); try { validate(url); } catch (e) { console.error(`Validation error: ${e}`); return new Response('Bad Request', { status: 400 }); } return new Response('OK'); } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v2 to v3` ## SimpleCache.delete renamed to SimpleCache.purge and requires purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using `SimpleCache.delete` to `SimpleCache.purge` with the same purging behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a Secret Store instance using the resource link name. ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/secret-store/SecretStore/fromBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fromBytes The **`fromBytes()`** function is used to create an in-memory secret from an array buffer. >**Note**: This API should be avoided when possible, by instead using [SecretStore.prototype.get](./prototype/get.mdx) to obtain secure secrets. ## Syntax ```js fromBytes(new Uint8Array([1, 2, 3])) ``` ### Parameters None. ### Return value Returns a `SecretStoreEntry`. ================================================ FILE: documentation/versioned_docs/version-3.40.1/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/secret-store/SecretStoreEntry/prototype/rawBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.rawBytes ▸ **rawBytes**(): `Uint8Array` Returns the raw byte contents of the SecretStoreEntry instance as a Uint8Array. ## Syntax ```js rawBytes() ``` ### Parameters None. ### Return value A Uint8Array ### Exceptions The `rawBytes()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ================================================ FILE: documentation/versioned_docs/version-3.40.1/security/inspect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # inspect The **`inspect()`** function inspects a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). ## Syntax ```js inspect(request, config); ``` ### Parameters - `request` _: Request_ - The Request to get a WAF determination for. - `config` _: object_ - `corp` _: string_ - Set a corp name for the configuration. - This parameter is currently required. - `workspace` _: string_ - Set a workspace name for the configuration. - This parameter is currently required. - `overrideClientIp` _: string_ - Specify an explicit client IP address to inspect. - By default, `inspect` will use the IP address that made the request to the running Compute service, but you may want to use a different IP when service chaining or if requests are proxied from outside of Fastly’s network. ### Return value Returns an `Object` with the `inspect` response, with the following fields: - `waf_response` _: number_ - Security status code. - `redirect_url` _: string | null_ - A redirect URL returned from Security. - `tags` _: string[]_ - Tags returned by Security. - `verdict` _: string_ - The outcome of inspecting a request with Security. It can be one of the following: - `"allow"` - Security indicated that this request is allowed. - `"block"` - Security indicated that this request should be blocked. - `"unauthorized"` - Security indicated that this service is not authorized to inspect a request. - Other verdicts may be returned but not currently documented. - `decision_ms` _: number_ - How long Security spent determining its verdict, in milliseconds. ## Examples ```js /// import { inspect } from "fastly:security"; async function app(event) { const res = inspect(event.request, { corp: "mycorp", workspace: "myws" }); switch (res.verdict) { case "allow": return await fetch(event.request); case "block": return new Response("Request Blocked", { status: 400 }); case "unauthorized": return new Response("Unauthorized", { status: 401 }); default: return new Response("idk", { status: 500 }); } } addEventListener("fetch", (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/shielding/Shield/Shield.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Shield()` Load information about the given shield. Returns an object representing the shield if it is active, or throws an exception if the string is malformed or the shield doesn’t exist. Shield names are defined on [this webpage](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations), in the “shield code” column. For example, the string “pdx-or-us” will look up our Portland, OR, USA shield site, while “paris-fr” will look up our Paris site. If you are using a major cloud provider for your primary origin site, consider looking at the “Recommended for” column, to find the Fastly POP most closely located to the given cloud provider. ## Syntax ```js new Shield(name) ``` > **Note:** `Shield()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Exceptions - `TypeError` - Thrown if no Shield exists with the provided name ## Examples In this example, we create a Shield instance for the Sydney, Australia shield POP. If the code is running on that shield POP, it fetches directly from origin. Otherwise, it routes the request through the shield using an encrypted connection. ```js /// import { Shield } from "fastly:shielding"; async function app(event) { const shield = new Shield('wsi-australia-au'); // If running on the shield POP, fetch from the origin directly if (shield.runningOn()) { return await fetch('https://http-me.fastly.com/anything', { backend: 'httpme' }); } // Otherwise, route the request through the shield using an encrypted connection return await fetch(event.request, { backend: shield.encryptedBackend() }); } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.40.1/shielding/Shield/prototype/encryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.encryptedBackend ▸ **encryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an encrypted connection to the POP. For reference, this is almost always the backend that you want to use. Only use [`Shield::unencryptedBackend`](./unencryptedBackend.mdx) in situations in which you are 100% sure that all the data you will send and receive over the backend is already encrypted. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.40.1/shielding/Shield/prototype/runningOn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.runningOn ▸ **runningOn**(): `boolean` Returns whether we are currently operating on the given shield. Technically, this may also return true in very isolated incidents in which Fastly is routing traffic from the target shield POP to the POP that this code is running on, but in these situations the results should be approximately identical. (For example, it may be the case that you are asking to shield to ‘pdx-or-us’. But, for load balancing, performance, or other reasons, Fastly is temporarily shifting shielding traffic from Portland to Seattle. In that case, this function may return true for hosts running on ‘bfi-wa-us’, our Seattle site, because effectively the shield has moved to that location. This should give you a slightly faster experience than the alternative, in which this function would return false, you would try to forward your traffic to the Portland site, and then that traffic would be caught and redirected back to Seattle.) ================================================ FILE: documentation/versioned_docs/version-3.40.1/shielding/Shield/prototype/unencryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.unencryptedBackend ▸ **unencryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an unencrypted connection to the POP. Generally speaking, we encourage users to use [`Shield::encryptedBackend`](./encryptedBackend.mdx) instead of this function. Data sent over this backend – the unencrypted version – will be sent over the open internet, with no protections. In most cases, this is not what you want. However, in some cases – such as when you want to ship large data blobs that you know are already encrypted — using these backends can prevent a double-encryption performance penalty. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.40.1/websocket/createWebsocketHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createWebsocketHandoff The **`createWebsocketHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Websocket, to the declared backend. ## Syntax ```js createWebsocketHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Websocket. - `backend` _: string_ - The name of the backend that Websocket should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Websocket. ```js import { createWebsocketHandoff } from "fastly:websocket"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createWebsocketHandoff(event.request, 'websocket_backend'); } else { return new Response('oopsie, make a request to /stream for some websocket goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/acl/Acl/open.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.open() Opens the ACL with the given name, returning a new `Acl` instance with the given name on success. ## Syntax ```js Acl.open(name) ``` ### Return value An `Acl` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.0/acl/Acl/prototype/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.prototype.lookup() The **`lookup(ipAddress)`** method returns the name associated with the `Acl` instance. ## Syntax ```js acl.lookup(ipAddress) ``` ### Parameters - `ipAddress` _: string_ - IPv4 or IPv6 address to lookup ### Return value An Object of the form `{ action: 'ALLOW' | 'BlOCK', prefix: string }`, where `prefix` is the IP address prefix that was matched in the ACL. ## Example ```js /// import { Acl } from 'fastly:acl'; addEventListener('fetch', async (evt) => { const myAcl = Acl.open('myacl'); const match = await myAcl.lookup(evt.client.address); evt.respondWith(new Response(match?.action === 'BLOCK' ? 'blocked' : 'allowed')); }); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. >**Note**: Dynamic backends are by default disabled at the Fastly service level. Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request dynamic backends on Fastly Services. To disable the usage of dynamic backends, see [enforceExplicitBackends](../enforceExplicitBackends.mdx). ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. - `grpc` _: boolean_ _**optional**_ - **_Experimental feature_** - When enabled, sets that this backend is to be used for gRPC traffic. - _Warning: When using this experimental feature, no guarantees are provided for behaviours for backends that do not provide gRPC traffic._ All optional generic options can have their defaults set via [`setDefaultDynamicBackendConfig()`](../setDefaultDynamicBackendConfig.mdx). This includes all configuration options above except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. ### Return value A new `Backend` object. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/exists.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.exists() The **`Backend.exists()`** method returns a boolean indicating if a Backend with the given name exists or not. ## Syntax ```js exists(name) ``` ### Return value A boolean indicating if a Backend with the given name exists or not. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/fromName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.fromName() Returns the `Backend` instance with the given name, if one exists. If one does not exist, an error is thrown. ## Syntax ```js fromName(name) ``` ### Return value A `Backend` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.health() :::info This method is deprecated, use [`Backend.prototype.health`](./prototype/health.mdx) instead. ::: The **`Backend.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js Backend.health(backend) ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/betweenBytesTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.betweenBytesTimeout The read-only **`betweenBytesTimeout`** property of a `Backend` instance is an integer number providing the between bytes timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/connectTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.connectTimeout The read-only **`connectTimeout`** property of a `Backend` instance is an integer number providing the connect timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/firstByteTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.firstByteTimeout The read-only **`firstByteTimeout`** property of a `Backend` instance is an integer number providing the first byte timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.health() The **`Backend.prototype.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js health() ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/hostOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.hostOverride The read-only **`hostOverride`** property of a `Backend` instance is the host header override string used when sending requests to this backend. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/httpKeepaliveTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.httpKeepaliveTime The read-only **`httpKeepaliveTime`** property of a `Backend` instance is the HTTP keepalive time for this backend in milliseconds, or 0 if no keepalive is set. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/isDynamic.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isDynamic The read-only **`isDynamic`** property of a `Backend` instance is a boolean indicating if the backend was dynamically created for this service. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/isSSL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isSSL The read-only **`isSSL`** property of a `Backend` instance is a boolean indicating if the backend is using an SSL connection. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # name The read-only **`name`** property of the backend returns the backend name string. ## Value A `string`. ## Description Provides the name of the backend. ## Examples ### Using name The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.port The read-only **`port`** property of a `Backend` instance is the port number of this backend. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/target.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.target The read-only **`target`** property of a `Backend` instance is the host string this backend is configured to use. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/tcpKeepalive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tcpKeepalive The read-only **`tcpKeepalive`** property of a `Backend` instance returns an object providing the TCP keepalive configuration, if any, otherwise returning `null` if TCP keepalive is not enabled. This object has the following properties: - `timeSecs` _: number or null._ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number or null._ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number or null._ - Number of probes to send to the backend before it is considered dead. ## Value A `Object` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/tlsMaxVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMaxVersion The read-only **`tlsMaxVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/tlsMinVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMinVersion The read-only **`tlsMinVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/toName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.toName() :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toName()`** method returns the name associated with the `Backend` instance. ## Syntax ```js toName() ``` ### Return value A string which contains the name of the Backend. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toString :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends :::info This method is deprecated, and dynamic backends are now always supported when enabled at the service level. See [`enforceExplicitBackends`](./enforceExplicitBackends.mdx) instead. ::: The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: By default, while dynamic backends are allowed in the SDK, they are by default disabled at the Fastly service level. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/enforceExplicitBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enforceExplicitBackends Call this function to enforce the security property of explicitly-defined backends, even when dynamic backends are enabled at the Fastly service level. By default, if dynamic backends are supported for the Fastly service, they will be automatically used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a potential security concern since third-party JavaScript code may send arbitrary requests, including sensitive/secret data, off to destinations that the JavaScript project was not intending. When calling this function, an optional default backend name can be provided. >**Note**: This is a separate option to the service-level dynamic backend support for Fastly services, which is by deault disabled for Fastly services. The **`enforceExplicitBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: Dynamic Backends are disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled or disabled on Fastly Services. ## Syntax ```js enforceExplicitBackends(defaultBackend?) ``` ### Parameters - `defaultBackend` _: string_ _**optional**_ - An optional default backend string name to use in `fetch()` requests. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/backend/setDefaultDynamicBackendConfig.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setDefaultDynamicBackendConfig() The **`setDefaultDynamicBackendConfig()`** allows setting backend configuration defaults that should apply to any newly created dynamic backends via the `new Backend()` constructor. ### Parameters - `defaultDynamicBackendConfig` - : An Object which contains the generic configuration options to apply to newly created Backends. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. ## Syntax ```js setDefaultDynamicBackendConfig(defaultConfig) ``` ### Return value None. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, with timeouts and TLS options provided from the default backend configuration options. import { allowDynamicBackends } from "fastly:experimental"; import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! // Timeouts and TLS configuration still get set from the default backend configuration above. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.age The **`age`** method of the `CacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.body The **`body`** method of the `CacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this `CacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.close The **`close`** method of the `CacheEntry` interface closes the connection to the cache for this `CacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.hits The **`hits`** method of the `CacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.length The **`length`** method of the `CacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.maxAge The **`maxAge`** method of the `CacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `CacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.state The **`state`** method of the `CacheEntry` interface returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.userMetadata The **`userMetadata`** method of the `CacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheState/found.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.found The **`found`** method of the `CacheState` interface returns `true` if a cached item was located. Even if an cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. ## Syntax ```js found() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item was located or not. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheState/mustInsertOrUpdate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.mustInsertOrUpdate The **`mustInsertOrUpdate`** method of the `CacheState` interface returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. ## Syntax ```js mustInsertOrUpdate() ``` ### Parameters None. ### Return value A `boolean` which represents whether a fresh cached item was found not. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheState/stale.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.stale The **`stale`** method of the `CacheState` interface returns `true` if the cached item is stale. A cached item is stale if its age is greater than its `maxAge` period. ## Syntax ```js stale() ``` ### Parameters None. ### Return value A `boolean` which represents whether the cached item is stale or not. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CacheState/usable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.usable The **`usable`** method of the `CacheState` interface returns `true` if the cached item is usable. A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. ## Syntax ```js usable() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item is usable or not. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CoreCache/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.insert Performs a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. ## Syntax ```js insert(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item’s contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CoreCache/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.lookup Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. ## Syntax ```js lookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns `CacheEntry` if a usable cached item was found, otherwise returns `null`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/CoreCache/transactionLookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.transactionLookup Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. Request Collapsing: If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, just one of the callers will be instructed to insert the item into the cache as part of the transaction. The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. Revalidation: Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. ## Syntax ```js transactionLookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns an instance of `TransactionCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, and return a message stating whether the entry was in the Fastly Cache or not. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); return new Response(page ? `${path} is in the cache` : `${path} is not in the cache`, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key`. If no entry is found (or has expired), the supplied `set` function is executed and its result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - The function to execute if and only if the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The maximum number of seconds to store the supplied entry in the cache. - `length` _: number_ __optional__ - The length of the value being stored within the cache. This is only used when the `value` is a `ReadableStream`. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/SimpleCache/purge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.purge purge the entry associated with the key `key` from the cache. ## Syntax ```js purge(key, options) ``` ### Parameters - `key` _: string_ - The key to purge from within the cache. - `options` _: object_ - `scope` _: string_ - : Where to purge the content from. - Possible values are: - "global" - This will remove the content from all of Fastly. - "pop" - This will remove the content from the POP that contains the currently executing instance. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `purge` querystring parameter, we purge the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('purge')) { SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.age The **`age`** method of the `TransactionCacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.body The **`body`** method of the `TransactionCacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `TransactionCacheEntry`. An error will be thrown if a stream is already active for this `TransactionCacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.cancel The **`cancel`** method of the `TransactionCacheEntry` interface cancels an obligation to provide an object to the cache. ## Syntax ```js cancel() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.close The **`close`** method of the `TransactionCacheEntry` interface closes the connection to the cache for this `TransactionCacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.hits The **`hits`** method of the `TransactionCacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insert Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. ## Syntax ```js insert(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/insertAndStreamBack.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insertAndStreamBack Perform a transaction cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. ## Syntax ```js insertAndStreamBack(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns an array where the first item is a `FastlyBody` instance and the second item is a `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.length The **`length`** method of the `TransactionCacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.maxAge The **`maxAge`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.state The **`state`** method of the `TransactionCacheEntry` interface returns a `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/update.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.update Perform an update of the cache item's metadata. ## Syntax ```js update(options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache/TransactionCacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.userMetadata The **`userMetadata`** method of the `TransactionCacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.0/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) new CacheOverride(init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. This options is also the default when providing an init object directly as the first argument. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. - `beforeSend` _:Function_ _**optional**_ - `(request: Request) => void | PromiseLike` - Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. - See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) in the Fastly cache interfaces documentation for details. - `afterSend` _: Function_ _**optional**_ - `(response: Response) => void | CacheOptions | PromiseLike` - Callback to be invoked after a response has been sent, but before it is stored into the cache. - Where `CacheOptions` contains: - `cache` _: boolean | 'uncacheable'_ _**optional**_ - Whether to cache this response. By default, leaving this field empty, responses will be cached based on their cache header information. - Setting this to true or false will override this default cache behaviour, setting in the cache or not setting in the cache, even if the default behaviour would have been otherwise. - Setting to 'uncacheable' the response will not only not be cached, but the cache will record that the originating request led to an uncacheable response, so that future cache lookups will result in immediately going to the backend, rather than attempting to coordinate concurrent requests to reduce backend traffic. - See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) for more details on the mechanism that `uncacheable` disables. - `bodyTransformFn` _: Function_ _**optional**_ - `(body: Uint8Array) => Uint8Array | PromiseLike` - Provide a function to be used for transforming the response body prior to caching. - Body transformations are performed by specifying a transform, rather than by directly working with the body during the onAfterSend callback function, because not every response contains a fresh body: 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because they do not retransmit the body. - For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will be applied to it. The original backend body is passed in to the transform function, and the function is expected to return the new body. - See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) in the Fastly cache interfaces documentation for details. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/compute/purgeSurrogateKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # purgeSurrogateKey The **`purgeSurrogateKey()`** function is used to purge the given surrogate key string from Fastly's cache. There are two purge modes: soft purge and hard purge, with hard purge as the default which clears all items from the cache immediately. When using a soft purge, stale entries are maintained in the cache, reducing orgin load, while also enabling stale revalidations. See the [Fastly Purge Documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) for more information on caching and purge operations. ## Syntax ```js purgeSurrogateKey(surrogateKey, soft?) ``` ### Parameters - `surrogateKey` _: string_ - The surrogate key string - `soft?` _: boolean_ - Enables a soft purge, retaining stale entries in the cache. Default is a hard purge. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/compute/vCpuTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # vCpuTime The **`vCpuTime()`** function provides the vCPU time used by the current request handler in milliseconds. ## Syntax ```js vCpuTime() ``` ### Parameters None. ### Return value `number`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Defines a config store instance using the resource link name. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have a resource link named "animals" (which is linked to a config store) and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.lookup() Look up the data associated with a particular User-Agent string. ## Syntax ```js lookup(userAgent) ``` ### Return value If there is data associated with the User-Agent, a `Device` instance is returned. Otherwise, `null` is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/brand.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.brand The read-only **`brand`** property of the `Device` interface is either a string stating the brand of the device, which can be different from the manufacturer of that device. If no brand is known, the value will be `null`. ## Value Either a string value if a brand is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/hardwareType.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.hardwareType The read-only **`hardwareType`** property of the `Device` interface is either a string stating the hardware type of the device, or `null` if the hardware type is not known. A string representation of the device's primary platform hardware. The most commonly used device types are also identified via boolean variables. Because a device may have multiple device types and this variable only has the primary type, we recommend using the boolean variables for logic and using this string representation for logging. ## Value Either a string value if a hardware type is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/isBot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isBot The read-only **`isBot`** property of the `Device` interface is either a boolean stating if the device is a bot, or `null` if the this is not known. ## Value Either a boolean stating if the device is a bot, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/isDesktop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isDesktop The read-only **`isDesktop`** property of the `Device` interface is either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ## Value Either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/isGameConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isGameConsole The read-only **`isGameConsole`** property of the `Device` interface is either a boolean stating if the device is a video game console, or `null` if the this is not known. ## Value Either a boolean stating if the device is a video game console, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/isMediaPlayer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMediaPlayer The read-only **`isMediaPlayer`** property of the `Device` interface is either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ## Value Either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/isMobile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMobile The read-only **`isMobile`** property of the `Device` interface is either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ## Value Either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/isSmartTV.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isSmartTV The read-only **`isSmartTV`** property of the `Device` interface is either a boolean stating if the device is a smart TV, or `null` if the this is not known. ## Value Either a boolean stating if the device is a smart TV, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/isTablet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTablet The read-only **`isTablet`** property of the `Device` interface is either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ## Value Either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/isTouchscreen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTouchscreen The read-only **`isTouchscreen`** property of the `Device` interface is either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ## Value Either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/model.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.model The read-only **`model`** property of the `Device` interface is either a string stating the model of the device, or `null` if the model is not known. ## Value Either a string value if a model is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.name The read-only **`name`** property of the `Device` interface is either a string stating the name of the device, or `null` if the name is not known. ## Value Either a string value if a name is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/device/Device/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toJSON The `toJSON()` method of the Device interface is a serializer; it returns a JSON representation of the Device object. To get a JSON string, you can use `JSON.stringify(device)` directly; it will call `toJSON()` automatically. ## Syntax ```js toJSON() ``` ### Return value A JSON object that is the serialization of the Device object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Dictionary()` :::info This Class is deprecated ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/edge-rate-limiter/EdgeRateLimiter/EdgeRateLimiter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `EdgeRateLimiter()` The **`EdgeRateLimiter` constructor** lets you open an epen a [ERL](https://docs.fastly.com/products/edge-rate-limiting) with the given ratecounter and penaltybox. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new EdgeRateLimiter(rateCounter, penaltyBox) ``` > **Note:** `EdgeRateLimiter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `rateCounter` _: RateCounter_ - The RateCounter instance to associate with this EdgeRateLimiter instance - `penaltyBox` _: PenaltyBox_ - The PenaltyBox instance which should be associated with this EdgeRateLimiter instance ### Return value A new `EdgeRateLimiter` object. ### Exceptions - `TypeError` - Thrown if the provided rateCounter value is not an instance of RateCounter - Thrown if the provided penaltyBox value is not an instance of PenaltyBox ================================================ FILE: documentation/versioned_docs/version-3.41.0/edge-rate-limiter/EdgeRateLimiter/prototype/checkRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EdgeRateLimiter.prototype.checkRate Increment an entry in the rate counter and check if the entry has exceeded some average number of requests per second (RPS) over the given window. If the entry is over the RPS limit for the window, add to the penaltybox for the given `timeToLive`. Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ## Syntax ```js checkRate(entry, delta, window, limit, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to increment and check - `delta` _: number_ - The amount to increment the `entry` by - `window` _: number_ - The time period to check across, has to be either 1 second, 10 seconds, or 60 seconds - `limit` _: number_ - The requests-per-second limit - `timeToLive` _: number_ - In minutes, how long the entry should be added into the penalty-box - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `true` if the entry has exceeded the average RPS for the window, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive finite number. - Thrown if the provided `window` value is not either, 1, 10, or 60. - Thrown if the provided `limit` value is not a positive finite number. - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.41.0/edge-rate-limiter/PenaltyBox/PenaltyBox.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `PenaltyBox()` The **`PenaltyBox` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for adding and checking if some entry is in the dataset. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new PenaltyBox(name) ``` > **Note:** `PenaltyBox()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a PenaltyBox with the given name ### Return value A new `PenaltyBox` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.41.0/edge-rate-limiter/PenaltyBox/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.add Add an `entry` into the PenaltyBox for the duration of the given `timeToLive`. ## Syntax ```js add(entry, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `timeToLive` _: number_ - In minutes, how long the entry should be added into the PenaltyBox - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.41.0/edge-rate-limiter/PenaltyBox/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.has Check if the given entry is contained in in the PenaltyBox instance. ## Syntax ```js has(entry) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up ### Return value Returns `true` if the entry is contained in the PenaltyBox instance, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.41.0/edge-rate-limiter/RateCounter/RateCounter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `RateCounter()` The **`RateCounter` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for counting and rate calculations. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new RateCounter(name) ``` > **Note:** `RateCounter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a RateCounter with the given name ### Return value A new `RateCounter` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.41.0/edge-rate-limiter/RateCounter/prototype/increment.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.increment Increment the given `entry` in the RateCounter instance with the given `delta` value. ## Syntax ```js increment(entry, delta) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `delta` _: number_ - The amount to increment the entry by ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive, finite number. ================================================ FILE: documentation/versioned_docs/version-3.41.0/edge-rate-limiter/RateCounter/prototype/lookupCount.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupCount Look up the current rate for the given `entry` and the given `duration`. ## Syntax ```js lookupCount(entry, duration) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `duration` _: number_ - The duration to lookup alongside the entry, has to be either, 10, 20, 30, 40, 50, or 60 seconds. ### Return value Returns a number which is the count for the given `entry` and `duration` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `duration` value is not either, 10, 20, 30, 40, 50 or 60. ================================================ FILE: documentation/versioned_docs/version-3.41.0/edge-rate-limiter/RateCounter/prototype/lookupRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupRate Look up the current rate for the given `entry` and the given `window`. ## Syntax ```js lookupRate(entry, window) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `window` _: number_ - The window to look up alongside the entry, has to be either 1 second, 10 seconds, or 60 seconds ### Return value Returns a number which is the rate for the given `entry` and `window` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `window` value is not either, 1, 10, or 60. ================================================ FILE: documentation/versioned_docs/version-3.41.0/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabledOrConfig` _: boolean_ - Whether or not to allow Dynamic Backends or - `enabledOrConfig` _: object_ - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to https://www.fastly.com/ and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/experimental/mapAndLogError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapAndLogError The **`mapAndLogError()`** function calls `mapError` on an `Error` object and sends the output to standard error. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapAndLogError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value `undefined`. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { mapAndLogError(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | mapAndLogError(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/experimental/mapError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapError The **`mapError()`** function extracts information from an `Error` object as a human-readable array of strings. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value Returns an array of `string`s. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { console.error(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | console.error(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/experimental/sdkVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sdkVersion The read-only **`sdkVersion`** property is a string whose indicates what JavaScript SDK version is being used. ## Value A string value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/experimental/setReusableSandboxOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setReusableSandboxOptions The **`setReusableSandboxOptions()`** function configures the reuse of the same underlying sandbox for multiple requests, which can improve performance by avoiding the overhead of initializing a new sandbox for each request. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js setReusableSandboxOptions(options) ``` ### Parameters - `options` _: Object_ - The configuration options for the reusable sandbox. - `maxRequests` _: number_ (default: `1`, `0` means unlimited) - The maximum number of requests that can be handled by a single sandbox before it is recycled. - `betweenRequestTimeoutMs` _: number_ (default: not specified) - The amount of time in milliseconds to wait between requests before recycling the sandbox. - `maxMemoryMiB` _: number_ (default: no limit) - The maximum amount of memory in MiB that the sandbox can use before it is recycled. - `sandboxTimeoutMs` _: number_ (default: no timeout) - The maximum amount of time in milliseconds that a sandbox can be active before it is recycled. ================================================ FILE: documentation/versioned_docs/version-3.41.0/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object`, or `null` if no geolocation data was found. The object contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Blob/Blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob() The **`Blob()`** constructor creates a `Blob` object, which represents a file-like object of immutable, raw data. ## Syntax ```js new Blob() new Blob(array) new Blob(array, options) ``` > **Note:** `Blob()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `array` _**optional**_ - : An array of values to include in the `Blob`. These can be [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx), [`Blob`](../../globals/Blob/Blob.mdx), or strings. If any of these elements is a [`Blob`](../../globals/Blob/Blob.mdx), its content (and not the object itself) is copied into the Blob being constructed. - `options` _**optional**_ - : An object containing optional attributes for the `Blob`. - `type` - : A string indicating the MIME type of the data. The default value is the empty string `""`. - `endings` - : A string indicating how to handle line endings in the data. This can be either `"transparent"` (default) to keep line endings unchanged, or `"native"` to convert line endings to the platform's native line endings (e.g., `\r\n` on Windows). ### Return value A new `Blob` object containing the specified data. ## Description `Blob` objects represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting its functionality and expanding it to support files on the user's system. To construct a `Blob` from other non-blob objects and data, use the `Blob()` constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](../../globals/Blob/prototype/slice.mdx) method. The `type` property of a `Blob` object will match the MIME type specified in the constructor's `options` parameter, defaulting to an empty string if not specified. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Blob/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.arrayBuffer() The **`arrayBuffer()`** method of the `Blob` interface returns a `Promise` that resolves with an `ArrayBuffer` containing the entire contents of the `Blob` as binary data. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A `Promise` that resolves with an `ArrayBuffer` containing the blob's data. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Blob/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.size The **`size`** read-only property of the `Blob` interface returns the size of the `Blob` in bytes. ## Value A number representing the size of the `Blob` in bytes. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Blob/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.slice() The **`slice()`** method of the `Blob` interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. ## Syntax ```js slice() slice(start) slice(start, end) slice(start, end, contentType) ``` ### Parameters - `start` _**optional**_ - : The 0-based index of the first byte to include in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is 0. - `end` _**optional**_ - : The 0-based index of the first byte that will not be included in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is `size`. - `contentType` _**optional**_ - : A string indicating the content type to assign to the new `Blob`. The default value is an empty string. ### Return value A new `Blob` object containing the specified subset of data. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Blob/prototype/stream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.stream() The **`stream()`** method of the `Blob` interface returns a `ReadableStream` that can be used to read the contents of the `Blob`. ## Syntax ```js stream() ``` ### Parameters None. ### Return value A `ReadableStream` that provides the data contained within the `Blob`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Blob/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.text() The **`text()`** method of the `Blob` interface returns a `Promise` that resolves with a string containing the contents of the blob, interpreted as UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a string containing the blob's data as a text string. The data is always interpreted as UTF-8. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Blob/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.type The **`type`** read-only property of the `Blob` interface returns the MIME type of the `Blob`. ## Value A string indicating the MIME type of the `Blob`. If the type cannot be determined, this returns an empty string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/EcKeyImportParams/EcKeyImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcKeyImportParams The **`EcKeyImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as ECDSA. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/EcdsaParams/EcdsaParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcdsaParams The **`EcdsaParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `hash` - : A string. An identifier for the digest algorithm to use. This should be one of the following: - `SHA-256`: selects the SHA-256 algorithm. - `SHA-384`: selects the SHA-384 algorithm. - `SHA-512`: selects the SHA-512 algorithm. > **Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. While these fields are always defined on Compute, they may be *null* when not available in testing environments such as Viceroy. - `FetchEvent.client.requestId` _**readonly**_ - : A UUID generated by Compute for each request. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : Either `null`, or a [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. - `FetchEvent.client.tlsJA3MD5` _**readonly**_ - : Either `null` or a string representation of the JA3 hash of the TLS ClientHello message. - `FetchEvent.client.tlsCipherOpensslName` _**readonly**_ - : Either `null` or a string representation of the cipher suite used to secure the client TLS connection. - `FetchEvent.client.tlsProtocol` _**readonly**_ - : Either `null` or a string representation of the TLS protocol version used to secure the client TLS connection. - `FetchEvent.client.tlsClientCertificate` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw client certificate in the mutual TLS handshake message. It is in PEM format. Returns an empty ArrayBuffer if this is not mTLS or available. - `FetchEvent.client.tlsClientHello` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw bytes sent by the client in the TLS ClientHello message. - `FetchEvent.client.tlsJA4` _**readonly**_ - : Either `null` or a string representation of the JA4 fingerprint of the TLS ClientHello message. - `FetchEvent.client.h2Fingerprint` _**readonly**_ - : Either `null` or a string representation of the HTTP/2 fingerprint for HTTP/2 connections. Returns `null` for HTTP/1.1 connections. - `FetchEvent.client.ohFingerprint` _**readonly**_ - : Either `null` or a string representation of the Original Header fingerprint based on the order and presence of request headers. - `FetchEvent.server` _**readonly**_ - : Information about the server receiving the request for the Fastly Compute service. - `FetchEvent.server.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the server which received the request. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.sendEarlyHints()`](./prototype/sendEarlyHints.mdx) - : Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FetchEvent/prototype/sendEarlyHints.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.sendEarlyHints() The **`sendEarlyHints()`** method allows you to send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response back to the client which made the incoming request to your application. ## Syntax ```js sendEarlyHints(headers) ``` ### Parameters - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../Headers/Headers.mdx) object or object literal of [`String`](../../String/String.mdx) key/value pairs. ### Return value Always returns `undefined`. ### Examples ```js event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'] ]); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/FormData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData() The **`FormData()`** constructor creates a new `FormData` object. ## Syntax ```js new FormData() new FormData(form) ``` > **Note:** `FormData()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `form` _**optional**_ - : An HTML `` element — when specified, the `FormData` object will be populated with the form's current key/value pairs using the name property of each element for the keys and their submitted value for the values. File input elements are handled specially: their values are taken from the files selected by the user in the upload control. ### Return value A new `FormData` object, pre-populated with form data if the optional `form` parameter was provided. ## Description The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using methods such as `fetch()`. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also append additional data to the `FormData` object after it's created using its various methods. A `FormData` object can be used in a number of ways with other APIs: 1. It can be sent with the `fetch()` API 2. It works seamlessly with the `Request` and `Response` objects - it can be used directly as the body of a `Request` object 3. It can be obtained from a `Response` object using the `formData()` method 4. It can be passed directly to the `URLSearchParams` constructor The transmitted data is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to `"multipart/form-data"`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.append() The **`append()`** method of the `FormData` interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. ## Syntax ```js append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.delete() The **`delete()`** method of the `FormData` interface removes all key/value pairs with the given name from the `FormData` object. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.entries() The **`entries()`** method of the `FormData` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator yields a new array for each key/value pair, with the first element being the key and the second element being the value. ## Syntax ```js entries() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.forEach() The **`forEach()`** method of the `FormData` interface executes the provided callback function once for each key/value pair in the `FormData` object. ## Syntax ```js forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each entry in the object. The function will be passed the following arguments: - `value` - : The value of the current entry. - `key` - : The key of the current entry. - `formData` - : The `FormData` object being traversed. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.get() The **`get()`** method of the `FormData` interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the [`getAll()`](../../../globals/FormData/prototype/getAll.mdx) method instead. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value A `FormDataEntryValue` containing the value. If the key does not exist, it returns `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/prototype/getAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.getAll() The **`getAll()`** method of the `FormData` interface returns all the values associated with a given key from within a `FormData` object. ## Syntax ```js getAll(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value An array of `FormDataEntryValue` items containing all values with the given key. If the key doesn't exist, an empty array is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.has() The **`has()`** method of the `FormData` interface returns a boolean indicating whether a `FormData` object contains a key/value pair with the given name. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the key you want to test for existence. ### Return value `true` if a key/value pair with the specified name exists; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.keys() The **`keys()`** method of the `FormData` interface returns an iterator allowing iteration through all keys contained in this object. The iterator yields the key for each value. ## Syntax ```js keys() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.set() The **`set()`** method of the `FormData` interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and [`append()`](../../../globals/FormData/prototype/append.mdx) is that if the specified key already exists, `set()` overwrites all existing values with the new one, whereas `append()` appends the new value onto the end of the existing values. ## Syntax ```js set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/FormData/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.values() The **`values()`** method of the `FormData` interface returns an iterator allowing iteration through all values contained in this object. The iterator yields the value for each key/value pair. ## Syntax ```js values() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name is not the name of an HTTP header, this method throws a `TypeError`. The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/prototype/getSetCookie.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.getSetCookie() The **`getSetCookie()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns an array of all the values of the `Set-Cookie` headers, returning an empty list if none are present. ## Syntax ```js getSetCookie() ``` ### Return value `String[]` representing the list of `Set-Cookie` headers. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2 or greater than π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex where x is a number very close to 0, you should get an answer very close to 1 + x, because limx0ex1x=1. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, a `ReadableStream` object, a [`Blob`](../../globals/Blob/Blob.mdx) object, or a [`FormData`](../../globals/FormData/FormData.mdx) object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_, see [`CacheOverride`](../../fastly:cache-override/CacheOverride/CacheOverride.mdx). - `cacheKey` _**Fastly-specific**_ - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.blob() The **`blob()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/clone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.clone() The **`clone()`** method of the `Request` interface creates a copy of the current `Request` object. Like the underlying `ReadableStream.tee`` api, the `body` of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Beware when you construct a `Request` from a stream and then `clone` it. `clone()` throws a `TypeError` if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) If you intend to modify the request, you may prefer the `Request` constructor. ## Syntax ```js clone() ``` ### Parameters None. ### Return value A `Request` object, which is an exact copy of the `Request` that `clone()` was called on. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.formData() The **`formData()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. - `SyntaxError` - : Thrown if the request's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Request` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Request instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - [`Blob`](../../globals/Blob/Blob.mdx) - [`FormData`](../../globals/FormData/FormData.mdx) - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.blob() The **`blob()`** method of the [`Response`](../Response.mdx) interface takes a [`Response`](../Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.formData() The **`formData()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. - `SyntaxError` - : Thrown if the response's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/ip.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ip The **`ip`** getter of the `Response` interface returns the IP address associated with the request, as either an IPv6 or IPv4 string. In the case where no IP address is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with an IP, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `string`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.port The **`port`** getter of the `Response` interface returns the port associated with the request, as a number. In the case where no port is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with a port, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `number`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Response` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Response instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - For ECDSA: Pass an [`EcKeyImportParams`](../../EcKeyImportParams/EcKeyImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](https://en.wikipedia.org/wiki/HZ_(character_encoding)). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Explicit Backends Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service. This `backend` option is then a special Fastly-specific fetch option that is provided to the `fetch()` call: ```js fetch('https://origin.com/path', { backend: 'origin' }); ``` Backends are configured using the Fastly service backend configuration, see the [Backend documentation](https://developer.fastly.com/reference/api/services/backend/) for more information. ## Dynamic Backends Dynamic backends are a compute feature that allow services to define backends for themselves. If the `backend` option is not provided when making `fetch()` requests, a backend will be automatically created by extracting the protocol, host, and port from the provided URL. In addition, custom backend configuration options can then also be provided through the [`Backend()`](../fastly:backend/Backend/Backend.mdx) constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ - `imageOptimizerOptions` _**Fastly-specific**_, see [`imageOptimizerOptions`](../fastly:image-optimizer/imageOptimizerOptions.mdx). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-3.41.0/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/after.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # after The `after` method inserts content after the closing tag of the element. ## Syntax ```js element.after(content); element.after(content, options); ``` ### Parameters - `content` _: string_ - The content to insert after the element's closing tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.after("World"); // Result:
Hello
World ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # append The `append` method inserts content at the end of the element's content. ## Syntax ```js element.append(content); element.append(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the end of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.append(", World"); // Result:
Hello, World
``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/before.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # before The `before` method inserts content before the opening tag of the element. ## Syntax ```js element.before(content); element.before(content, options); ``` ### Parameters - `content` _: string_ - The content to insert before the element's opening tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.before("Well"); // Result: Well
Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/hasAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # hasAttribute The `hasAttribute` method returns a `boolean` value indicating whether the specified attribute is present on the element. ## Syntax ```js element.hasAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to check for. ### Return value A boolean value indicating whether the attribute is present. ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/prepend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # prepend The `prepend` method inserts content at the beginning of the element's content. ## Syntax ```js element.prepend(content); element.prepend(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the beginning of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.prepend("Well, "); // Result:
Well, Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/removeAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # removeAttribute The `removeAttribute` method removes the specified attribute from the element. ## Syntax ```js element.removeAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to remove. ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/replaceChildren.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceChildren The `replaceChildren` method replaces the element's children with new content. ## Syntax ```js element.replaceChildren(content); element.replaceChildren(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element's children with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceChildren("Greetings!"); // Result:
Greetings!
``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/replaceWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceWith The `replaceWith` method replaces the element with new content. ## Syntax ```js element.replaceWith(content); element.replaceWith(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceWith("

Greetings!

"); // Result:

Greetings!

``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/selector.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # selector The `selector` read-only property is a `string` representing the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) that matches the element. ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/setAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setAttribute The `setAttribute` method sets the value of the specified attribute on the element. If the value already exists, it will be updated; otherwise, a new attribute with the specified name and value will be added to the element. ## Syntax ```js element.setAttribute(attributeName, value); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to set. - `value` _: string_ - The value to assign to the attribute. ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/Element/prototype/tag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # tag The `tag` read-only property is a `string` representing the tag name of the element. ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/HTMLRewritingStream/HTMLRewritingStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `HTMLRewritingStream()` The **`HTMLRewritingStream`** lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback. This callback can manipulate the attributes of the element, and add or remove content from the immediate context. ## Syntax ```js new HTMLRewritingStream() ``` ### Return value A new `HTMLRewritingStream` object. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/html-rewriter/HTMLRewritingStream/prototype/onElement.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # onElement ▸ **onElement**`(selector: string, handler: (element: Element) => void): this` Registers an element handler with the [`HTMLRewritingStream`] that will be called for each [`Element`] that matches the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) `selector`. Elements added by handlers will not be processed by other handlers. ## Syntax ```js .onElement(selector, handler) ``` ### Parameters - `selector` _: string_ - A CSS selector that determines the elements for which `handler` will be called - The following types of CSS selector are supported: Currently the rewriter supports the following CSS selectors: | Pattern | Description | |----------------------|----------------------------------------------------------------------------| | `*` | Any element | | `E` | All elements of type `E` | | `E F` | `F` elements inside `E` elements | | `E > F` | `F` elements directly inside `E` elements | | `E:nth-child(n)` | The n-th child of type `E` | | `E:first-child` | First child of type `E` | | `E:nth-of-type(n)` | The n-th sibling of type `E` | | `E:first-of-type` | First sibling of type `E` | | `E:not(s)` | Type `E` elements not matching selector `s` | | `E.myclass` | Type `E` elements with class `"myclass"` | | `E#myid` | Type `E` elements with ID `"myid"` | | `E[attr]` | Type `E` elements with attribute `attr` | | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | | `E[attr="val" i]` | Type `E` elements where `attr` is `"val"`, case-insensitive | | `E[attr="val" s]` | Type `E` elements where `attr` is `"val"`, case-sensitive | | `E[attr~="val"]` | Type `E` elements where `attr` contains `"val"` in a space-separated list | | `E[attr`|`;="val"]`| Type `E` elements where `attr` is hyphen-separated and starts with `"val"` | | `E[attr^="val"]` | Type `E` elements where `attr` starts with `"val"` | | `E[attr$="val"]` | Type `E` elements where `attr` ends with `"val"` | | `E[attr*="val"]` | Type `E` elements where `attr` contains `"val"` | - `handler` _: (element: Element) => void_ - A callback function that will be called once for each element that matches `selector` ### Return value The `HTMLRewritingStream`, so multiple calls to `onElement` can be chained. ### Exceptions - `Error` - If the provided `selector` is not a valid CSS selector. - If the provided `handler` is not a function. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/Auto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Auto` Enumerator options for [`imageOptimizerOptions.auto`](./imageOptimizerOptions.mdx). ## Constants - `AVIF` (`"avif"`) If the browser's Accept header indicates compatibility, deliver an AVIF image. - `WEBP` (`"webp"`) If the browser's Accept header indicates compatibility, deliver a WebP image. ## Examples ```js import { Auto, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, auto: Auto.AVIF }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/BWAlgorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `BWAlgorithm` Enumerator options for [`imageOptimizerOptions.bw`](./imageOptimizerOptions.mdx). ## Constants - `Threshold` (`"threshold"`) Uses a luminance threshold to convert the image to black and white. - `Atkinson` (`"atkinson"`) Uses [Atkinson dithering](https://en.wikipedia.org/wiki/Atkinson_dithering) to convert the image to black and white. ## Examples ```js import { Region, BWAlgorithm } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, bw: BWAlgorithm.Threshold }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/CropMode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CropMode` Enumerator options for [`imageOptimizerOptions.crop.mode`](./imageOptimizerOptions.mdx) and `imageOptimizerOptions.precrop.mode`. ## Constants - `Smart` (`"smart"`) Enables content-aware algorithms to attempt to crop the image to the desired aspect ratio while intelligently focusing on the most important visual content, including the detection of faces. - `Safe` (`"safe"`) Allow cropping out-of-bounds regions. ## Examples ```js import { CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Smart, } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/Disable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Disable` Enumerator options for [`imageOptimizerOptions.disable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Prevent images being resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Disable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, disable: Disable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/Enable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Enable` Enumerator options for [`imageOptimizerOptions.enable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Allow images to be resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Enable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, enable: Enable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/Fit.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Fit` Enumerator options for [`imageOptimizerOptions.fit`](./imageOptimizerOptions.mdx). ## Constants - `Bounds` (`"bounds"`) Resize the image to fit entirely within the specified region, making one dimension smaller if needed. - `Cover` (`"cover"`) Resize the image to entirely cover the specified region, making one dimension larger if needed. - `Crop` (`"crop"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Fit, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 150, height; 150, fit: Fit.Bounds }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/Format.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Format` Enumerator options for [`imageOptimizerOptions.format`](./imageOptimizerOptions.mdx). ## Constants - `Auto` (`"auto"`) Automatically use the best format based on browser support and image/transform characteristics - `AVIF` (`"avif"`) AVIF - `BJPG` (`"bjpg"`) Baseline JPEG - `GIF` (`"gif"`) Graphics Interchange Format - `JPG` (`"jpg"`) JPEG - `JXL` (`"jxl"`) JPEGXL - `MP4` (`"mp4"`) MP4 (H.264) - `PJPG` (`"pjpg"`) Progressive JPEG - `PJXL` (`"pjxl"`) Progressive JPEGXL - `PNG` (`"png"`) Portable Network Graphics - `PNG8` (`"png8"`) Portable Network Graphics palette image with 256 colors and 8-bit transparency - `SVG` (`"svg"`) Scalable Vector Graphics - `WEBP` (`"webp"`) WebP - `WEBPLL` (`"webpll"`) WebP (Lossless) - `WEBPLY` (`"webply"`) WebP (Lossy) ## Examples ```js import { Format, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/Metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Metadata` Enumerator options for [`imageOptimizerOptions.metadata`](./imageOptimizerOptions.mdx). ## Constants - `Copyright` (`"copyright"`) Preserve [copyright notice](https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#copyright-notice), creator, credit line, licensor, and web statement of rights fields. - `C2PA` (`"c2pa"`) Preserve the [C2PA manifest](https://c2pa.org/) and add any transformations performed by Fastly Image Optimizer. - `CopyRightAndC2PA` (`"copyright,c2pa"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Metadata, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, metadata: Metadata.Copyright }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/Optimize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Optimize` Enumerator options for [`imageOptimizerOptions.optimize`](./imageOptimizerOptions.mdx). ## Constants - `Low` (`"low"`) Output image quality will be similar to the input image quality. - `Medium` (`"medium"`) More optimization is allowed. We attempt to preserve the visual quality of the input image. - `High` (`"high"`) Minor visual artifacts may be visible. This produces the smallest file. ## Examples ```js import { Optimize, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, optimize: Optimize.High }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/Orient.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Orient` Enumerator options for [`imageOptimizerOptions.orient`](./imageOptimizerOptions.mdx). ## Constants - `Default` (`"1"`) - `FlipHorizontal` (`"2"`) - `FlipHorizontalAndVertical` (`"3"`) - `FlipVertical` (`"4"`) - `FlipHorizontalOrientLeft` (`"5"`) - `OrientRight` (`"6"`) - `FlipHorizontalOrientRight` (`"7"`) - `OrientLeft` (`"8"`) ## Examples ```js import { Orient, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, orient: Orient.FlipHorizontal }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/Profile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Profile` Enumerator options for [`imageOptimizerOptions.profile`](./imageOptimizerOptions.mdx). ## Constants - `Baseline` (`"baseline"`) The profile recommended for video conferencing and mobile applications. (Default) - `Main` (`"main"`) The profile recommended for standard-definition broadcasts. - `High` (`"high"`) The profile recommended for high-definition broadcasts. ## Examples ```js import { Profile, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, profile: Profile.Main }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/Region.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Region` Enumerator options for [`imageOptimizerOptions.region`](./imageOptimizerOptions.mdx). ## Constants - `UsEast` (`"us_east"`) - `UsCentral` (`"us_central"`) - `UsWest` (`"us_west"`) - `EuCentral` (`"eu_central"`) - `EuWest` (`"eu_west"`) - `Asia` (`"asia"`) - `Australia` (`"australia"`) ## Examples ```js import { Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/ResizeFilter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ResizeFilter` Enumerator options for [`imageOptimizerOptions.resizeFilter`](./imageOptimizerOptions.mdx). ## Constants - `Nearest` (`"nearest"`) Uses the value of nearby translated pixel values. - `Bilinear` (`"bilinear"`) Uses an average of a 2x2 environment of pixels. - `Linear` (`"linear"`) Same as `Bilenear`. - `Bicubic` (`"bicubic"`) Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. - `Cubic` (`"cubic"`) Same as `Bicubic`. - `Lanczos2` (`"lanczos2"`) Uses the Lanczos filter to increase the ability to detect edges and linear features within an image and uses sinc resampling to provide the best possible reconstruction. - `Lanczos3` (`"lanczos3"`) Lanczos3 uses a better approximation of the sinc resampling function. (Default) - `Lanczos` (`"lanczos"`) Same as `Lanczos3`. ## Examples ```js import { ResizeFilter, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, resizeFilter: ResizeFilter.Linear }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/image-optimizer/imageOptimizerOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `imageOptimizerOptions` Options specified in the [`Request`](../globals/Request/Request.mdx) constructor for running the [Fastly Image Optimizer](https://docs.fastly.com/products/image-optimizer). More detailed documentation on all Image Optimizer options is available in the [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/). ## Parameters All parameters other than `region` are optional. - `region`: _[`Region`](./Region.mdx)_ Where image optimizations should occur. - `auto`: _[`Auto`](./Auto.mdx)_ Enable optimization features automatically. - `bgColor`: _[`Color`](#color)_ Set the background color of an image. - `blur`: _`number` (0.5-1000) or [`Percentage`](#percentage)_ Set the blurriness of the output image. - `brightness`: _`number` (-100-100)_ Set the brightness of the output image. - `bw`: _[`BWAlgorithm`](./BWAlgorithm.mdx)_ Convert an image to black and white. - `canvas`: _`Object`_ Increase the size of the canvas around an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `contrast`: _`number` (-100-100)_ Set the contrast of the output image. - `crop`: _`Object`_ Remove pixels from an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `mode` (optional): _[`CropMode`](./CropMode.mdx)_ - `disable`: _[`Disable`](./Disable.mdx)_ Disable functionality that is enabled by default. - `dpr`: `number` Ratio between physical pixels and logical pixels. - `enable`: _[`Enable`](./Enable.mdx)_ Enable functionality that is disabled by default. - `fit`: _[`Fit`](./Fit.mdx)_ Set how the image will fit within the size bounds provided. - `format`: _[`Format`](./Format.mdx)_ Specify the output format to convert the image to. - `frame`: _`number` (must have the value 1)_ Extract the first frame from an animated image sequence. - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the height of the image. - `level`: _`String` containing one of the [allowed values](https://www.fastly.com/documentation/reference/io/level/#allowed-values)_ Specify the level constraints when converting to video. - `metadata`: _[`Metadata`](./Metadata.mdx)_ Control which metadata fields are preserved during transformation. - `optimize`: _[`Optimize`](./Optimize.mdx)_ Automatically apply optimal quality compression. - `orient`: _[`Orient`](./Orient.mdx)_ Change the cardinal orientation of the image. - `pad`: _[`Sides`](#sides)_ Add pixels to the edge of an image. - `precrop`: _`Object`_ Remove pixels from an image before any other transformations occur. - `size`: _[`Size`](#size)_ - `position`: _[`Position`](#position)_ - `mode`: _[`CropMode`](./CropMode.mdx)_ - `profile`: _[`Profile`](./Profile.mdx)_ Specify the profile class of application when converting to video. - `quality`: _`integer` (1-100)_ Optimize the image to the given compression level for lossy file formatted images. - `resizeFilter`: _[`ResizeFilter`](./ResizeFilter.mdx)_ Specify the resize filter used when resizing images. - `saturation`: _`number` (-100-100)_ Set the saturation of the output image. - `sharpen`: _`Object`_ Set the sharpness of the output image. - `amount`: _`number` (0-10)_ - `radius`: _`number` (0.5-1000)_ - `threshold`: _`integer` (0-255)_ - `trim`: _[`Sides`](#sides)_ Remove pixels from the edge of an image. - `viewbox`: _`number` (must have the value 1)_ Remove explicit width and height properties in SVG output. - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the width of the image. ## Types ### Color Either: - a 3 or 6 character hexadecimal string - an `Object` containing: - `r`: _`integer` (0-255)_ Red component - `g`: _`integer` (0-255)_ Green component - `b`: _`integer` (0-255)_ Blue component - `a` (optional): _`number` (0.0-1.0)_ Alpha component ### Percentage A `String` containing a number suffixed with a percent sign (%). ### Position An `Object` containing: - Exactly one of: - `x`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetX`: _`number` (interpreted as a percentage)_ - Exactly one of: - `y`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetY`: _`number` (interpreted as a percentage)_ ### Sides An `Object` containing `top`, `bottom`, `left`, and `right`, all of which are either an `integer` or [`Percentage`](#percentage). ### Size An `Object` containing either: - `absolute`: _`Object`_ - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `ratio`: _`Object`_ - `width`: _`number`_ - `height`: _`number`_ ## Examples ```js import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG, bgColor: { 'r': 100, 'g': 255, 'b': 9, 'a': 0.5 }, blur: '1%', brightness: -20, contrast: -20, height: 600, level: '4.0', orient: Orient.FlipVertical, saturation: 80, sharpen: { 'amount': 5, 'radius': 6, 'threshold': 44 }, canvas: { 'size': { 'absolute': { 'width': 400, 'height': 400 } } }, crop: { size: { absolute: { width: 200, height: 200 }, mode: CropMode.Safe } }, trim: { top: 10, left: 10, right: 10, bottom: 10 }, pad: { top: 30, left: 30, right: "1%", bottom: 30 } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a KV store instance using the resource link name. ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStore/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.delete Deletes the value associated with the key `key` in the KV store. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value Returns `undefined` ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - Does not exist ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then delete the entry. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') await files.delete('hello') const entry = await files.get('hello') if (entry) { return new Response(await entry.text()) } else { return new Response('no file named hello exists') } } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStore/prototype/list.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.list The **`list()`** can be used to list the keys of a store. ## Syntax ```js list(options?) ``` ### Parameters - `options` _: object_ _**optional**_ - List options supporting properties: - `cursor` _: string_ _**optional**_ - The cursor used to pick up from a previous iteration. - `limit` _: number_ _**optional**_ - The maximum number of keys to return. - `prefix` _: string_ _**optional**_ - List only those keys that start with the given string prefix. - `noSync` _: boolean_ _**optional**_ - Do not sync the key list first, instead provide a possibly out-of-date listing. May be faster but inconsistent. ### Return value Returns a `Promise` which resolves with `{ list: string[], cursor: string | undefined }`. ## Example In this example we list the keys of a KV Store named `'files'`, iterating 10 at a time, counting the total; ```js /// import { KVStore } from 'fastly:kv-store'; async function app(event) { const files = new KVStore('files'); let cursor, list, total = 0; do { ({ cursor, list } = await files.list({ limit: 10, cursor })); total += list?.length; } while (list); return new Response(`Iterated ${total} entries`); } addEventListener('fetch', (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value, options?) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. - `options` _: object_ _**optional**_ - An insert options parameter, supporting: - `metadata` _: ArrayBuffer | TypedArray | DataView_ _**optional**_ - Binary metadata associated with the entry, may be up to 1000 bytes. - `ttl` _: number_ _**optional**_ - TTL for the entry - `mode` _: 'overwrite' | 'add' | 'append' | 'prepend'_ _**optional**_ - Insert mode, defaults to 'overwrite' - `gen` _: number_ _**optional**_ - 'generation' header specific to the version of an entry key ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - `TypeError` - If the provided `gen`: - Is not an number ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStoreEntry/prototype/metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadata() The `metadata()` method of the `KVStoreEntry` interface provides the binary metadata associated with the `KVStoreEntry`. The metadata binary may be up to 1000 bytes, and is returned as a `Uint8Array` TypedArray buffer, if metadata is set, or null otherwise. ## Syntax ```js metadata() ``` ### Parameters None. ### Return value A `Promise` that resolves to a `Uint8Array` buffer object. ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStoreEntry/prototype/metadataText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadataText() The `metadataText()` method of the `KVStoreEntry` interface provides a String interpretation of binary metadata associated with the `KVStoreEntry`. If the binary data is not a valid string, an encoding error will be thrown. ## Syntax ```js metadataText() ``` ### Parameters None. ### Return value A `Promise` that resolves to a String. ================================================ FILE: documentation/versioned_docs/version-3.41.0/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; const logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; let logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/logger/configureConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # configureConsole The **`configureConsole()`** function allows configuring the behaviour of the `console` global JS logger. ## Syntax ```js configureConsole(loggingOptions) ``` ### Parameters - `loggingOptions` _: object_ - - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ## Examples In this example, we disable prefixing for `console.log` and use `stderr` output for `console.error`: ```js import { configureConsole } from "fastly:logger"; configureConsole({ prefixing: false, stderr: true }); async function handleRequest(event) { console.log(JSON.stringify(event.request.headers)); const url = new URL(event.request.url); try { validate(url); } catch (e) { console.error(`Validation error: ${e}`); return new Response('Bad Request', { status: 400 }); } return new Response('OK'); } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v2 to v3` ## SimpleCache.delete renamed to SimpleCache.purge and requires purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using `SimpleCache.delete` to `SimpleCache.purge` with the same purging behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a Secret Store instance using the resource link name. ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/secret-store/SecretStore/fromBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fromBytes The **`fromBytes()`** function is used to create an in-memory secret from an array buffer. >**Note**: This API should be avoided when possible, by instead using [SecretStore.prototype.get](./prototype/get.mdx) to obtain secure secrets. ## Syntax ```js fromBytes(new Uint8Array([1, 2, 3])) ``` ### Parameters None. ### Return value Returns a `SecretStoreEntry`. ================================================ FILE: documentation/versioned_docs/version-3.41.0/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/secret-store/SecretStoreEntry/prototype/rawBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.rawBytes ▸ **rawBytes**(): `Uint8Array` Returns the raw byte contents of the SecretStoreEntry instance as a Uint8Array. ## Syntax ```js rawBytes() ``` ### Parameters None. ### Return value A Uint8Array ### Exceptions The `rawBytes()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ================================================ FILE: documentation/versioned_docs/version-3.41.0/security/inspect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # inspect The **`inspect()`** function inspects a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). ## Syntax ```js inspect(request, config); ``` ### Parameters - `request` _: Request_ - The Request to get a WAF determination for. - `config` _: object_ - `corp` _: string_ - Set a corp name for the configuration. - This parameter is currently required. - `workspace` _: string_ - Set a workspace name for the configuration. - This parameter is currently required. - `overrideClientIp` _: string_ - Specify an explicit client IP address to inspect. - By default, `inspect` will use the IP address that made the request to the running Compute service, but you may want to use a different IP when service chaining or if requests are proxied from outside of Fastly’s network. ### Return value Returns an `Object` with the `inspect` response, with the following fields: - `waf_response` _: number_ - Security status code. - `redirect_url` _: string | null_ - A redirect URL returned from Security. - `tags` _: string[]_ - Tags returned by Security. - `verdict` _: string_ - The outcome of inspecting a request with Security. It can be one of the following: - `"allow"` - Security indicated that this request is allowed. - `"block"` - Security indicated that this request should be blocked. - `"unauthorized"` - Security indicated that this service is not authorized to inspect a request. - Other verdicts may be returned but not currently documented. - `decision_ms` _: number_ - How long Security spent determining its verdict, in milliseconds. ## Examples ```js /// import { inspect } from "fastly:security"; async function app(event) { const res = inspect(event.request, { corp: "mycorp", workspace: "myws" }); switch (res.verdict) { case "allow": return await fetch(event.request); case "block": return new Response("Request Blocked", { status: 400 }); case "unauthorized": return new Response("Unauthorized", { status: 401 }); default: return new Response("idk", { status: 500 }); } } addEventListener("fetch", (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/shielding/Shield/Shield.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Shield()` Load information about the given shield. Returns an object representing the shield if it is active, or throws an exception if the string is malformed or the shield doesn’t exist. Shield names are defined on [this webpage](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations), in the “shield code” column. For example, the string “pdx-or-us” will look up our Portland, OR, USA shield site, while “paris-fr” will look up our Paris site. If you are using a major cloud provider for your primary origin site, consider looking at the “Recommended for” column, to find the Fastly POP most closely located to the given cloud provider. ## Syntax ```js new Shield(name) ``` > **Note:** `Shield()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Exceptions - `TypeError` - Thrown if no Shield exists with the provided name ## Examples In this example, we create a Shield instance for the Sydney, Australia shield POP. If the code is running on that shield POP, it fetches directly from origin. Otherwise, it routes the request through the shield using an encrypted connection. ```js /// import { Shield } from "fastly:shielding"; async function app(event) { const shield = new Shield('wsi-australia-au'); // If running on the shield POP, fetch from the origin directly if (shield.runningOn()) { return await fetch('https://http-me.fastly.com/anything', { backend: 'httpme' }); } // Otherwise, route the request through the shield using an encrypted connection return await fetch(event.request, { backend: shield.encryptedBackend() }); } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.0/shielding/Shield/prototype/encryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.encryptedBackend ▸ **encryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an encrypted connection to the POP. For reference, this is almost always the backend that you want to use. Only use [`Shield::unencryptedBackend`](./unencryptedBackend.mdx) in situations in which you are 100% sure that all the data you will send and receive over the backend is already encrypted. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.41.0/shielding/Shield/prototype/runningOn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.runningOn ▸ **runningOn**(): `boolean` Returns whether we are currently operating on the given shield. Technically, this may also return true in very isolated incidents in which Fastly is routing traffic from the target shield POP to the POP that this code is running on, but in these situations the results should be approximately identical. (For example, it may be the case that you are asking to shield to ‘pdx-or-us’. But, for load balancing, performance, or other reasons, Fastly is temporarily shifting shielding traffic from Portland to Seattle. In that case, this function may return true for hosts running on ‘bfi-wa-us’, our Seattle site, because effectively the shield has moved to that location. This should give you a slightly faster experience than the alternative, in which this function would return false, you would try to forward your traffic to the Portland site, and then that traffic would be caught and redirected back to Seattle.) ================================================ FILE: documentation/versioned_docs/version-3.41.0/shielding/Shield/prototype/unencryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.unencryptedBackend ▸ **unencryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an unencrypted connection to the POP. Generally speaking, we encourage users to use [`Shield::encryptedBackend`](./encryptedBackend.mdx) instead of this function. Data sent over this backend – the unencrypted version – will be sent over the open internet, with no protections. In most cases, this is not what you want. However, in some cases – such as when you want to ship large data blobs that you know are already encrypted — using these backends can prevent a double-encryption performance penalty. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.41.0/websocket/createWebsocketHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createWebsocketHandoff The **`createWebsocketHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Websocket, to the declared backend. ## Syntax ```js createWebsocketHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Websocket. - `backend` _: string_ - The name of the backend that Websocket should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Websocket. ```js import { createWebsocketHandoff } from "fastly:websocket"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createWebsocketHandoff(event.request, 'websocket_backend'); } else { return new Response('oopsie, make a request to /stream for some websocket goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/acl/Acl/open.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.open() Opens the ACL with the given name, returning a new `Acl` instance with the given name on success. ## Syntax ```js Acl.open(name) ``` ### Return value An `Acl` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.2/acl/Acl/prototype/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Acl.prototype.lookup() The **`lookup(ipAddress)`** method returns the name associated with the `Acl` instance. ## Syntax ```js acl.lookup(ipAddress) ``` ### Parameters - `ipAddress` _: string_ - IPv4 or IPv6 address to lookup ### Return value An Object of the form `{ action: 'ALLOW' | 'BlOCK', prefix: string }`, where `prefix` is the IP address prefix that was matched in the ACL. ## Example ```js /// import { Acl } from 'fastly:acl'; addEventListener('fetch', async (evt) => { const myAcl = Acl.open('myacl'); const match = await myAcl.lookup(evt.client.address); evt.respondWith(new Response(match?.action === 'BLOCK' ? 'blocked' : 'allowed')); }); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/Backend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Backend()` The **`Backend` constructor** lets you dynamically create new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/) for your Fastly Compute service. >**Note**: Dynamic backends are by default disabled at the Fastly service level. Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) to request dynamic backends on Fastly Services. To disable the usage of dynamic backends, see [enforceExplicitBackends](../enforceExplicitBackends.mdx). ## Syntax ```js new Backend(backendConfiguration) ``` > **Note:** `Backend()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `backendConfiguration` - : An Object which contains all the configuration options to apply to the newly created Backend. - `name` _: string_ - The name of the backend. - The name has to be between 1 and 254 characters inclusive. - The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. - `target` _: string_ - A hostname, IPv4, or IPv6 address for the backend as well as an optional port. - The target has to be at-least 1 character. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. Is null, undefined, an empty string, not a valid IP address or host, or is the string `::` - `hostOverride` _: string_ _**optional**_ - If set, will force the HTTP Host header on connections to this backend to be the supplied value. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `sniHostname` _: string_ _**optional**_ - The SNI hostname to use on connections to this backend. - Throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. - `grpc` _: boolean_ _**optional**_ - **_Experimental feature_** - When enabled, sets that this backend is to be used for gRPC traffic. - _Warning: When using this experimental feature, no guarantees are provided for behaviours for backends that do not provide gRPC traffic._ All optional generic options can have their defaults set via [`setDefaultDynamicBackendConfig()`](../setDefaultDynamicBackendConfig.mdx). This includes all configuration options above except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. ### Return value A new `Backend` object. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Backend } from "fastly:backend"; async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com", connectTimeout: 1000, firstByteTimeout: 15000, betweenBytesTimeout: 10000, useSSL: true, tlsMinVersion: 1.3, tlsMaxVersion: 1.3, }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/exists.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.exists() The **`Backend.exists()`** method returns a boolean indicating if a Backend with the given name exists or not. ## Syntax ```js exists(name) ``` ### Return value A boolean indicating if a Backend with the given name exists or not. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/fromName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.fromName() Returns the `Backend` instance with the given name, if one exists. If one does not exist, an error is thrown. ## Syntax ```js fromName(name) ``` ### Return value A `Backend` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.health() :::info This method is deprecated, use [`Backend.prototype.health`](./prototype/health.mdx) instead. ::: The **`Backend.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js Backend.health(backend) ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/betweenBytesTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.betweenBytesTimeout The read-only **`betweenBytesTimeout`** property of a `Backend` instance is an integer number providing the between bytes timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/connectTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.connectTimeout The read-only **`connectTimeout`** property of a `Backend` instance is an integer number providing the connect timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/firstByteTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.firstByteTimeout The read-only **`firstByteTimeout`** property of a `Backend` instance is an integer number providing the first byte timeout for this backend in milliseconds. When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/health.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.health() The **`Backend.prototype.health()`** method returns a string representing the health of the given Backend instance. ## Syntax ```js health() ``` ### Return value A string representing the health of the specified Backend value. Possible values are: - `"healthy"` - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. - `"unhealthy"` - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. - `"unknown"` - The backend does not have a health check configured. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/hostOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.hostOverride The read-only **`hostOverride`** property of a `Backend` instance is the host header override string used when sending requests to this backend. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/httpKeepaliveTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.httpKeepaliveTime The read-only **`httpKeepaliveTime`** property of a `Backend` instance is the HTTP keepalive time for this backend in milliseconds, or 0 if no keepalive is set. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/isDynamic.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isDynamic The read-only **`isDynamic`** property of a `Backend` instance is a boolean indicating if the backend was dynamically created for this service. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/isSSL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.isSSL The read-only **`isSSL`** property of a `Backend` instance is a boolean indicating if the backend is using an SSL connection. ## Value A `boolean`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # name The read-only **`name`** property of the backend returns the backend name string. ## Value A `string`. ## Description Provides the name of the backend. ## Examples ### Using name The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.name); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.port The read-only **`port`** property of a `Backend` instance is the port number of this backend. ## Value A `number`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/target.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.target The read-only **`target`** property of a `Backend` instance is the host string this backend is configured to use. ## Value A `string`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/tcpKeepalive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tcpKeepalive The read-only **`tcpKeepalive`** property of a `Backend` instance returns an object providing the TCP keepalive configuration, if any, otherwise returning `null` if TCP keepalive is not enabled. This object has the following properties: - `timeSecs` _: number or null._ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number or null._ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number or null._ - Number of probes to send to the backend before it is considered dead. ## Value A `Object` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/tlsMaxVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMaxVersion The read-only **`tlsMaxVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/tlsMinVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.tlsMinVersion The read-only **`tlsMinVersion`** property of a `Backend` instance is the max TLS version it is configured to use, as a number, either `1.0`, `1.1`, `1.2`, or `1.3`. When not used, or for environments that do not support this feature, such as Viceroy, `null` may be returned. ## Value A `number` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/toName.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Backend.prototype.toName() :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toName()`** method returns the name associated with the `Backend` instance. ## Syntax ```js toName() ``` ### Return value A string which contains the name of the Backend. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/Backend/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toString :::info This method is deprecated, use [`Backend.prototype.name`](./name.mdx) instead. ::: The **`toString()`** method returns a string representing the specified Backend value. ## Syntax ```js toString() ``` ### Return value A string representing the specified Backend value. ## Description The [Backend](../Backend.mdx) object overrides the `toString()` method of [Object](../../../globals//Object/Object.mdx); it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For [Backend](../Backend.mdx) values, the `toString` method returns the name given to the [Backend](../Backend.mdx) object during construction. The `toString()` method requires its `this` value to be a [Backend](../Backend.mdx) object. If the `this` value does not inherit from `Backend.prototype`, a [TypeError](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples ### Using toString() The following example logs the string value of a [Backend](../Backend.mdx) object: import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js import { Backend } from "fastly:backend"; async function app() { const backend = new Backend({ name: "fastly", target: "fastly.com", }); console.log(backend.toString()); // "fastly" } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends :::info This method is deprecated, and dynamic backends are now always supported when enabled at the service level. See [`enforceExplicitBackends`](./enforceExplicitBackends.mdx) instead. ::: The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: By default, while dynamic backends are allowed in the SDK, they are by default disabled at the Fastly service level. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabled` _: boolean_ - Whether or not to allow Dynamic Backends ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/enforceExplicitBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enforceExplicitBackends Call this function to enforce the security property of explicitly-defined backends, even when dynamic backends are enabled at the Fastly service level. By default, if dynamic backends are supported for the Fastly service, they will be automatically used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a potential security concern since third-party JavaScript code may send arbitrary requests, including sensitive/secret data, off to destinations that the JavaScript project was not intending. When calling this function, an optional default backend name can be provided. >**Note**: This is a separate option to the service-level dynamic backend support for Fastly services, which is by deault disabled for Fastly services. The **`enforceExplicitBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are enabled, but can be a potential security concern since third-party JavaScript code may send arbitrary requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending. Using `allowDynamicBackends(false)` this security property can be restored to only use explicit backend definitions. >**Note**: Dynamic Backends are disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled or disabled on Fastly Services. ## Syntax ```js enforceExplicitBackends(defaultBackend?) ``` ### Parameters - `defaultBackend` _: string_ _**optional**_ - An optional default backend string name to use in `fetch()` requests. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/backend/setDefaultDynamicBackendConfig.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setDefaultDynamicBackendConfig() The **`setDefaultDynamicBackendConfig()`** allows setting backend configuration defaults that should apply to any newly created dynamic backends via the `new Backend()` constructor. ### Parameters - `defaultDynamicBackendConfig` - : An Object which contains the generic configuration options to apply to newly created Backends. - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `useSSL` _: boolean_ _**optional**_ - Whether or not to require TLS for connections to this backend. - `dontPool` _: boolean_ _**optional**_ - Determine whether or not connections to the same backend should be pooled across different sessions. - Fastly considers two backends “the same” if they're registered with the same name and the exact same settings. - In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. - This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). - By default, pooling is enabled for dynamic backends. - `tlsMinVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Minimum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `tlsMaxVersion` _: 1 | 1.1 | 1.2 | 1.3_ _**optional**_ - Maximum allowed TLS version on SSL connections to this backend. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is not 1, 1.1, 1.2, or 1.3 - `certificateHostname` _: string_ _**optional**_ - Define the hostname that the server certificate should declare. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `caCertificate` _: string_ _**optional**_ - The CA certificate to use when checking the validity of the backend. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `ciphers` _: string_ _**optional**_ - List of OpenSSL ciphers to support for connections to this origin. - If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. - [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is an empty string. - `clientCertificate` _: object_ _**optional**_ - The client certificate to provide for the TLS handshake - `certificate` _: string_ - The PEM certificate string. - `key` _: SecretStoreEntry_ - The `SecretStoreEntry` to use for the key, created via [`SecretStore.prototype.get`](../fastly:secret-store/SecretStore/prototype/get.mdx) or alteratively via [`SecretStore.fromBytes`](../fastly:secret-store/SecretStore/fromBytes.mdx). - `httpKeepalive` _: number_ _**optional**_ - Enable HTTP keepalive, setting the timout in milliseconds. - `tcpKeepalive` _: boolean | object_ _**optional**_ - Enable TCP keepalive. When an object, optionally setting the keepalive configuration options. - `timeSecs` _: number_ _**optional**_ - Configure how long to wait after the last sent data over the TCP connection before starting to send TCP keepalive probes. - `intervalSecs` _: number_ _**optional**_ - Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. - `probes` _: number_ _**optional**_ - Number of probes to send to the backend before it is considered dead. ## Syntax ```js setDefaultDynamicBackendConfig(defaultConfig) ``` ### Return value None. ## Examples In this example an explicit Dynamic Backend is created and supplied to the fetch request, with timeouts and TLS options provided from the default backend configuration options. import { allowDynamicBackends } from "fastly:experimental"; import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! // Timeouts and TLS configuration still get set from the default backend configuration above. const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; import { Backend } from "fastly:backend"; allowDynamicBackends(true); setDefaultDynamicBackendConfig({ connectTimeout: 1000, firstByteTimeout: 15_000, betweenBytesTimeout: 10_000, useSSL: true, sslMinVersion: 1.3, sslMaxVersion: 1.3 }); async function app() { // For any request, return the fastly homepage -- without defining a backend! const backend = new Backend({ name: 'fastly', target: 'fastly.com', hostOverride: "www.fastly.com" }); return fetch('https://www.fastly.com/', { backend // Here we are configuring this request to use the backend from above. }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.age The **`age`** method of the `CacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.body The **`body`** method of the `CacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this `CacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.close The **`close`** method of the `CacheEntry` interface closes the connection to the cache for this `CacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.hits The **`hits`** method of the `CacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.length The **`length`** method of the `CacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.maxAge The **`maxAge`** method of the `CacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `CacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.state The **`state`** method of the `CacheEntry` interface returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheEntry.userMetadata The **`userMetadata`** method of the `CacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheState/found.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.found The **`found`** method of the `CacheState` interface returns `true` if a cached item was located. Even if an cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. ## Syntax ```js found() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item was located or not. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheState/mustInsertOrUpdate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.mustInsertOrUpdate The **`mustInsertOrUpdate`** method of the `CacheState` interface returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. ## Syntax ```js mustInsertOrUpdate() ``` ### Parameters None. ### Return value A `boolean` which represents whether a fresh cached item was found not. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheState/stale.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.stale The **`stale`** method of the `CacheState` interface returns `true` if the cached item is stale. A cached item is stale if its age is greater than its `maxAge` period. ## Syntax ```js stale() ``` ### Parameters None. ### Return value A `boolean` which represents whether the cached item is stale or not. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CacheState/usable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CacheState.usable The **`usable`** method of the `CacheState` interface returns `true` if the cached item is usable. A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. ## Syntax ```js usable() ``` ### Parameters None. ### Return value A `boolean` which represents whether a cached item is usable or not. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CoreCache/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.insert Performs a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. ## Syntax ```js insert(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item’s contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CoreCache/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.lookup Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. ## Syntax ```js lookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns `CacheEntry` if a usable cached item was found, otherwise returns `null`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/CoreCache/transactionLookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CoreCache.transactionLookup Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. Request Collapsing: If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, just one of the callers will be instructed to insert the item into the cache as part of the transaction. The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. Revalidation: Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. ## Syntax ```js transactionLookup(key, options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `headers` _: HeadersInit_ __optional__ - The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. - A lookup will succeed when there is at least one cached item that matches lookup’s `key`, and all of the lookup’s headers included in the cache items’ `vary` list match the corresponding headers in that cached item. - A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin’s response. - Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. ### Return value Returns an instance of `TransactionCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/SimpleCache/SimpleCache.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SimpleCache` The **`SimpleCache` class** provides a simplified interface to inserting and retrieving entries from Fastly's Cache. All the methods on the class are static methods, there are no instance methods. ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, if the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/SimpleCache/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.get ▸ **get**(): `string` Gets the entry associated with the key `key` from the cache. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the cache. ### Return value If the key does not exist in the cache, this returns `null`. If the key does exist in the cache, this returns a `SimpleCacheEntry`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example we attempt to retrieve an entry from the Fastly Cache, and return a message stating whether the entry was in the Fastly Cache or not. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.get(path); return new Response(page ? `${path} is in the cache` : `${path} is not in the cache`, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/SimpleCache/getOrSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.getOrSet The **`getOrSet()`** method attempts to get an entry from the cache for the supplied `key`. If no entry is found (or has expired), the supplied `set` function is executed and its result is inserted into the cache under the supplied `key` and for the supplied `ttl` (Time-To-Live) duration, provided in seconds. ## Syntax ```js getOrSet(key, set) getOrSet(key, set, length) ``` ### Parameters - `key` _: string_ - The key to lookup and/or store the supplied entry under within the cache. - `set` _: Function_ - The function to execute if and only if the cache does not have a usable entry for the supplied `key`. The function should return a Promise which resolves with the following interface: - `value` _: ArrayBuffer | TypedArray | DataView | ReadableStream | URLSearchParams | String | string literal_ - The value to store within the cache. - `ttl` _: number_ - The maximum number of seconds to store the supplied entry in the cache. - `length` _: number_ __optional__ - The length of the value being stored within the cache. This is only used when the `value` is a `ReadableStream`. ### Return value Returns a `SimpleCacheEntry`. ### Exceptions - If the provided `key`: - Cannot be coerced to a string - Is an empty string - Is longer than 8135 characters - If the provided `ttl`: - Cannot be coerced to a number - Is a negative number - Is `NaN` - Is Inifinity ## Examples In this example we attempt to retrieve an entry from the Fastly Cache. If the entry does not exist, we create the content and insert it into the Fastly Cache before finally returning. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const path = new URL(event.request.url).pathname; let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/SimpleCache/purge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCache.purge purge the entry associated with the key `key` from the cache. ## Syntax ```js purge(key, options) ``` ### Parameters - `key` _: string_ - The key to purge from within the cache. - `options` _: object_ - `scope` _: string_ - : Where to purge the content from. - Possible values are: - "global" - This will remove the content from all of Fastly. - "pop" - This will remove the content from the POP that contains the currently executing instance. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Cannot be coerced to a string - Is longer than 8135 characters ## Examples In this example, when a request contains a `purge` querystring parameter, we purge the an entry from the cache. ```js /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request.url); const path = url.pathname; if (url.searchParams.has('purge')) { SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/SimpleCacheEntry/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.arrayBuffer() The **`arrayBuffer()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/SimpleCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.body The **`body`** read-only property of the `SimpleCacheEntry` interface is a `ReadableStream` of the instance's contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/SimpleCacheEntry/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.bodyUsed The **`bodyUsed`** read-only property of the `SimpleCacheEntry` interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/SimpleCacheEntry/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.json() The **`json()`** method of the `SimpleCacheEntry` interface takes a `SimpleCacheEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/SimpleCacheEntry/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SimpleCacheEntry.text() The **`text()`** method of the `SimpleCacheEntry` interface takes the instance's stream and reads it to completion. It returns a promise that resolves with a `String`. The result is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/age.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.age The **`age`** method of the `TransactionCacheEntry` interface returns the current age in milliseconds of the cached item. ## Syntax ```js age() ``` ### Parameters None. ### Return value A `number` which represents the current age in milliseconds of the cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.body The **`body`** method of the `TransactionCacheEntry` interface retrieves the cached item contents as a `ReadableStream`. Only one stream can be active at a time for a given `TransactionCacheEntry`. An error will be thrown if a stream is already active for this `TransactionCacheEntry`. ## Syntax ```js body(options) ``` ### Parameters - `options` _: object_ __optional__ - `start` _: number_ - The offset from which to start the range. - `end` _: number_ - How long the range should be. ### Return value A `ReadableStream` which contains the cached item contents. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.cancel The **`cancel`** method of the `TransactionCacheEntry` interface cancels an obligation to provide an object to the cache. ## Syntax ```js cancel() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.close The **`close`** method of the `TransactionCacheEntry` interface closes the connection to the cache for this `TransactionCacheEntry`. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/hits.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.hits The **`hits`** method of the `TransactionCacheEntry` interface returns the amount of cache hits for the cached item. Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. ## Syntax ```js hits() ``` ### Parameters None. ### Return value A `number` which represents the number of cache hits to this cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/insert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insert Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. ## Syntax ```js insert(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns a `FastlyBody`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/insertAndStreamBack.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.insertAndStreamBack Perform a transaction cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.protoype.close` must be called. If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. ## Syntax ```js insertAndStreamBack(options) ``` ### Parameters - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. - `sensitive` _: boolean_ __optional__ - Enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is false. - [See the Fastly PCI-Compliant Caching and Delivery documentation for details.](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) ### Return value Returns an array where the first item is a `FastlyBody` instance and the second item is a `CacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.length The **`length`** method of the `TransactionCacheEntry` interface returns the size in bytes of the cached item, if known, otherwise returns `null` if the length is currently unknown. The length of the cached item may be unknown if the item is currently being streamed into the cache without a fixed length. ## Syntax ```js length() ``` ### Parameters None. ### Return value A `number` or `null` which represents the current length of the cached item. `null` is returned if the length is currently unknown. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/maxAge.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.maxAge The **`maxAge`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which the cached item is considered fresh. ## Syntax ```js maxAge() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which the cached item is considered fresh. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/staleWhileRevalidate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.staleWhileRevalidate The **`staleWhileRevalidate`** method of the `TransactionCacheEntry` interface returns the time in milliseconds for which a cached item can safely be used despite being considered stale. ## Syntax ```js staleWhileRevalidate() ``` ### Parameters None. ### Return value A `number` which represents the time in milliseconds for which a cached item can safely be used despite being considered stale. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/state.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.state The **`state`** method of the `TransactionCacheEntry` interface returns a `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ## Syntax ```js state() ``` ### Parameters None. ### Return value A `CacheState` instance which reflects the current state of this `TransactionCacheEntry` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/update.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.update Perform an update of the cache item's metadata. ## Syntax ```js update(options) ``` ### Parameters - `key` _: string_ - A cache key which is a string with a length of up to 8,135 that identify a cached item. - The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. - `options` _: object_ - `maxAge` _: number_ __optional__ - Sets the “time to live” for the cache item in milliseconds: The time for which the item will be considered fresh. - `vary` _: array_ __optional__ - Sets the list of headers that must match when looking up this cached item. - `initialAge` _: number_ __optional__ - Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. - The initial age is 0 by default. - `staleWhileRevalidate` _: number_ __optional__ - Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. - Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. - The methods `CacheState.protoype.usable` and `CacheState.protoype.stale` can be used to determine the current state of an item. - The stale-while-revalidate period is 0 by default. - `surrogateKeys` _: array_ __optional__ - Sets the surrogate keys that can be used for purging this cached item. - Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item’s TTL to elapse, or overwriting the item with insert(). - Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. - [See the Fastly surrogate keys guide for details.](https://docs.fastly.com/en/guides/working-with-surrogate-keys) - `length` _: number_ __optional__ - Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. - It is preferable to provide a length, if possible. - Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. - `userMetadata` _: ArrayBufferView | ArrayBuffer | URLSearchParams | string_ __optional__ - Sets the user-defined metadata to associate with the cached item. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache/TransactionCacheEntry/userMetadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransactionCacheEntry.userMetadata The **`userMetadata`** method of the `TransactionCacheEntry` interface returns the user-controlled metadata associated with the cached item. ## Syntax ```js userMetadata() ``` ### Parameters None. ### Return value An `ArrayBuffer` which contains the user-controlled metadata associated with the cached item. ================================================ FILE: documentation/versioned_docs/version-3.41.2/cache-override/CacheOverride/CacheOverride.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CacheOverride()` The **`CacheOverride` constructor** lets you configure the caching behavior of a `Response`. Normally, the HTTP Headers on a [`Response`](../../globals/Response/Response.mdx) would control how the [`Response`](../../globals/Response/Response.mdx) is cached, but `CacheOverride` can be set on a [`Request`](../../globals/Request/Request.mdx), to define custom caching behavior. ## Syntax ```js new CacheOverride(mode) new CacheOverride(mode, init) new CacheOverride(init) ``` > **Note:** `CacheOverride()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `mode` _: string_ - Sets the cache override mode for a request - If set to: - `"none"`: Do not override the behavior specified in the origin response’s cache control headers. - `"pass"`: Do not cache the response to this request, regardless of the origin response’s headers. - `"override"`: Override particular cache control settings using the `CacheOverride` object's settings. This options is also the default when providing an init object directly as the first argument. - `init` - : An Object which contains all the configuration options to apply to the newly created `CacheOverride`. - `pci` _: boolean_ _**optional**_ - Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching. - By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it to `true` to enable compliant caching. - See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. - `surrogateKey` _: string_ _**optional**_ - Override the caching behavior of this request to include the given surrogate key, provided as a header value. - See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details. - `swr` _: number_ _**optional**_ - Override the caching behavior of this request to use the given `stale-while-revalidate` time, in seconds - `ttl` _: number_ _**optional**_ - Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. - `beforeSend` _:Function_ _**optional**_ - `(request: Request) => void | PromiseLike` - Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. - See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) in the Fastly cache interfaces documentation for details. - `afterSend` _: Function_ _**optional**_ - `(response: Response) => void | CacheOptions | PromiseLike` - Callback to be invoked after a response has been sent, but before it is stored into the cache. - Where `CacheOptions` contains: - `cache` _: boolean | 'uncacheable'_ _**optional**_ - Whether to cache this response. By default, leaving this field empty, responses will be cached based on their cache header information. - Setting this to true or false will override this default cache behaviour, setting in the cache or not setting in the cache, even if the default behaviour would have been otherwise. - Setting to 'uncacheable' the response will not only not be cached, but the cache will record that the originating request led to an uncacheable response, so that future cache lookups will result in immediately going to the backend, rather than attempting to coordinate concurrent requests to reduce backend traffic. - See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) for more details on the mechanism that `uncacheable` disables. - `bodyTransformFn` _: Function_ _**optional**_ - `(body: Uint8Array) => Uint8Array | PromiseLike` - Provide a function to be used for transforming the response body prior to caching. - Body transformations are performed by specifying a transform, rather than by directly working with the body during the onAfterSend callback function, because not every response contains a fresh body: 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because they do not retransmit the body. - For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will be applied to it. The original backend body is passed in to the transform function, and the function is expected to return the new body. - See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) in the Fastly cache interfaces documentation for details. ### Return value A new `CacheOverride` object. ## Examples In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), and the home page to have a short TTL and a long SWR (Stale While Revalidate). import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { CacheOverride } from "fastly:cache-override"; // In this example we override the cache for all the requests prefixed /static/ // to have a long TTL (Time To Live), and the home page to have a short TTL and // a long SWR (Stale While Revalidate). async function app (event) { const path = (new URL(event.request.url)).pathname; let cacheOverride; if (path == '/') { cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); } else if (path.startsWith('/static/')) { cacheOverride = new CacheOverride('override', {ttl: 86_400}); } else { cacheOverride = new CacheOverride('none') } return fetch(event.request.url, { cacheOverride, backend: 'origin_0' }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/compute/purgeSurrogateKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # purgeSurrogateKey The **`purgeSurrogateKey()`** function is used to purge the given surrogate key string from Fastly's cache. There are two purge modes: soft purge and hard purge, with hard purge as the default which clears all items from the cache immediately. When using a soft purge, stale entries are maintained in the cache, reducing orgin load, while also enabling stale revalidations. See the [Fastly Purge Documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) for more information on caching and purge operations. ## Syntax ```js purgeSurrogateKey(surrogateKey, soft?) ``` ### Parameters - `surrogateKey` _: string_ - The surrogate key string - `soft?` _: boolean_ - Enables a soft purge, retaining stale entries in the cache. Default is a hard purge. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/compute/vCpuTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # vCpuTime The **`vCpuTime()`** function provides the vCPU time used by the current request handler in milliseconds. ## Syntax ```js vCpuTime() ``` ### Parameters None. ### Return value `number`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/config-store/ConfigStore/ConfigStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ConfigStore()` The **`ConfigStore` constructor** lets you access a specific [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). > **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new ConfigStore(name); ``` > **Note:** `ConfigStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Defines a config store instance using the resource link name. ### Return value A new `ConfigStore` object. ### Exceptions - `TypeError` - Thrown if no Config Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have a resource link named "animals" (which is linked to a config store) and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/config-store/ConfigStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ConfigStore.prototype.get The **`get()`** method returns the value associated with the provided key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified ConfigStore value or `null` if the key does not exist in the ConfigStore ## Description Get a value for a key in the config-store. If the provided key does not exist in the ConfigStore then this returns `null`. The `get()` method requires its `this` value to be a [`ConfigStore`](../../../fastly%3Aconfig-store/ConfigStore/ConfigStore.mdx) object. If the `this` value does not inherit from `ConfigStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { ConfigStore } from "fastly:config-store"; async function app (event) { const config = new ConfigStore('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/lookup.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.lookup() Look up the data associated with a particular User-Agent string. ## Syntax ```js lookup(userAgent) ``` ### Return value If there is data associated with the User-Agent, a `Device` instance is returned. Otherwise, `null` is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/brand.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.brand The read-only **`brand`** property of the `Device` interface is either a string stating the brand of the device, which can be different from the manufacturer of that device. If no brand is known, the value will be `null`. ## Value Either a string value if a brand is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/hardwareType.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.hardwareType The read-only **`hardwareType`** property of the `Device` interface is either a string stating the hardware type of the device, or `null` if the hardware type is not known. A string representation of the device's primary platform hardware. The most commonly used device types are also identified via boolean variables. Because a device may have multiple device types and this variable only has the primary type, we recommend using the boolean variables for logic and using this string representation for logging. ## Value Either a string value if a hardware type is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/isBot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isBot The read-only **`isBot`** property of the `Device` interface is either a boolean stating if the device is a bot, or `null` if the this is not known. ## Value Either a boolean stating if the device is a bot, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/isDesktop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isDesktop The read-only **`isDesktop`** property of the `Device` interface is either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ## Value Either a boolean stating if the device is a desktop web browser, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/isGameConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isGameConsole The read-only **`isGameConsole`** property of the `Device` interface is either a boolean stating if the device is a video game console, or `null` if the this is not known. ## Value Either a boolean stating if the device is a video game console, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/isMediaPlayer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMediaPlayer The read-only **`isMediaPlayer`** property of the `Device` interface is either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ## Value Either a boolean stating if the device is a media player (like Blu-ray players, iPod devices, and smart speakers such as Amazon Echo), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/isMobile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isMobile The read-only **`isMobile`** property of the `Device` interface is either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ## Value Either a boolean stating if the device is a mobile phone, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/isSmartTV.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isSmartTV The read-only **`isSmartTV`** property of the `Device` interface is either a boolean stating if the device is a smart TV, or `null` if the this is not known. ## Value Either a boolean stating if the device is a smart TV, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/isTablet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTablet The read-only **`isTablet`** property of the `Device` interface is either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ## Value Either a boolean stating if the device is a tablet (like an iPad), or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/isTouchscreen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.isTouchscreen The read-only **`isTouchscreen`** property of the `Device` interface is either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ## Value Either a boolean stating if the device's screen is touch sensitive, or `null` if the this is not known. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/model.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.model The read-only **`model`** property of the `Device` interface is either a string stating the model of the device, or `null` if the model is not known. ## Value Either a string value if a model is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Device.prototype.name The read-only **`name`** property of the `Device` interface is either a string stating the name of the device, or `null` if the name is not known. ## Value Either a string value if a name is known, otherwise `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/device/Device/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # toJSON The `toJSON()` method of the Device interface is a serializer; it returns a JSON representation of the Device object. To get a JSON string, you can use `JSON.stringify(device)` directly; it will call `toJSON()` automatically. ## Syntax ```js toJSON() ``` ### Return value A JSON object that is the serialization of the Device object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/dictionary/Dictionary/Dictionary.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Dictionary()` :::info This Class is deprecated ::: The **`Dictionary` constructor** lets you access a specific [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new Dictionary(name); ``` > **Note:** `Dictionary()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The name of the [Fastly Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries) that this `Dictionary` instance should provide access to. ### Return value A new `Dictionary` object. ### Exceptions - `TypeError` - Thrown if no Dictionary exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name does not contain only ascii alphanumeric, underscore, and whitespace characters ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/dictionary/Dictionary/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Dictionary.prototype.get :::info This Class is deprecated, it has been renamed to [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) and can be imported via `import { ConfigStore } from 'fastly:config-store'` The `get()` method exists on the [`ConfigStore`](../../../fastly:config-store/ConfigStore/ConfigStore.mdx) Class. ::: The **`get()`** method returns the value associated with the provided key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from the dictionary. ### Return value A `string` representing the specified Dictionary value or `null` if the key does not exist in the Dictionary ## Description Get a value for a key in the dictionary. If the provided key does not exist in the Dictionary then this returns `null`. The `get()` method requires its `this` value to be a [`Dictionary`](../Dictionary.mdx) object. If the `this` value does not inherit from `Dictionary.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - Thrown if the provided key is longer than 255 in length - Thrown if the provided key is an empty string ## Examples In this example we have an Edge Dictionary named "animals" and we return the "cat" entry as the response body to the client. import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Dictionary } from "fastly:dictionary"; async function app (event) { const config = new Dictionary('animals'); return new Response(config.get('cat')); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/edge-rate-limiter/EdgeRateLimiter/EdgeRateLimiter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `EdgeRateLimiter()` The **`EdgeRateLimiter` constructor** lets you open an epen a [ERL](https://docs.fastly.com/products/edge-rate-limiting) with the given ratecounter and penaltybox. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new EdgeRateLimiter(rateCounter, penaltyBox) ``` > **Note:** `EdgeRateLimiter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `rateCounter` _: RateCounter_ - The RateCounter instance to associate with this EdgeRateLimiter instance - `penaltyBox` _: PenaltyBox_ - The PenaltyBox instance which should be associated with this EdgeRateLimiter instance ### Return value A new `EdgeRateLimiter` object. ### Exceptions - `TypeError` - Thrown if the provided rateCounter value is not an instance of RateCounter - Thrown if the provided penaltyBox value is not an instance of PenaltyBox ================================================ FILE: documentation/versioned_docs/version-3.41.2/edge-rate-limiter/EdgeRateLimiter/prototype/checkRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EdgeRateLimiter.prototype.checkRate Increment an entry in the rate counter and check if the entry has exceeded some average number of requests per second (RPS) over the given window. If the entry is over the RPS limit for the window, add to the penaltybox for the given `timeToLive`. Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ## Syntax ```js checkRate(entry, delta, window, limit, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to increment and check - `delta` _: number_ - The amount to increment the `entry` by - `window` _: number_ - The time period to check across, has to be either 1 second, 10 seconds, or 60 seconds - `limit` _: number_ - The requests-per-second limit - `timeToLive` _: number_ - In minutes, how long the entry should be added into the penalty-box - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `true` if the entry has exceeded the average RPS for the window, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive finite number. - Thrown if the provided `window` value is not either, 1, 10, or 60. - Thrown if the provided `limit` value is not a positive finite number. - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.41.2/edge-rate-limiter/PenaltyBox/PenaltyBox.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `PenaltyBox()` The **`PenaltyBox` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for adding and checking if some entry is in the dataset. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new PenaltyBox(name) ``` > **Note:** `PenaltyBox()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a PenaltyBox with the given name ### Return value A new `PenaltyBox` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.41.2/edge-rate-limiter/PenaltyBox/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.add Add an `entry` into the PenaltyBox for the duration of the given `timeToLive`. ## Syntax ```js add(entry, timeToLive) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `timeToLive` _: number_ - In minutes, how long the entry should be added into the PenaltyBox - Valid `timeToLive` is 1 minute to 60 minutes and `timeToLive` value is truncated to the nearest minute. ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `timeToLive` value is not either, a number between 1 and 60 inclusively. ================================================ FILE: documentation/versioned_docs/version-3.41.2/edge-rate-limiter/PenaltyBox/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # PenaltyBox.prototype.has Check if the given entry is contained in in the PenaltyBox instance. ## Syntax ```js has(entry) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up ### Return value Returns `true` if the entry is contained in the PenaltyBox instance, otherwise returns `false`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.41.2/edge-rate-limiter/RateCounter/RateCounter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `RateCounter()` The **`RateCounter` constructor** can be used with a [Edge Rate Limiter](../EdgeRateLimiter/EdgeRateLimiter.mdx) or standalone for counting and rate calculations. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new RateCounter(name) ``` > **Note:** `RateCounter()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Open a RateCounter with the given name ### Return value A new `RateCounter` object instance. ### Exceptions - `TypeError` - Thrown if the provided `name` value can not be coerced into a string ================================================ FILE: documentation/versioned_docs/version-3.41.2/edge-rate-limiter/RateCounter/prototype/increment.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.increment Increment the given `entry` in the RateCounter instance with the given `delta` value. ## Syntax ```js increment(entry, delta) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `delta` _: number_ - The amount to increment the entry by ### Return value Returns `undefined`. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `delta` value is not a positive, finite number. ================================================ FILE: documentation/versioned_docs/version-3.41.2/edge-rate-limiter/RateCounter/prototype/lookupCount.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupCount Look up the current rate for the given `entry` and the given `duration`. ## Syntax ```js lookupCount(entry, duration) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `duration` _: number_ - The duration to lookup alongside the entry, has to be either, 10, 20, 30, 40, 50, or 60 seconds. ### Return value Returns a number which is the count for the given `entry` and `duration` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `duration` value is not either, 10, 20, 30, 40, 50 or 60. ================================================ FILE: documentation/versioned_docs/version-3.41.2/edge-rate-limiter/RateCounter/prototype/lookupRate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RateCounter.prototype.lookupRate Look up the current rate for the given `entry` and the given `window`. ## Syntax ```js lookupRate(entry, window) ``` ### Parameters - `entry` _: string_ - The name of the entry to look up - `window` _: number_ - The window to look up alongside the entry, has to be either 1 second, 10 seconds, or 60 seconds ### Return value Returns a number which is the rate for the given `entry` and `window` in this `RateCounter` instance. ### Exceptions - `TypeError` - Thrown if the provided `entry` value can not be coerced into a string - Thrown if the provided `window` value is not either, 1, 10, or 60. ================================================ FILE: documentation/versioned_docs/version-3.41.2/env/env.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # env The **`env()`** function returns the value for the provided environment variable name. For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) >**Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. ## Syntax ```js env(name) ``` ### Parameters - `name` _: string_ - The name of the environment variable to retrieve ### Return value The value for the requested environment variable, if no such environment variable exists then an empty string is returned. ## Examples In this example we log to stdout the environment variables [`FASTLY_HOSTNAME`](https://developer.fastly.com/reference/compute/ecp-env/fastly-hostname/) and [`FASTLY_TRACE_ID`](https://developer.fastly.com/reference/compute/ecp-env/fastly-trace-id/). import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { env } from "fastly:env"; function app(event) { console.log("FASTLY_HOSTNAME:", env("FASTLY_HOSTNAME")); console.log("FASTLY_TRACE_ID:", env("FASTLY_TRACE_ID")); return new Response("", { status: 200 }); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/experimental/allowDynamicBackends.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # allowDynamicBackends The **`allowDynamicBackends()`** function is used to control whether or not Dynamic Backends should be allowed within this Fastly Compute Service. By default, Dynamic Backends are disabled within a JavaScript application as it can be a potential avenue for third-party JavaScript code to send requests, potentially including sensitive/secret data, off to destinations that the JavaScript project was not intending, which could be a security issue. >**Note**: This feature is in disabled by default for Fastly Services. Please contact [Fastly Support](https://support.fastly.com/hc/requests/new?ticket_form_id=360000269711) to request the feature be enabled on the Fastly Services which require Dynamic Backends. ## Syntax ```js allowDynamicBackends(enabledOrConfig) ``` ### Parameters - `enabledOrConfig` _: boolean_ - Whether or not to allow Dynamic Backends or - `enabledOrConfig` _: object_ - `connectTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for a connection to this backend to be established. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `firstByteTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. - If exceeded, the connection is aborted and a 503 response will be presented instead. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 - `betweenBytesTimeout` _: number_ _**optional**_ - Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. - If exceeded, the response received so far will be considered complete and the fetch will end. - Throws a [`RangeError`](../globals/RangeError/RangeError.mdx) if the value is negative or greater than or equal to 2^32 ### Return value `undefined`. ## Examples In this example an implicit Dynamic Backend is created when making the fetch request to https://www.fastly.com/ and the response is then returned to the client. import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { allowDynamicBackends } from "fastly:experimental"; allowDynamicBackends(true); async function app() { // For any request, return the fastly homepage -- without defining a backend! return fetch('https://www.fastly.com/'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/experimental/includeBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # includeBytes The **`includeBytes()`** function is used embed a file as a Uint8Array. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js includeBytes(path) ``` ### Parameters - `path` _: string_ - The path to include, relative to the Fastly Compute application's top-level directory during build-time initialization. ### Return value Returns a `Uint8Array` ## Examples In this example we include the README.md file as a Uint8Array and use it for the body in the response we return to the client. ```js /// import { includeBytes } from "fastly:experimental"; const readme = includeBytes('README.md'); async function app() { return new Response(readme); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/experimental/mapAndLogError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapAndLogError The **`mapAndLogError()`** function calls `mapError` on an `Error` object and sends the output to standard error. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapAndLogError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value `undefined`. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { mapAndLogError(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | mapAndLogError(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/experimental/mapError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # mapError The **`mapError()`** function extracts information from an `Error` object as a human-readable array of strings. This includes the error name, message, and a call stack. If `--enable-stack-traces` is specified during the build, the call stack will be mapped using source maps. If `--enable-stack-traces` is specified and `--exclude-sources` is not specified during the build, then this will also include a code dump of neighboring lines of user code. ## Syntax ```js mapError(error) ``` ### Parameters - `error` _: Error _ or _string_ - The error to retrieve information about. If a `string` is provided, then it is first converted to an `Error`. ### Return value Returns an array of `string`s. ## Examples In this example, build the application using the `--enable-stack-traces` flag. ```js addEventListener('fetch', e => e.respondWith(handler(e))); async function handler(event) { try { throw new TypeError('foo'); } catch (err) { console.error(mapError(err)); } return new Response('ok'); } ``` The following is output to the error log. ``` TypeError: foo at handler (src/index.ts:4:11) 1 | addEventListener('fetch', e => e.respondWith(handler(e))); 2 | async function handler(event) { 3 | try { > 4 | throw new TypeError('foo'); ^ 5 | } catch (err) { 6 | console.error(mapError(err)); 7 | } at src/index.ts:1:45 ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/experimental/sdkVersion.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sdkVersion The read-only **`sdkVersion`** property is a string whose indicates what JavaScript SDK version is being used. ## Value A string value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/experimental/setReusableSandboxOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setReusableSandboxOptions The **`setReusableSandboxOptions()`** function configures the reuse of the same underlying sandbox for multiple requests, which can improve performance by avoiding the overhead of initializing a new sandbox for each request. >**Note**: Can only be used during build-time initialization, not when processing requests. ## Syntax ```js setReusableSandboxOptions(options) ``` ### Parameters - `options` _: Object_ - The configuration options for the reusable sandbox. - `maxRequests` _: number_ (default: `1`, `0` means unlimited) - The maximum number of requests that can be handled by a single sandbox before it is recycled. - `betweenRequestTimeoutMs` _: number_ (default: not specified) - The amount of time in milliseconds to wait between requests before recycling the sandbox. - `maxMemoryMiB` _: number_ (default: no limit) - The maximum amount of memory in MiB that the sandbox can use before it is recycled. - `sandboxTimeoutMs` _: number_ (default: no timeout) - The maximum amount of time in milliseconds that a sandbox can be active before it is recycled. ================================================ FILE: documentation/versioned_docs/version-3.41.2/fanout/createFanoutHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createFanoutHandoff The **`createFanoutHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Fanout, to the declared backend. ## Syntax ```js createFanoutHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Fanout. - `backend` _: string_ - The name of the backend that Fanout should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Fanout. ```js import { createFanoutHandoff } from "fastly:fanout"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createFanoutHandoff(event.request, 'fanout'); } else { return new Response('oopsie, make a request to /stream for some fanout goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/geolocation/getGeolocationForIpAddress.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # getGeolocationForIpAddress The **`getGeolocationForIpAddress()`** function is used to retrieve geolocation information about the given IP address. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js getGeolocationForIpAddress(address) ``` ### Parameters - `address` _: string_ - The IPv4 or IPv6 address to query. ### Return value Returns an `Object`, or `null` if no geolocation data was found. The object contains information about the given IP address with the following properties: - `as_name` _: string | null_ - The name of the organization associated with `as_number`. - For example, fastly is the value given for IP addresses under AS-54113. - `as_number` _: number | null_ - [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. - `area_code` _: number | null_ - The telephone area code associated with an IP address. - These are only available for IP addresses in the United States, its territories, and Canada. - `city` _: string | null_ - City or town name. - `conn_speed` _: string | null_ - Connection speed. - `conn_type` _: string | null_ - Connection type. - `continent` _: string | null_ - Continent. - `country_code` _: string | null_ - A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. - The US country code is returned for IP addresses associated with overseas United States military bases. - These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. - `country_code3` _: string | null_ - A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. - The USA country code is returned for IP addresses associated with overseas United States military bases. - `country_name` _: string | null_ - Country name. - This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. - `gmt_offset` _: string | null_ - Time zone offset from Greenwich Mean Time (GMT) for `city`. - `latitude` _: number | null_ - Latitude, in units of degrees from the equator. - Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `longitude` _: number | null_ - Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). - Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. - `metro_code` _: number | null_ - Metro code, representing designated market areas (DMAs) in the United States. - `postal_code` _: string | null_ - The postal code associated with the IP address. - These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. - For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. - `proxy_description` _: string | null_ - Client proxy description. - `proxy_type` _: string | null_ - Client proxy type. - `region` _: string | null_ - [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. - For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. - This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). - `utc_offset` _: number | null;_ - Time zone offset from coordinated universal time (UTC) for `city`. ## Examples In this example we return the geolocation details for the provided ip querystring parameter or for the incoming client request if the querystring parameter does not exist. import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "data": { "dictionaries": { "animals": { "cat": "meow" } } }, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { getGeolocationForIpAddress } from "fastly:geolocation" async function app(event) { try { let ip = new URL(event.request.url).searchParams.get('ip') || event.client.address let geo = getGeolocationForIpAddress(ip); return new Response(JSON.stringify(geo), { headers: { "Content-Type": "application/json", }, }); } catch (error) { console.error(error); return new Response("Internal Server Error", { status: 500 }); } } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/AggregrateError/AggregrateError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # AggregateError() The **`AggregateError()`** constructor creates an error for several errors that need to be wrapped in a single error. ## Syntax ```js new AggregateError(errors) new AggregateError(errors, message) new AggregateError(errors, message, options) AggregateError(errors) AggregateError(errors, message) AggregateError(errors, message, options) ``` > **Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance. ### Parameters - `errors` - : An iterable of errors, may not actually be [`TypeError`](../Error/Error.mdx) instances. - `message` _**optional**_ - : An optional human-readable description of the aggregate error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array\[Symbol.species] The **`Array[Symbol.species]`** accessor property returns the constructor used to construct return values from array methods. > **Warning:** The existence of `[Symbol.species]` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Array[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get [Symbol.species]` was called. The return value is used to construct return values from array methods that create new arrays. ## Description The `[Symbol.species]` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `[Symbol.species]` of derived subclasses would also return the constructor itself by default. ```js class SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, `filter()` and `map()`), the array's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array() The **`Array()`** constructor is used to create `Array` objects. ## Syntax ```js new Array(element0, element1, /* … ,*/ elementN) new Array(arrayLength) Array(element0, element1, /* … ,*/ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without `new`. Both create a new `Array` instance. ### Parameters - `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values). ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/from.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.from The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object. ## Syntax ```js Array.from(arrayLike) // Arrow function Array.from(arrayLike, (element) => { /* … */ }) Array.from(arrayLike, (element, index) => { /* … */ }) // Mapping function Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // Inline mapping function Array.from(arrayLike, function (element) { /* … */ }) Array.from(arrayLike, function (element, index) { /* … */ }) Array.from(arrayLike, function (element) { /* … */ }, thisArg) Array.from(arrayLike, function (element, index) { /* … */ }, thisArg) ``` ### Parameters - `arrayLike` - : An iterable or array-like object to convert to an array. - `mapFn` _**optional**_ - : Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `thisArg` _**optional**_ - : Value to use as `this` when executing `mapFn`. ### Return value A new `Array` instance. ## Description `Array.from()` lets you create `Array`s from: - [iterable objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) (objects such as [`Map`](../Map/Map.mdx) and [`Set`](../Set/Set.mdx); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array. `Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`Array.prototype.map()`](./prototype/map.mdx). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/isArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.isArray() The **`Array.isArray()`** static method determines whether the passed value is an `Array`. ## Syntax ```js Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance. ## Description `Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/of.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.of() The **`Array.of()`** method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. ## Syntax ```js Array.of(element0) Array.of(element0, element1) Array.of(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : Elements used to create the array. ### Return value A new `Array` instance. ## Description The difference between `Array.of()` and the [`Array()`](./Array.mdx) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined.mdx) values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of an `Array` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](./values.mdx) property. ## Syntax ```js array[Symbol.iterator]() ``` ### Return value The same return value as [`Array.prototype.values()`](./values.mdx): a new iterable iterator object that yields the value of each index in the array. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/@@unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype[Symbol.unscopables] The **`@@unscopables`** data property of `Array.prototype` is shared by all `Array` instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](./at.mdx) - [`copyWithin()`](./copyWithin.mdx) - [`entries()`](./entries.mdx) - [`fill()`](./fill.mdx) - [`find()`](./find.mdx) - [`findIndex()`](./findIndex.mdx) - [`flat()`](./flat.mdx) - [`flatMap()`](./flatMap.mdx) - [`includes()`](./includes.mdx) - [`keys()`](./keys.mdx) - [`values()`](./values.mdx) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../../Object/prototype/toString.mdx) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See [`Symbol.unscopables`](../../Symbol/unscopables.mdx) for how to set unscopable properties for your own objects. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.at The **`at()`** method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ## Syntax ```js at(index) ``` ### Parameters - `index` - : Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed. ### Return value The element in the array matching the given index. Always returns [`undefined`](../../../globals/undefined.mdx) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index. The usual practice is to access [`Array.prototype.length`](./length.mdx) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`. The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.concat The **`concat()`** method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. ## Syntax ```js concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `valueN` _**optional**_ - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new `Array` instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../../Symbol/isConcatSpreadable.mdx) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a copying. It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is sparse. The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `Symbol.isConcatSpreadable` will be spread into the resulting array. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/copyWithin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.copyWithin The **`copyWithin()`** method shallow copies part of an array to another location in the same array and returns it without modifying its length. ## Syntax ```js copyWithin(target) copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, converted to an integer. - Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used. - If `target < -array.length`, `0` is used. - If `target >= array.length`, nothing is copied. - If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array). - `start` _**optional**_ - : Zero-based index at which to start copying elements from, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is copied. - `end` _**optional**_ - : Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied. - If `end` is positioned before or at `start` after normalization, nothing is copied. ### Return value The modified array. ## Description The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary. The `copyWithin()` method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `copyWithin()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.entries The **`entries()`** method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array. ## Syntax ```js entries() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/every.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.every The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. ## Syntax ```js // Arrow function every((element) => { /* … */ }) every((element, index) => { /* … */ }) every((element, index, array) => { /* … */ }) // Callback function every(callbackFn) every(callbackFn, thisArg) // Inline callback function every(function (element) { /* … */ }) every(function (element, index) { /* … */ }) every(function (element, index, array) { /* … */ }) every(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for every array element. Otherwise, `false`. ## Description The `every()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `every()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/fill.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.fill The **`fill()`** method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array. ## Syntax ```js fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` _**optional**_ - : Zero-based index at which to start filling, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` _**optional**_ - : Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` is positioned before or at `start` after normalization, no index is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a mutating method. It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in sparse arrays with `value` as well. The `fill()` method is generic. It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/filter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.filter The **`filter()`** method creates a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. ## Syntax ```js // Arrow function filter((element) => { /* … */ }) filter((element, index) => { /* … */ }) filter((element, index, array) => { /* … */ }) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function (element) { /* … */ }) filter(function (element, index) { /* … */ }) filter(function (element, index, array) { /* … */ }) filter(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `filter()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned. ## Description The `filter()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `filter()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `filter()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/find.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.find() The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../../../globals/undefined.mdx) is returned. - If you need the **index** of the found element in the array, use [`findIndex()`](./findIndex.mdx). - If you need to find the **index of a value**, use [`indexOf()`](./indexOf.mdx). (It's similar to [`findIndex()`](./findIndex.mdx), but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use [`includes()`](./includes.mdx). Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use [`some()`](./some.mdx). ## Syntax ```js // Arrow function find((element) => { /* … */ }) find((element, index) => { /* … */ }) find((element, index, array) => { /* … */ }) // Callback function find(callbackFn) find(callbackFn, thisArg) // Inline callback function find(function (element) { /* … */ }) find(function (element, index) { /* … */ }) find(function (element, index, array) { /* … */ }) find(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../../../globals/undefined.mdx) is returned. ## Description The `find()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../../../globals/undefined.mdx). `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `find()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/findIndex.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.findIndex The **`findIndex()`** method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the [`find()`](./find.mdx) method, which returns the first element that satisfies the testing function (rather than its index). ## Syntax ```js // Arrow function findIndex((element) => { /* … */ }) findIndex((element, index) => { /* … */ }) findIndex((element, index, array) => { /* … */ }) // Callback function findIndex(callbackFn) findIndex(callbackFn, thisArg) // Inline callback function findIndex(function (element) { /* … */ }) findIndex(function (element, index) { /* … */ }) findIndex(function (element, index, array) { /* … */ }) findIndex(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value to indicate a matching element has been found. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`. `findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are visited as if they were `undefined`. The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/flat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flat The **`flat()`** method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ## Syntax ```js flat() flat(depth) ``` ### Parameters - `depth` _**optional**_ - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/flatMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.flatMap() The **`flatMap()`** method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`Array.prototype.map()`](./map.mdx) followed by a [`Array.prototype.flat()`](./flat.mdx) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately. ## Syntax ```js // Arrow function flatMap((element) => { /* … */ }) flatMap((element, index) => { /* … */ }) flatMap((element, index, array) => { /* … */ }) // Callback function flatMap(callbackFn) flatMap(callbackFn, thisArg) // Inline callback function flatMap(function (element) { /* … */ }) flatMap(function (element, index) { /* … */ }) flatMap(function (element, index, array) { /* … */ }) flatMap(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `flatMap()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function and flattened by a depth of 1. ## Description The `flatMap()` method is an iterative method. See [`Array.prototype.map()`](./map.mdx) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](./map.mdx) followed by [`flat(1)`](./flat.mdx) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.forEach() The **`forEach()`** method executes a provided function once for each array element. ## Syntax ```js // Arrow function forEach((element) => { /* … */ }) forEach((element, index) => { /* … */ }) forEach((element, index, array) => { /* … */ }) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function (element) { /* … */ }) forEach(function (element, index) { /* … */ }) forEach(function (element, index, array) { /* … */ }) forEach(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `forEach()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined`. ## Description The `forEach()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`Array.prototype.map()`](./map.mdx), `forEach()` always returns [`undefined`](../../../globals/undefined.mdx) and is not chainable. The typical use case is to execute side effects at the end of a chain. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `forEach()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like [`Array.prototype.some()`](./some.mdx), [`Array.prototype.some()`](./some.mdx), [`Array.prototype.find()`](./find.mdx), and [`Array.prototype.findIndex()`](./findIndex.mdx) also stops iteration immediately when further iteration is not necessary. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.includes() The **`includes()`** method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `false` is returned. ### Return value A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). ## Description The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is _not_ considered to be the same as `0`. [`NaN`](../../NaN.mdx) can be correctly searched for. When used on sparse arrays, the `includes()` method iterates empty slots as if they have the value `undefined`. The `includes()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.indexOf() The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present. ## Syntax ```js indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of the element in the array; **-1** if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `indexOf()` method skips empty slots in sparse arrays. The `indexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/join.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.join() The **`join()`** method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. ## Syntax ```js join() join(separator) ``` ### Parameters - `separator` _**optional**_ - : Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. ### Return value A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](./toString.mdx) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. When used on sparse arrays, the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.keys() The **`keys()`** method returns a new **Array Iterator** object that contains the keys for each index in the array. ## Syntax ```js keys() ``` ### Return value A new `Array` iterator object. ## Description When used on sparse arrays, the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.lastIndexOf() The **`lastIndexOf()`** method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. ## Syntax ```js lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` _**optional**_ - : Zero-based index at which to start searching backwards, converted to an integer. - Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of the element in the array; **-1** if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). The `lastIndexOf()` method skips empty slots in sparse arrays. The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.length The **`length`** data property of an `Array` instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. ## Value A non-negative integer less than 232. ## Description The value of the `length` property is a non-negative integer with a value less than 232. ```js const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length ``` The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means: - Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted. - Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index. - Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.map() The **`map()`** method **creates a new array** populated with the results of calling a provided function on every element in the calling array. ## Syntax ```js // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /* … */ }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function (element) { /* … */ }) map(function (element, index) { /* … */ }) map(function (element, index, array) { /* … */ }) map(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `map()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value A new array with each element being the result of the callback function. ## Description The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. The `map()` method is a copying method. It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`Array.prototype.forEach()`](./forEach.mdx) or `for...of` instead. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/pop.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.pop() The **`pop()`** method removes the **last** element from an array and returns that element. This method changes the length of the array. ## Syntax ```js pop() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../../../globals/undefined.mdx). [`Array.prototype.shift()`](./shift.mdx) has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](./slice.mdx) instead. The `pop()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/push.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.push() The **`push()`** method adds one or more elements to the end of an array and returns the new length of the array. ## Syntax ```js push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The element(s) to add to the end of the array. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `push()` method appends values to an array. [`Array.prototype.unshift()`](./unshift.mdx)has similar behavior to `push()`, but applied to the start of an array. The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](./concat.mdx) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`. The `push()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/reduce.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduce() The **`reduce()`** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array: The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add. ## Syntax ```js // Arrow function reduce((accumulator, currentValue) => { /* … */ }) reduce((accumulator, currentValue, currentIndex) => { /* … */ }) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }) reduce((accumulator, currentValue) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue) reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue) // Callback function reduce(callbackFn) reduce(callbackFn, initialValue) // Inline callback function reduce(function (accumulator, currentValue) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }) reduce(function (accumulator, currentValue) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`. - `currentValue` - : The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `initialValue` _**optional**_ - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire array. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : The array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. `reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ### When to not use reduce() Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/reduceRight.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reduceRight() The **`reduceRight()`** method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. See also [`Array.prototype.reduce()`](./reduce.mdx) for left-to-right. ## Syntax ```js // Arrow function reduceRight((accumulator, currentValue) => { /* … */ }) reduceRight((accumulator, currentValue, index) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }) reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue) // Callback function reduceRight(callbackFn) reduceRight(callbackFn, initialValue) // Callback reducer function reduceRight(function (accumulator, currentValue) { /* … */ }) reduceRight(function (accumulator, currentValue, index) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }) reduceRight(function (accumulator, currentValue, index, array) { /* … */ }, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.) - `currentValue` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `reduceRight()` was called upon. - `initialValue` _**optional**_ - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description The `reduceRight()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. Unlike other [iterative methods](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `reduceRight()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/reverse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.reverse() The **`reverse()`** method reverses an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. ## Syntax ```js reverse() ``` ### Return value The reference to the original array, now reversed. Note that the array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. The `reverse()` method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are [deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) and also become empty slots. The `reverse()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/shift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.shift() The **`shift()`** method removes the **first** element from an array and returns that removed element. This method changes the length of the array. ## Syntax ```js shift() ``` ### Return value The removed element from the array; [`undefined`](../../../globals/undefined.mdx) if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`Array.prototype.length`](./length.mdx) property is 0, [`undefined`](../../../globals/undefined.mdx) is returned. The [`Array.prototype.pop()`](./pop.mdx) method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](./slice.mdx) instead. The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.slice() The **`slice()`** method returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified. ## Syntax ```js slice() slice(start) slice(start, end) ``` ### Parameters - `start` _**optional**_ - : Zero-based index at which to start extraction, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, nothing is extracted. - `end` _**optional**_ - : Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted. - If `end` is positioned before or at `start` after normalization, nothing is extracted. ### Return value A new array containing the extracted elements. ## Description The `slice()` method is a copying method. It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array. The `slice()` method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well. The `slice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/some.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.some() The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. ## Syntax ```js // Arrow function some((element) => { /* … */ }) some((element, index) => { /* … */ }) some((element, index, array) => { /* … */ }) // Callback function some(callbackFn) some(callbackFn, thisArg) // Inline callback function some(function (element) { /* … */ }) some(function (element, index) { /* … */ }) some(function (element, index, array) { /* … */ }) some(function (element, index, array) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `true` if the callback function returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`. ## Description The `some()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays. `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. The `some()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.sort() The **`sort()`** method sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ## Syntax ```js // Functionless sort() // Arrow function sort((a, b) => { /* … */ } ) // Compare function sort(compareFn) // Inline compare function sort(function compareFn(a, b) { /* … */ }) ``` ### Parameters - `compareFn` _**optional**_ - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b` | | < 0 | sort `a` before `b` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/splice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.splice() The **`splice()`** method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`Array.prototype.slice()`](./slice.mdx). ## Syntax ```js splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, converted to an integer. - Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` _**optional**_ - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` _**optional**_ - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a mutating method. It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](../@@species.mdx) to create a new array instance to be returned. If the deleted portion is sparse, the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ","). ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). - `options` _**optional**_ - : An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx); for dates, see [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on sparse arrays, the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.toString() The **`toString()`** method returns a string representing the specified array and its elements. ## Syntax ```js toString() ``` ### Return value A string representing the elements of the array. ## Description The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls [`join()`](../../../globals/Array/prototype/join.mdx) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../../../globals/Object/prototype/toString.mdx) is used instead, returning `[object Array]`. ```js const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call({ join: () => 1 })); // 1 ``` JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/unshift.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.unshift() The **`unshift()`** method adds one or more elements to the beginning of an array and returns the new length of the array. ## Syntax ```js unshift(element0) unshift(element0, element1) unshift(element0, element1, /* … ,*/ elementN) ``` ### Parameters - `elementN` - : The elements to add to the front of the `arr`. ### Return value The new [`Array.prototype.length`](./length.mdx) property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. [`Array.prototype.push()`](./push.mdx) has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Array/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Array.prototype.values() The **`values()`** method returns a new _array [iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol)_ object that iterates the value of each index in the array. ## Syntax ```js values() ``` ### Return value A new iterable iterator object. ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](./@@iterator.mdx). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on sparse arrays, the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ArrayBuffer/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get ArrayBuffer\[Symbol.species] The **`ArrayBuffer[Symbol.species]`** accessor property returns the constructor used to construct return values from array buffer methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js ArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from array buffer methods that create new array buffers. ## Description The `Symbol.species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](./prototype/slice.mdx)), the object's `constructor[Symbol.species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ArrayBuffer/ArrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer() The **`ArrayBuffer()`** constructor is used to create "ArrayBuffer" objects. ## Syntax ```js new ArrayBuffer(length) ``` > **Note:** `ArrayBuffer()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `length` - : The size, in bytes, of the array buffer to create. ### Return value A new `ArrayBuffer` object of the specified size. Its contents are initialized to 0. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `length` is larger than `Number_MAX_SAFE_INTEGER` (≥ 253) or negative. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ArrayBuffer/isView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.isView The **`ArrayBuffer.isView()`** method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a [`DataView`](../DataView/DataView.mdx). ## Syntax ```js ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the `ArrayBuffer` views; otherwise, `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ArrayBuffer/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.byteLength The **`byteLength`** accessor property represents the length of an `ArrayBuffer` in bytes. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ArrayBuffer/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ArrayBuffer.prototype.slice() The **`slice()`** method returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. ## Syntax ```js slice(begin) slice(begin, end) ``` ### Parameters - `begin` - : Zero-based byte index at which to begin slicing. - `end` _**optional**_ - : Byte index before which to end slicing. If end is unspecified, the new `ArrayBuffer` contains all bytes from begin to the end of this `ArrayBuffer`. If negative, it will make the Byte index begin from the last Byte. ### Return value A new `ArrayBuffer` object. ## Description The `slice()` method copies up to, but not including, the byte indicated by the `end` parameter. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. The range specified by the `begin` and `end` parameters is clamped to the valid index range for the current array. If the computed length of the new `ArrayBuffer` would be negative, it is clamped to zero. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/BigInt/BigInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt() The **`BigInt()`** function returns a value of type **bigint**. ## Syntax ```js BigInt(value) ``` > **Note:** `BigInt()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `value` - : The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A `BigInt` value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if the parameter is a non-integral number. - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if at least one of these conditions is met: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is [`undefined`](../undefined.mdx), `null`, `Symbol`. - [`SyntaxError`](../SyntaxError/SyntaxError.mdx) - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/BigInt/asIntN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asIntN() The **`BigInt.asIntN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer. ## Syntax ```js BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`: ```plain 25n = 00011001 (base 2) ^=== Clamp to three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asIntN` is a static property of `BigInt`, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/BigInt/asUintN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.asUintN() The **`BigInt.asUintN`** static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer. ## Syntax ```js BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive. - `bigint` - : The BigInt value to clamp to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - [`RangeError`](../../globals/RangeError/RangeError.mdx) - : Thrown if `bits` is negative or greater than 253 - 1. ## Description The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`: ```plain 25n = 00011001 (base 2) ^==== Clamp to four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as [`Number.prototype.toExponential()`](../Number/prototype/toExponential.mdx), `asUintN` is a static property of `BigInt`, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/BigInt/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given BigInt. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format()` method. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/BigInt/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.toString() The **`toString()`** method returns a string representing the specified `BigInt` value. The trailing "n" is not part of the string. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified `BigInt` value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `BigInt` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `BigInt` values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/BigInt/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `BigInt` object. ## Syntax ```js bigIntObj.valueOf() ``` ### Return value A BigInt representing the primitive value of the specified `BigInt` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/BigInt64Array/BigInt64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigInt64Array() The **`BigInt64Array()`** typed array constructor creates a new `BigInt64Array` object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigInt64Array() new BigInt64Array(length) new BigInt64Array(typedArray) new BigInt64Array(object) new BigInt64Array(buffer) new BigInt64Array(buffer, byteOffset) new BigInt64Array(buffer, byteOffset, length) ``` > **Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/BigUint64Array/BigUint64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # BigUint64Array() The **`BigUint64Array()`** typed array constructor creates a new `BigUint64Array` object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../DataView/DataView.mdx) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ## Syntax ```js new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](..//TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Blob/Blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob() The **`Blob()`** constructor creates a `Blob` object, which represents a file-like object of immutable, raw data. ## Syntax ```js new Blob() new Blob(array) new Blob(array, options) ``` > **Note:** `Blob()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `array` _**optional**_ - : An array of values to include in the `Blob`. These can be [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx), [`Blob`](../../globals/Blob/Blob.mdx), or strings. If any of these elements is a [`Blob`](../../globals/Blob/Blob.mdx), its content (and not the object itself) is copied into the Blob being constructed. - `options` _**optional**_ - : An object containing optional attributes for the `Blob`. - `type` - : A string indicating the MIME type of the data. The default value is the empty string `""`. - `endings` - : A string indicating how to handle line endings in the data. This can be either `"transparent"` (default) to keep line endings unchanged, or `"native"` to convert line endings to the platform's native line endings (e.g., `\r\n` on Windows). ### Return value A new `Blob` object containing the specified data. ## Description `Blob` objects represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting its functionality and expanding it to support files on the user's system. To construct a `Blob` from other non-blob objects and data, use the `Blob()` constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](../../globals/Blob/prototype/slice.mdx) method. The `type` property of a `Blob` object will match the MIME type specified in the constructor's `options` parameter, defaulting to an empty string if not specified. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Blob/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.arrayBuffer() The **`arrayBuffer()`** method of the `Blob` interface returns a `Promise` that resolves with an `ArrayBuffer` containing the entire contents of the `Blob` as binary data. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A `Promise` that resolves with an `ArrayBuffer` containing the blob's data. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Blob/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.size The **`size`** read-only property of the `Blob` interface returns the size of the `Blob` in bytes. ## Value A number representing the size of the `Blob` in bytes. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Blob/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.slice() The **`slice()`** method of the `Blob` interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. ## Syntax ```js slice() slice(start) slice(start, end) slice(start, end, contentType) ``` ### Parameters - `start` _**optional**_ - : The 0-based index of the first byte to include in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is 0. - `end` _**optional**_ - : The 0-based index of the first byte that will not be included in the new `Blob`. If negative, it refers to an index from the end of the `Blob`. The default value is `size`. - `contentType` _**optional**_ - : A string indicating the content type to assign to the new `Blob`. The default value is an empty string. ### Return value A new `Blob` object containing the specified subset of data. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Blob/prototype/stream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.stream() The **`stream()`** method of the `Blob` interface returns a `ReadableStream` that can be used to read the contents of the `Blob`. ## Syntax ```js stream() ``` ### Parameters None. ### Return value A `ReadableStream` that provides the data contained within the `Blob`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Blob/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.text() The **`text()`** method of the `Blob` interface returns a `Promise` that resolves with a string containing the contents of the blob, interpreted as UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a string containing the blob's data as a text string. The data is always interpreted as UTF-8. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Blob/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Blob.type The **`type`** read-only property of the `Blob` interface returns the MIME type of the `Blob`. ## Value A string indicating the MIME type of the `Blob`. If the type cannot be determined, this returns an empty string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Boolean/Boolean.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean() The **`Boolean()`** constructor can create `Boolean` objects or return primitive values of type boolean. ## Syntax ```js new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with `new`), it creates a `Boolean` object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), `false`, [`NaN`](../NaN.mdx), [`undefined`](../undefined.mdx), or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](https://developer.mozilla.org/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Boolean/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.toString() The **`toString()`** method returns a string representing the specified boolean value. ## Syntax ```js toString() ``` ### Return value A string representing the specified boolean value. ## Description The `Boolean` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../Object/prototype/toString.mdx). For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Boolean/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Boolean.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Boolean` object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the given `Boolean` object. ## Description The `valueOf()` method of `Boolean` returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy() The **`ByteLengthQueuingStrategy()`** constructor creates and returns a `ByteLengthQueuingStrategy` object instance. ## Syntax ```js new ByteLengthQueuingStrategy(highWaterMark) ``` ### Parameters An object with the following property: - `highWaterMark` - : The total number of bytes that can be contained in the internal queue before backpressure is applied. Unlike `CountQueuingStrategy()` where the `highWaterMark` parameter specifies a simple count of the number of chunks, with `ByteLengthQueuingStrategy()`, the `highWaterMark` parameter specifies a number of _bytes_ — specifically, given a stream of chunks, how many bytes worth of those chunks (rather than a count of how many of those chunks) can be contained in the internal queue before backpressure is applied. ### Return value An instance of the `ByteLengthQueuingStrategy` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ByteLengthQueuingStrategy/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ByteLengthQueuingStrategy.size() The **`size()`** method of the `ByteLengthQueuingStrategy` interface returns the given chunk's `byteLength` property. ## Syntax ```js size(chunk) ``` ### Parameters - `chunk` - : A chunk of data being passed through the stream. ### Return value An integer representing the byte length of the given chunk. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/CompressionStream/CompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream() The **`CompressionStream()`** constructor creates a new `CompressionStream` object which compresses a stream of data. ## Syntax ```js new CompressionStream(format) ``` ### Parameters - `format` - : One of the following allowed compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/CompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.readable The **`readable`** read-only property of the `CompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/CompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CompressionStream.writable The **`writable`** read-only property of the `CompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/CryptoKey/CryptoKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # CryptoKey The **`CryptoKey`** interface represents a cryptographic key obtained from one of the [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) method [`importKey()`](../SubtleCrypto/prototype/importKey.mdx). ## Instance properties - [`type`](./prototype/type.mdx) _**readonly**_ - : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`. - [`extractable`](./prototype/extractable.mdx) _**readonly**_ - : A boolean value indicating whether or not the key may be extracted. - [`algorithm`](./prototype/algorithm.mdx) _**readonly**_ - : An object describing the algorithm for which this key can be used and any associated extra parameters. - [`usages`](./prototype/usages.mdx) _**readonly**_ - : An `Array` of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/CryptoKey/prototype/algorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # algorithm The read-only **`algorithm`** property of the [`CryptoKey`](../CryptoKey.mdx) interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. The object returned depends of the algorithm used to generate the key. ## Value An object matching: - [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) if the algorithm is any of the RSA variants. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/CryptoKey/prototype/extractable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # extractable The read-only **`extractable`** property indicates whether or not the key may be extracted. If the key cannot be exported, an exception will be thrown if an attempt to extract the key is made. ## Value A boolean value that is `true` if the key can be exported and `false` if not. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/CryptoKey/prototype/type.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # type The read-only **`type`** property indicates which kind of key is represented by the object. It can have the following values: - `"secret"`: This key is a secret key for use with a symmetric algorithm. - `"private"`: This key is the private half of an asymmetric algorithm's key pair. - `"public"`: This key is the public half of an asymmetric algorithm's key pair. ## Value One of the following strings: `"secret"`, `"private"`, or `"public"`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/CryptoKey/prototype/usages.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # usages The read-only **`usages`** property indicates what can be done with the key. ## Value An `Array` of strings from the following list: - `"encrypt"`: The key may be used to encrypt messages. - `"decrypt"`: The key may be used to decrypt messages. - `"sign"`: The key may be used to sign messages. - `"verify"`: The key may be used to verify signatures. - `"deriveKey"`: The key may be used in deriving a new key. - `"deriveBits"`: The key may be used in deriving bits. - `"wrapKey"`: The key may be used to wrap a key. - `"unwrapKey"`: The key may be used to unwrap a key. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DOMException/DOMException.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException() The **`DOMException()`** constructor returns a `DOMException` object with a specified message and name. ## Syntax ```js new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` _optional_ - : A description of the exception. If not present, the empty string `''` is used. - `name` _optional_ - : A string. If the specified name is a [standard error name](#error-names), then getting the [`code`](./code.mdx) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created `DOMException` object. ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong `Document`. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` *deprecated* - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript `TypeError` exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DOMException/code.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.code The **`code`** read-only property of the `DOMException` interface returns one of the legacy [error code constants](./DOMException.mdx#error-names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the [`name`](./name.mdx) attribute. ## Value One of the [error code constants](./DOMException.mdx#error-names), or `0` if none match. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DOMException/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.message The **`message`** read-only property of the `DOMException` interface returns a string representing a message or description associated with the given [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DOMException/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DOMException.prototype.name The **`name`** read-only property of the `DOMException` interface returns a string that contains one of the strings associated with an [error name](./DOMException.mdx#error-names). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/DataView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView() The **`DataView()`** constructor is used to create `DataView` objects. ## Syntax ```js new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) ``` > **Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `buffer` - : An existing `ArrayBuffer` to use as the storage backing the new `DataView` object. - `byteOffset` _**optional**_ - : The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. - `byteLength` _**optional**_ - : The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. ### Return value A new `DataView` object representing the specified data buffer. ### Exceptions - [`RangeError`](../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. For example, if the buffer is 16 bytes long, the `byteOffset` is 8, and the `byteLength` is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/buffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.buffer The **`buffer`** accessor property represents the `ArrayBuffer` referenced by the `DataView` at construction time. ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/byteLength.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteLength The **`byteLength`** accessor property represents the length (in bytes) of the dataview. ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/byteOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.byteOffset The **`byteOffset`** accessor property represents the offset (in bytes) of this view from the start of its `ArrayBuffer`. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/getBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigInt64() The **`getBigInt64()`** method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigInt64(byteOffset) getBigInt64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/getBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getBigUint64() The **`getBigUint64()`** method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getBigUint64(byteOffset) getBigUint64(byteOffset, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to read the data from. - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read. ### Return value A `BigInt`. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/getFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat32() The **`getFloat32()`** method gets a signed 32-bit float (float) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat32(byteOffset) getFloat32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/getFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getFloat64() The **`getFloat64()`** method gets a signed 64-bit float (double) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getFloat64(byteOffset) getFloat64(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 64-bit float number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/getInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt16() The **`getInt16()`** method gets a signed 16-bit integer (short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt16(byteOffset) getInt16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/getInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt32() The **`getInt32()`** method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt32(byteOffset) getInt32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in bytes, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value A signed 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/getInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getInt8() The **`getInt8()`** method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getInt8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value A signed 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/getUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint16() The **`getUint16()`** method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint16(byteOffset) getUint16(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 16-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/getUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint32() The **`getUint32()`** method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint32(byteOffset) getUint32(byteOffset, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read. ### Return value An unsigned 32-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/getUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.getUint8() The **`getUint8()`** method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js getUint8(byteOffset) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to read the data. ### Return value An unsigned 8-bit integer number. ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would read beyond the end of the view. ## Description There is no alignment constraint; multi-byte values may be fetched from any offset. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/setBigInt64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigInt64() The **`setBigInt64()`** method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigInt64(byteOffset, value) setBigInt64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in a signed 64-bit integer is `2n ** (64n -1n) - 1n` (`9223372036854775807n`). Upon overflow, it will be negative (`-9223372036854775808n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/setBigUint64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setBigUint64() The **`setBigUint64()`** method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setBigUint64(byteOffset, value) setBigUint64(byteOffset, value, littleEndian) ``` ### Parameters - byteOffset - : The offset, in bytes, from the start of the view to store the data from. - value - : The value to set as a `BigInt`. The highest possible value that fits in an unsigned 64-bit integer is `2n ** 64n - 1n` (`18446744073709551615n`). Upon overflow, it will be zero (`0n`). - littleEndian - : _**optional**_ Indicates whether the 64-bit int is stored in [little- or big-endian](https://developer.mozilla.org/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such that it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/setFloat32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat32() The **`setFloat32()`** method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat32(byteOffset, value) setFloat32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/setFloat64.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setFloat64() The **`setFloat64()`** method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setFloat64(byteOffset, value) setFloat64(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 64-bit float is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/setInt16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt16() The **`setInt16()`** method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt16(byteOffset, value) setInt16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/setInt32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt32() The **`setInt32()`** method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt32(byteOffset, value) setInt32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/setInt8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setInt8() The **`setInt8()`** method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setInt8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/setUint16.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint16() The **`setUint16()`** method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint16(byteOffset, value) setUint16(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 16-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/setUint32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint32() The **`setUint32()`** method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint32(byteOffset, value) setUint32(byteOffset, value, littleEndian) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. - `littleEndian` - : _**optional**_ Indicates whether the 32-bit int is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DataView/prototype/setUint8.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DataView.prototype.setUint8() The **`setUint8()`** method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the [`DataView`](../../../globals/DataView/DataView.mdx). ## Syntax ```js setUint8(byteOffset, value) ``` ### Parameters - `byteOffset` - : The offset, in byte, from the start of the view where to store the data. - `value` - : The value to set. ### Return value [`undefined`](../../../globals/undefined.mdx). ### Errors thrown - [`RangeError`](../../RangeError/RangeError.mdx) - : Thrown if the `byteOffset` is set such as it would store beyond the end of the view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/Date.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date() The **`Date()`** constructor can create a `Date` instance or return a string representing the current time. ## Syntax ```js new Date() new Date(value) new Date(dateString) new Date(dateObject) new Date(year, monthIndex) new Date(year, monthIndex, day) new Date(year, monthIndex, day, hours) new Date(year, monthIndex, day, hours, minutes) new Date(year, monthIndex, day, hours, minutes, seconds) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) Date() ``` > **Note:** `Date()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters There are five basic forms for the `Date()` constructor: #### No parameters When no parameters are provided, the newly-created `Date` object represents the current date and time as of the time of instantiation. #### Time value or timestamp number - `value` - : An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most [UNIX Timestamp](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16) functions are only accurate to the nearest second. #### Date string - `dateString` - : A string value representing a date, in a format recognized by the [`Date.parse()`](./parse.mdx) method. (The ECMA262 spec specifies a [simplified version of ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format), but other formats can be implementation-defined, which commonly include [IETF-compliant RFC 2822 timestamps](https://datatracker.ietf.org/doc/html/rfc2822#page-14).) > **Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the ISO 8601 format (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822) format strings is by convention only. A library can help if many different formats are to be accommodated. > > Date-only strings (e.g. `"1970-01-01"`) are treated as UTC, while date-time strings (e.g. `"1970-01-01T12:00"`) are treated as local. You are therefore also advised to make sure the input format is consistent between the two types. #### Date object - `dateObject` - : An existing `Date` object. This effectively makes a copy of the existing `Date` object with the same date and time. This is equivalent to `new Date(dateObject.valueOf())`, except the `valueOf()` method is not called. When one parameter is passed to the `Date()` constructor, `Date` instances are specially treated. All other values are [converted to primitives](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion). If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp. #### Individual date and time component values Given at least a year and month, this form of `Date()` returns a `Date` object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (`1` for `day` and `0` for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. If any parameter overflows its defined bounds, it "carries over". For example, if a `monthIndex` greater than `11` is passed in, those months will cause the year to increment; if a `minutes` greater than `59` is passed in, `hours` will increment accordingly, etc. Therefore, `new Date(1990, 12, 1)` will return January 1st, 1991; `new Date(2020, 5, 19, 25, 65)` will return 2:05 A.M. June 20th, 2020. Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, `new Date(2020, 5, 0)` will return May 31st, 2020. - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` - : Integer value representing the month, beginning with `0` for January to `11` for December. - `day` _**optional**_ - : Integer value representing the day of the month. The default is `1`. - `hours` _**optional**_ - : Integer value between `0` and `23` representing the hour of the day. Defaults to `0`. - `minutes` _**optional**_ - : Integer value representing the minute segment of a time. The default is `0` minutes past the hour. - `seconds` _**optional**_ - : Integer value representing the second segment of a time. The default is `0` seconds past the minute. - `milliseconds` _**optional**_ - : Integer value representing the millisecond segment of a time. The default is `0` milliseconds past the second. ### Return value Calling `new Date()` (the `Date()` constructor) returns a [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than `-8,640,000,000,000,000` or greater than `8,640,000,000,000,000` milliseconds, it returns a `Date` object whose [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) method returns the literal string `Invalid Date`. Calling the `Date()` function (without the `new` keyword) returns a string representation of the current date and time, exactly as `new Date().toString()` does. Any arguments given in a `Date()` function call (without the `new` keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/UTC.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.UTC() The **`Date.UTC()`** method accepts parameters similar to the `Date` constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js Date.UTC(year) Date.UTC(year, monthIndex) Date.UTC(year, monthIndex, day) Date.UTC(year, monthIndex, day, hour) Date.UTC(year, monthIndex, day, hour, minute) Date.UTC(year, monthIndex, day, hour, minute, second) Date.UTC(year, monthIndex, day, hour, minute, second, millisecond) ``` - `year` - : Integer value representing the year. Values from `0` to `99` map to the years `1900` to `1999`. All other values are the actual year. See the [example](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). - `monthIndex` _**optional**_ - : An integer between `0` (January) and `11` (December) representing the month. Since ECMAScript 2017 it defaults to `0` if omitted. _(Up until ECMAScript 2016, `monthIndex` was a required parameter. As of ES2017, it no longer is.)_ - `day` _**optional**_ - : An integer between `1` and `31` representing the day of the month. If omitted, defaults to `1`. - `hour` _**optional**_ - : An integer between `0` and `23` representing the hours. If omitted, defaults to `0`. - `minute` _**optional**_ - : An integer between `0` and `59` representing the minutes. If omitted, defaults to `0`. - `second` _**optional**_ - : An integer between `0` and `59` representing the seconds. If omitted, defaults to `0`. - `millisecond` _**optional**_ - : An integer between `0` and `999` representing the milliseconds. If omitted, defaults to `0`. ### Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ## Description `UTC()` takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between `0` and `99` are converted to a year in the 20th century `(1900 + year)`. For example, `95` is converted to the year `1995`. The `UTC()` method differs from the `Date` constructor in two ways: 1. `Date.UTC()` uses universal time instead of the local time. 2. `Date.UTC()` returns a time value as a number instead of creating a `Date` object. If a parameter is outside of the expected range, the `UTC()` method updates the other parameters to accommodate the value. For example, if `15` is used for `monthIndex`, the year will be incremented by 1 `(year + 1)` and `3` will be used for the month. `UTC()` is a static method of `Date`, so it's called as `Date.UTC()` rather than as a method of a `Date` instance. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.now() The static **`Date.now()`** method returns the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ## Syntax ```js Date.now() ``` ### Return value A number representing the number of milliseconds elapsed since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.parse() The **`Date.parse()`** method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated. ## Syntax ```js Date.parse(dateString) ``` ### Parameters - `dateString` - : A string representing [a simplification of the ISO 8601 calendar date extended format](#date-time-string-format). (Other formats may be used, but results are implementation-dependent.) ### Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, [`NaN`](../NaN.mdx) is returned. ## Description The `parse()` method takes a date string (such as `"2011-10-10T14:48:00"`) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the [`setTime()`](./prototype/setTime.mdx) method and the `Date` object. ### Date Time String Format The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format. (See the section [Date Time String Format](https://tc39.es/ecma262/#sec-date-time-string-format) in the ECMAScript specification for more details.) For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or `NaN`. Because `parse()` is a static method of `Date`, it is called as `Date.parse()` rather than as a method of a `Date` instance. ### Fall-back to implementation-specific date formats > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause `Date.parse()` to return [`NaN`](../NaN.mdx). However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in [`NaN`](../NaN.mdx), depending on the browser and values provided, e.g.: ```js // Non-ISO string with invalid date values new Date("23/25/2014"); ``` will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return [`NaN`](../NaN.mdx): ```js // ISO string with invalid values new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey's implementation-specific heuristic can be found in [`jsdate.cpp`](https://searchfox.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). The string `"10 06 2014"` is an example of a non-conforming ISO format and thus falls back to a custom routine. See also this [rough outline](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) on how the parsing works. ```js new Date("10 06 2014"); ``` will be treated as a local date of 6 October, 2014, and not 10 June, 2014. Other examples: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### Differences in assumed time zone > **Note:** This section contains implementation-specific behavior that can be inconsistent > across implementations. Given a non-standard date string of `"March 7, 2014"`, `parse()` assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as `"2014-03-07"`, it will assume a time zone of UTC. Therefore `Date` objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype\[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a `Date` object to a primitive value. ## Syntax ```js Date()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the given `Date` object. Depending on the argument, the method can return either a string or a number. ## Description The `[Symbol.toPrimitive]()` method of the `Date` object returns a primitive value, that is either of type number or of type string. If `hint` is `string` or `default`, `[Symbol.toPrimitive]()` tries to call the [`toString`](../../Object/prototype/toString.mdx) method. If the `toString` property does not exist, it tries to call the [`valueOf`](../../Object/prototype/valueOf.mdx) method and if the `valueOf` does not exist either, `[Symbol.toPrimitive]()` throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). If `hint` is `number`, `[Symbol.toPrimitive]()` first tries to call `valueOf`, and if that fails, it calls `toString`. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDate() The **`getDate()`** method returns the day of the month for the specified date according to local time. ## Syntax ```js getDate() ``` ### Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getDay() The **`getDay()`** method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see [`Date.prototype.getDate()`](./getDate.mdx). ## Syntax ```js getDay() ``` ### Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getFullYear() The **`getFullYear()`** method returns the year of the specified date according to local time. Use this method instead of the [`Date.prototype.getYear()`](./getYear.mdx) method. ## Syntax ```js getFullYear() ``` ### Return value A number corresponding to the year of the given date, according to local time. ## Description The value returned by `getFullYear()` is an absolute number. For dates between the years 1000 and 9999, `getFullYear()` returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000\. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getHours() The **`getHours()`** method returns the hour for the specified date, according to local time. ## Syntax ```js getHours() ``` ### Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMilliseconds() The **`getMilliseconds()`** method returns the milliseconds in the specified date according to local time. ## Syntax ```js getMilliseconds() ``` ### Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMinutes() The **`getMinutes()`** method returns the minutes in the specified date according to local time. ## Syntax ```js getMinutes() ``` ### Return value An integer number, between 0 and 59, representing the minutes in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getMonth() The **`getMonth()`** method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getMonth() ``` ### Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getSeconds() The **`getSeconds()`** method returns the seconds in the specified date according to local time. ## Syntax ```js getSeconds() ``` ### Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTime() The **`getTime()`** method returns the number of milliseconds since the [epoch](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#the_ecmascript_epoch_and_timestamps), which is defined as the midnight at the beginning of January 1, 1970, UTC. You can use this method to help assign a date and time to another `Date` object. This method is functionally equivalent to the [`Date.prototype.valueOf()`](./valueOf.mdx) method. ## Syntax ```js getTime() ``` ### Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. ## Description To offer protection against timing attacks and fingerprinting, the precision of `new Date().getTime()` might get rounded depending on browser settings. ```js // reduced time precision (2ms) in Firefox 60 new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // reduced time precision with `privacy.resistFingerprinting` enabled new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getTimezoneOffset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getTimezoneOffset() The **`getTimezoneOffset()`** method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone. ## Syntax ```js getTimezoneOffset() ``` ### Return value The difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. ## Description `date.getTimezoneOffset()` returns the difference, in minutes, between `date` as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in. ### Negative values and positive values The number of minutes returned by `getTimezoneOffset()` is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, `-600` will be returned. | Current time zone | Return value | | ----------------- | ------------ | | UTC-8 | 480 | | UTC | 0 | | UTC+3 | -180 | ### Varied results in Daylight Saving Time (DST) regions In a region that annually shifts in and out of Daylight Saving Time (DST), as `date` varies, the number of minutes returned by calling `getTimezoneOffset()` can be non-uniform. > **Note:** `getTimezoneOffset()`'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of `date` affects the result. In most implementations, the [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) (tzdata) is used to precisely determine the offset of the local timezone at the moment of the `date`. However, if such information is unavailable, an implementation may return zero. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDate() The **`getUTCDate()`** method returns the day of the month (from 1 to 31) in the specified date according to universal time. ## Syntax ```js getUTCDate() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number ranging from 1 to 31 representing day of month for the given date, according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getUTCDay.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCDay() The **`getUTCDay()`** method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. ## Syntax ```js getUTCDay() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCFullYear() The **`getUTCFullYear()`** method returns the year in the specified date according to universal time. ## Syntax ```js getUTCFullYear() ``` ### Return value A number. If the `Date` object represents a valid date, an integer representing the year in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ## Description The value returned by `getUTCFullYear()` is an absolute number that is compliant with year-2000, for example, 1995. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCHours() The **`getUTCHours()`** method returns the hours in the specified date according to universal time. ## Syntax ```js getUTCHours() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 23, representing the hours in the given date according to Coordinated Universal Time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMilliseconds() The **`getUTCMilliseconds()`** method returns the milliseconds portion of the time object's value according to universal time. ## Syntax ```js getUTCMilliseconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 999, representing the milliseconds portion of the given `Date` object according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. Not to be confused with Unix epoch time. To get the total milliseconds since 1970/01/01, use the [`getTime()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMinutes() The **`getUTCMinutes()`** method returns the minutes in the specified date according to universal time. ## Syntax ```js getUTCMinutes() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the minutes in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCMonth() The **`getUTCMonth()`** returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). ## Syntax ```js getUTCMonth() ``` ### Return value A number. If the `Date` object represents a valid date, an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getUTCSeconds() The **`getUTCSeconds()`** method returns the seconds in the specified date according to universal time. ## Syntax ```js getUTCSeconds() ``` ### Return value A number. If the `Date` object represents a valid date, an integer between 0 and 59, representing the seconds in the given date according to universal time. Otherwise, [`NaN`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN) if the `Date` object doesn't represent a valid date. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/getYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.getYear() The **`getYear()`** method returns the year in the specified date according to local time. Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the [`Date.prototype.getFullYear()`](./getFullYear.mdx) method. ## Syntax ```js getYear() ``` ### Return value A number representing the year of the given date, according to local time, minus 1900. ## Description - For years greater than or equal to 2000, the value returned by `getYear()` is 100 or greater. For example, if the year is 2026, `getYear()` returns 126. - For years between and including 1900 and 1999, the value returned by `getYear()` is between 0 and 99. For example, if the year is 1976, `getYear()` returns 76. - For years less than 1900, the value returned by `getYear()` is less than 0. For example, if the year is 1800, `getYear()` returns -100. To take into account years before and after 2000, you should use [`Date.prototype.getFullYear()`](./getFullYear.mdx) instead of `getYear()` so that the year is specified in full. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setDate() The **`setDate()`** method changes the day of the month of a given `Date` instance, based on local time. To instead change the day of the month for a given `Date` instance based on UTC time, use the [`Date.prototype.setUTCDate()`](./setUTCDate.mdx) method. ## Syntax ```js setDate(dayValue) ``` ### Parameters - `dayValue` - : An integer representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the `Date` object is also changed in place). ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setFullYear() The **`setFullYear()`** method sets the full year for a specified date according to local time. Returns new timestamp. ## Syntax ```js setFullYear(yearValue) setFullYear(yearValue, monthValue) setFullYear(yearValue, monthValue, dateValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dateValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dateValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dateValue` parameters, the values returned from the [`Date.prototype.getMonth()`](./getMonth.mdx) and [`Date.prototype.getDate()`](./getDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setHours() The **`setHours()`** method sets the hours for a specified date according to local time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. - `minutesValue` - : Optional. Ideally, an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the datetime will be incremented by the extra minutes. - `secondsValue` - : Optional. Ideally, an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the datetime will be incremented by the extra seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. Ideally, a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getMinutes()`](./getMinutes.mdx), [`Date.prototype.getSeconds()`](./getSeconds.mdx), and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMilliseconds() The **`setMilliseconds()`** method sets the milliseconds for a specified date according to local time. ## Syntax ```js setMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you specify a number outside the expected range, the date information in the `Date` object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMonth() The **`setMonth()`** method sets the month for a specified date according to the currently set year. ## Syntax ```js setMonth(monthValue) setMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getDate()`](./getDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setSeconds() The **`setSeconds()`** method sets the seconds for a specified date according to local time. ## Syntax ```js setSeconds(secondsValue) setSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` _**optional**_ - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setTime.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setTime() The **`setTime()`** method sets the `Date` object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. ## Syntax ```js setTime(timeValue) ``` ### Parameters - `timeValue` - : An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). ## Description Use the `setTime()` method to help assign a date and time to another `Date` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setUTCDate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCDate() The **`setUTCDate()`** method changes the day of the month of a given `Date` instance, based on UTC time. To instead change the day of the month for a given `Date` instance based on local time, use the [`Date.prototype.setDate()`](././setDate.mdx) method. ## Syntax ```js setUTCDate(dayValue) ``` ### Parameters - `dayValue` - : An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If the `dayValue` is outside of the range of date values for the month, `setDate()` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month. If you use 40 for `dayValue`, and the month stored in the `Date` object is June, the day will be changed to 10 and the month will be incremented to July. If a negative number is provided for `dayValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setUTCFullYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCFullYear() The **`setUTCFullYear()`** method sets the full year for a specified date according to universal time. ## Syntax ```js setUTCFullYear(yearValue) setUTCFullYear(yearValue, monthValue) setUTCFullYear(yearValue, monthValue, dayValue) ``` ### Parameters - `yearValue` - : An integer specifying the numeric value of the year, for example, 1995. - `monthValue` - : Optional. An integer between 0 and 11 representing the months January through December. - `dayValue` - : Optional. An integer between 1 and 31 representing the day of the month. If you specify the `dayValue` parameter, you must also specify the `monthValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `monthValue` and `dayValue` parameters, the values returned from the [`Date.prototype.getUTCMonth()`](./getUTCMonth.mdx) and [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCFullYear()` attempts to update the other parameters and the date information in the `Date` object accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1 (`yearValue + 1`), and 3 is used for the month. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setUTCHours.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCHours() The **`setUTCHours()`** method sets the hour for a specified date according to universal time, and returns the number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date` instance. ## Syntax ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### Parameters - `hoursValue` - : An integer between 0 and 23, representing the hour. - `minutesValue` - : Optional. An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `minutesValue`, `secondsValue`, and `msValue` parameters, the values returned from the [`Date.prototype.getUTCMinutes()`](./getUTCMinutes.mdx), [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx), and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCHours()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setUTCMilliseconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMilliseconds() The **`setUTCMilliseconds()`** method sets the milliseconds for a specified date according to universal time. ## Syntax ```js setUTCMilliseconds(millisecondsValue) ``` ### Parameters - `millisecondsValue` - : A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If a parameter you specify is outside of the expected range, `setUTCMilliseconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 1100 for `millisecondsValue`, the seconds stored in the `Date` object will be incremented by 1, and 100 will be used for milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setUTCMinutes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMinutes() The **`setUTCMinutes()`** method sets the minutes for a specified date according to universal time. ## Syntax ```js setUTCMinutes(minutesValue) setUTCMinutes(minutesValue, secondsValue) setUTCMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getUTCSeconds()`](./getUTCSeconds.mdx) and [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setUTCMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setUTCMonth.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCMonth() The **`setUTCMonth()`** method sets the month for a specified date according to universal time. ## Syntax ```js setUTCMonth(monthValue) setUTCMonth(monthValue, dayValue) ``` ### Parameters - `monthValue` - : An integer between 0 and 11, representing the months January through December. - `dayValue` - : Optional. An integer from 1 to 31, representing the day of the month. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `dayValue` parameter, the value returned from the [`Date.prototype.getUTCDate()`](./getUTCDate.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCMonth()` attempts to update the date information in the `Date` object accordingly. For example, if you use 15 for `monthValue`, the year will be incremented by 1, and 3 will be used for month. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setUTCSeconds.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setUTCSeconds() The **`setUTCSeconds()`** method sets the seconds for a specified date according to universal time. ## Syntax ```js setUTCSeconds(secondsValue) setUTCSeconds(secondsValue, msValue) ``` ### Parameters - `secondsValue` - : An integer between 0 and 59, representing the seconds. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `msValue` parameter, the value returned from the [`Date.prototype.getUTCMilliseconds()`](./getUTCMilliseconds.mdx) method is used. If a parameter you specify is outside of the expected range, `setUTCSeconds()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes stored in the `Date` object will be incremented by 1, and 40 will be used for seconds. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/setYear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setYear() The legacy **`setYear()`** method sets the year for a specified date according to local time. However, the way the legacy `setYear()` method sets year values is different from how the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method sets year values — and in some cases, also different from how `new Date()` and [`Date.parse()`](../parse.mdx) set year values. Specifically, given two-digit numbers, such as `22` and `61`: - `setYear()` interprets any two-digit number as an offset to `1900`; so `date.setYear(22)` results in the year value being set to `1922`, and `date.setYear(61)` results in the year value being set to `1961`. (In contrast, while `new Date(61, 1)` also results in the year value being set to `1961`, `new Date("2/1/22")` results in the year value being set to `2022`; and similarly for [`Date.parse()`](../parse.mdx)). - [`Date.prototype.setFullYear()`](./setFullYear.mdx) does no special interpretation but instead uses the literal two-digit value as-is to set the year; so `date.setFullYear(61)` results in the year value being set to `0061`, and `date.setFullYear(22)` results in the year value being set to `0022`. Because of those differences in behavior, you should no longer use the legacy `setYear()` method, but should instead use the preferred [`Date.prototype.setFullYear()`](./setFullYear.mdx) method. ## Syntax ```js setYear(yearValue) ``` ### Parameters - `yearValue` - : An integer. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If `yearValue` is a number between 0 and 99 (inclusive), then the year for `dateObj` is set to `1900 + yearValue`. Otherwise, the year for `dateObj` is set to `yearValue`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/toDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toDateString() The **`toDateString()`** method returns the date portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toDateString() ``` ### Return value A string representing the date portion of the given `Date` object in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces: 1. First three letters of the week day name 2. First three letters of the month name 3. Two-digit day of the month, padded on the left a zero if necessary 4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign For example: "Thu Jan 01 1970". - If you want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/toISOString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toISOString() The **`toISOString()`** method returns a string in _simplified_ extended ISO format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, respectively). The timezone is always zero UTC offset, as denoted by the suffix `Z`. ## Syntax ```js toISOString() ``` ### Return value A string representing the given date in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format according to universal time. It's the same format as the one required to be recognized by [`Date.parse()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#date-time-string-format). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toJSON() The **`toJSON()`** method returns a string representation of the `Date` object. ## Syntax ```js toJSON() ``` ### Return value A string representation of the given date. ## Description `Date` instances refer to a specific point in time. `toJSON()` calls the object's [`Date.prototype.toISOString()`](./toISOString.mdx) method, which returns a string representing the `Date` object's value. This method is generally intended to, by default, usefully serialize `Date` objects during [JSON](https://developer.mozilla.org/docs/Glossary/JSON) serialization, which can then be deserialized using the [`Date()` constructor](../Date.mdx) or [`Date.parse()`](../parse.mdx) as the reviver of [`JSON.parse()`](../../JSON/parse.mdx). The method first attempts to convert its `this` value [to a primitive](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[Symbol.toPrimitive]()`](../../Symbol/toPrimitive.mdx) (with `"number"` as hint), [`valueOf()`](../../Object/prototype/valueOf.mdx), and [`toString()`](../../Object/prototype/toString.mdx) methods, in that order. If the result is a [non-finite](../../Number/isFinite.mdx) number, `null` is returned. (This generally corresponds to an invalid date, whose [`valueOf()`](./valueOf.mdx) returns [`NaN`](../../NaN.mdx).) Otherwise, if the converted primitive is not a number or is a finite number, the return value of `this.toISOString()` is returned. Note that the method does not check whether the `this` value is a valid `Date` object. However, calling `Date.prototype.toJSON()` on non-`Date` objects does not have well-defined semantics. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/toLocaleDateString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleDateString() The **`toLocaleDateString()`** method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleDateString() toLocaleDateString(locales) toLocaleDateString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. The `timeStyle` option must be undefined, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) would be thrown. If `weekday`, `year`, `month`, and `day` are all undefined, then `year`, `month`, and `day` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the date portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `weekday`, `year`, `month`, `day`, `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `year`, `month`, `day`, `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the given date according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/toLocaleTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toLocaleTimeString() The **`toLocaleTimeString()`** method returns a string with a language-sensitive representation of the time portion of the date. In implementations with [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`. ## Syntax ```js toLocaleTimeString() toLocaleTimeString(locales) toLocaleTimeString(locales, options) ``` ### Parameters The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`. In implementations without `Intl.DateTimeFormat` support, this parameter is ignored. See the [`Intl.DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them. ### Return value A string representing the time portion of the given `Date` instance according to language-specific conventions. In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above. ## Performance When formatting large numbers of dates, it is better to create an [`Intl.DateTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object and use its [`format()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) method. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toString() The **`toString()`** method returns a string representing the specified `Date` object interpreted in the local timezone. ## Syntax ```js toString() ``` ### Return value A string representing the given date. ## Description The `Date` object overrides the `toString()` method of `Object`. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString) and [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString) together, adding a space in between. For example: "Thu Jan 01 1970 04:42:04 GMT+0000 (Coordinated Universal Time)" The `toString()` method is automatically called when a date is coerced to a string, such as `const today = 'Today is ' + new Date()`. `Date.prototype.toString()` must be called on `Date` instances. If the `this` value does not inherit from `Date.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - If you only want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you only want to get the _time_ part, use [`toTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/toTimeString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toTimeString() The **`toTimeString()`** method returns the time portion of a `Date` object interpreted in the local timezone in English. ## Syntax ```js toTimeString() ``` ### Return value A string representing the time portion of the given date in human readable form in English. ## Description `Date` instances refer to a specific point in time. `toTimeString()` interprets the date in the local timezone and formats the _time_ part in English. It always uses the format of `hh:mm:ss GMT±xxxx (TZ)`, where: | Format String | Description | | ------------- | ----------------------------------------------------------------------------------------------------- | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | | `±xxxx` | The local timezone's offset — two digits for hours and two digits for minutes (e.g. `-0500`, `+0800`) | | `TZ` | The timezone's name (e.g. `PDT`, `PST`) | For example: "04:42:04 GMT+0000 (Coordinated Universal Time)". - If you want to get the _date_ part, use [`toDateString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString). - If you want to get both the date and time, use [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toString). - If you want to make the date interpreted as UTC instead of local timezone, use [`toUTCString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). - If you want to format the date in a more user-friendly format (e.g. localization), use [`toLocaleTimeString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/toUTCString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.toUTCString() The **`toUTCString()`** method converts a date to a string, interpreting it in the UTC time zone. `toGMTString()` is an alias of this method. Based on [rfc7231](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.1.1) and modified according to [ECMA-262 toUTCString](https://tc39.es/ecma262/#sec-date.prototype.toutcstring), it can have negative values. ## Syntax ```js toUTCString() ``` ### Return value A string representing the given date using the UTC time zone. ## Description The value returned by `toUTCString()` is a string in the form `Www, dd Mmm yyyy hh:mm:ss GMT`, where: | Format String | Description | | ------------- | ------------------------------------------------------------ | | `Www` | Day of week, as three letters (e.g. `Sun`, `Mon`) | | `dd` | Day of month, as two digits with leading zero if required | | `Mmm` | Month, as three letters (e.g. `Jan`, `Feb`) | | `yyyy` | Year, as four or more digits with leading zeroes if required | | `hh` | Hour, as two digits with leading zero if required | | `mm` | Minute, as two digits with leading zero if required | | `ss` | Seconds, as two digits with leading zero if required | ### Aliasing JavaScript's `Date` API was inspired by Java's `java.util.Date` library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java `Date` class had a method called `toGMTString` — which was poorly named, because the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) is not equivalent to the [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time), while JavaScript dates always operate by UTC time. For web compatibility reasons, `toGMTString` remains as an alias to `toUTCString`, and they refer to the exact same function object. This means: ```js Date.prototype.toGMTString.name === "toUTCString"; ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Date/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `Date` object. ## Syntax ```js valueOf() ``` ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date, or [`NaN`](../../NaN.mdx) in case of an invalid date. ## Description The `valueOf()` method returns the primitive value of a `Date` object as a number data type, the number of milliseconds since midnight 01 January, 1970 UTC. This method is functionally equivalent to the [`Date.prototype.getTime()`](./getTime.mdx) method. This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DecompressionStream/DecompressionStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream() The **`DecompressionStream()`** constructor creates a new `DecompressionStream` object which decompresses a stream of data. ## Syntax ```js new DecompressionStream(format) ``` ### Parameters - `format` - : One of the following compression formats: - `"gzip"` - `"deflate"` - `"deflate-raw"` ## Exceptions - `TypeError` - : Thrown if the format passed to the constructor is not supported. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DecompressionStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.readable The **`readable`** read-only property of the `DecompressionStream` interface returns a `ReadableStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/DecompressionStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # DecompressionStream.writable The **`writable`** read-only property of the `DecompressionStream` interface returns a `WritableStream`. ## Value A `WritableStream` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/EcKeyImportParams/EcKeyImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcKeyImportParams The **`EcKeyImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as ECDSA. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/EcdsaParams/EcdsaParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EcdsaParams The **`EcdsaParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.sign()` or `SubtleCrypto.verify()` when using the ECDSA algorithm. ## Instance properties - `name` - : A string. This should be set to `ECDSA`. - `hash` - : A string. An identifier for the digest algorithm to use. This should be one of the following: - `SHA-256`: selects the SHA-256 algorithm. - `SHA-384`: selects the SHA-384 algorithm. - `SHA-512`: selects the SHA-512 algorithm. > **Warning:** `SHA-1` is also supported here but the SHA-1 algorithm is considered vulnerable and should no longer be used. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Error/Error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error The **`Error()`** constructor creates an error object. ## Syntax ```js new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance. ### Parameters - `message` _**optional**_ - : A human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A value indicating the specific cause of the error, reflected in the [`Error.prototype.cause`](./prototype/cause.mdx) property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Error/prototype/cause.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.cause The **`cause`** data property of an [`Error`](../../../globals/Error/Error.mdx) instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error`](../Error.mdx) constructor in the `options.cause` argument. It may not be present. ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Error/prototype/message.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.message The **`message`** data property of an [`Error`](../Error.mdx) instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error`](../Error.mdx) constructor as the first argument. ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the [`name`](./name.mdx) property is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the [`Error`](../Error.mdx) constructor. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Error/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.name The **`name`** data property of `Error.prototype` is shared by all [`Error`](../Error.mdx) instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like [`TypeError`](../../../globals/TypeError/TypeError.mdx) and [`SyntaxError`](../../SyntaxError/SyntaxError.mdx) provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. ## Description By default, [`Error`](../Error.mdx) instances are given the name "Error". The `name` property, in addition to the [`message`](./message.mdx) property, is used by the [`Error.prototype.toString()`](./toString.mdx) method to create a string representation of the error. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Error/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Error.prototype.toString() The **`toString()`** method returns a string representing the specified [`Error`](../Error.mdx) object. ## Syntax ```js toString() ``` ### Return value A string representing the specified [`Error`](../Error.mdx) object. ## Description The [`Error`](../Error.mdx) object overrides the [`Object.prototype.toString()`](../../Object/prototype/toString.mdx) method inherited by all objects. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/EvalError/EvalError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # EvalError The **`EvalError()`** constructor creates a new `EvalError` instance. ## Syntax ```js new EvalError() new EvalError(message) new EvalError(message, options) new EvalError(message, fileName) new EvalError(message, fileName, lineNumber) EvalError() EvalError(message) EvalError(message, options) EvalError(message, fileName) EvalError(message, fileName, lineNumber) ``` > **Note:** `EvalError()` can be called with or without `new`. Both create a new `EvalError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FetchEvent/FetchEvent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent This is the event type for `fetch` events. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](./prototype/respondWith.mdx) method, which allows us to provide a response to this fetch. ## Instance properties - `FetchEvent.request` _**readonly**_ - : The `Request` that was received by the application. - `FetchEvent.client` _**readonly**_ - : Information about the downstream client that made the request. While these fields are always defined on Compute, they may be *null* when not available in testing environments such as Viceroy. - `FetchEvent.client.requestId` _**readonly**_ - : A UUID generated by Compute for each request. - `FetchEvent.client.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the downstream client. - `FetchEvent.client.geo` _**readonly**_ - : Either `null`, or a [geolocation dictionary](../../fastly:geolocation/getGeolocationForIpAddress.mdx) corresponding to the IP address of the downstream client. - `FetchEvent.client.tlsJA3MD5` _**readonly**_ - : Either `null` or a string representation of the JA3 hash of the TLS ClientHello message. - `FetchEvent.client.tlsCipherOpensslName` _**readonly**_ - : Either `null` or a string representation of the cipher suite used to secure the client TLS connection. - `FetchEvent.client.tlsProtocol` _**readonly**_ - : Either `null` or a string representation of the TLS protocol version used to secure the client TLS connection. - `FetchEvent.client.tlsClientCertificate` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw client certificate in the mutual TLS handshake message. It is in PEM format. Returns an empty ArrayBuffer if this is not mTLS or available. - `FetchEvent.client.tlsClientHello` _**readonly**_ - : Either `null` or an ArrayBuffer containing the raw bytes sent by the client in the TLS ClientHello message. - `FetchEvent.client.tlsJA4` _**readonly**_ - : Either `null` or a string representation of the JA4 fingerprint of the TLS ClientHello message. - `FetchEvent.client.h2Fingerprint` _**readonly**_ - : Either `null` or a string representation of the HTTP/2 fingerprint for HTTP/2 connections. Returns `null` for HTTP/1.1 connections. - `FetchEvent.client.ohFingerprint` _**readonly**_ - : Either `null` or a string representation of the Original Header fingerprint based on the order and presence of request headers. - `FetchEvent.server` _**readonly**_ - : Information about the server receiving the request for the Fastly Compute service. - `FetchEvent.server.address` _**readonly**_ - : A string representation of the IPv4 or IPv6 address of the server which received the request. ## Instance methods - [`FetchEvent.respondWith()`](./prototype/respondWith.mdx) - : Provide (a promise for) a response for this request. - [`FetchEvent.sendEarlyHints()`](./prototype/sendEarlyHints.mdx) - : Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response for this request. - [`FetchEvent.waitUntil()`](./prototype/waitUntil.mdx) - : Extends the lifetime of the event. Used to notify the host environment of tasks that extend beyond the returning of a response, such as streaming and caching. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FetchEvent/prototype/respondWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.respondWith() The **`respondWith()`** method allows you to provide a promise for a [`Response`](../../Response/Response.mdx) to send back to the client which made the incoming request to your application. ## Syntax ```js respondWith(response) ``` ### Parameters - `response` - : A [`Response`](../../Response/Response.mdx) or a [`Promise`](../../Promise/Promise.mdx) that resolves to a [`Response`](../../Response/Response.mdx). Otherwise, a network error is returned to Fetch. ### Return value Always returns `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FetchEvent/prototype/sendEarlyHints.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.sendEarlyHints() The **`sendEarlyHints()`** method allows you to send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) response back to the client which made the incoming request to your application. ## Syntax ```js sendEarlyHints(headers) ``` ### Parameters - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../Headers/Headers.mdx) object or object literal of [`String`](../../String/String.mdx) key/value pairs. ### Return value Always returns `undefined`. ### Examples ```js event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'] ]); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FetchEvent/prototype/waitUntil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FetchEvent.waitUntil() The **`waitUntil()`** method tells the host environment that work is ongoing until the promise settles, and it shouldn't terminate the application if it wants that work to complete. The `waitUntil()` method must be initially called synchronously within the event callback, but after that it can be called multiple times, and will hold the process open until all the promises passed to it settle. ## Syntax ```js waitUntil(promise) ``` ### Parameters A [`Promise`](../../Promise/Promise.mdx). ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FinalizationRegistry/FinalizationRegistry.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry() The **`FinalizationRegistry`** constructor creates a `FinalizationRegistry` object that uses the given callback. ## Syntax ```js // Arrow callback function new FinalizationRegistry((heldValue) => { /* … */ }) // Callback function new FinalizationRegistry(callbackFn) // Inline callback function new FinalizationRegistry(function(heldValue) { /* … */ }) ``` > **Note:** `FinalizationRegistry()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `callback` - : The callback function this registry should use. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FinalizationRegistry/prototype/register.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.register() The `register()` method registers an object with a `FinalizationRegistry` instance so that if the object is garbage-collected, the registry's callback may get called. ## Syntax ```js register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target object to register. - `heldValue` - : The value to pass to the finalizer for this object. This cannot be the `target` object but can be anything else, including functions and primitives. - `unregisterToken` _**optional**_ - : A token that may be used with the `unregister` method later to unregister the target object. If provided (and not `undefined`), this must be an object. If not provided, the target cannot be unregistered. ### Return value `undefined`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when one of the following condition is met: - `target` is not an object (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object ## Description See the [Avoid where possible](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the `FinalizationRegistry` page for important caveats. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FinalizationRegistry/prototype/unregister.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FinalizationRegistry.prototype.unregister() The `unregister()` method unregisters a target object from a `FinalizationRegistry` instance. ## Syntax ```js unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the [`FinalizationRegistry.prototype.register`](./register.mdx) method when registering the target object. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown when `unregisterToken` is not an object. ## Description When a target object has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Float32Array/Float32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float32Array() The **`Float32Array()`** typed array constructor creates a new `Float32Array` object, which is, an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Float64Array/Float64Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Float64Array() The **`Float64Array()`** typed array constructor creates a new `Float64Array` object, which is, an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Float64Array() new Float64Array(length) new Float64Array(typedArray) new Float64Array(object) new Float64Array(buffer) new Float64Array(buffer, byteOffset) new Float64Array(buffer, byteOffset, length) ``` > **Note:** `Float64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/FormData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData() The **`FormData()`** constructor creates a new `FormData` object. ## Syntax ```js new FormData() new FormData(form) ``` > **Note:** `FormData()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. ### Parameters - `form` _**optional**_ - : An HTML `` element — when specified, the `FormData` object will be populated with the form's current key/value pairs using the name property of each element for the keys and their submitted value for the values. File input elements are handled specially: their values are taken from the files selected by the user in the upload control. ### Return value A new `FormData` object, pre-populated with form data if the optional `form` parameter was provided. ## Description The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using methods such as `fetch()`. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also append additional data to the `FormData` object after it's created using its various methods. A `FormData` object can be used in a number of ways with other APIs: 1. It can be sent with the `fetch()` API 2. It works seamlessly with the `Request` and `Response` objects - it can be used directly as the body of a `Request` object 3. It can be obtained from a `Response` object using the `formData()` method 4. It can be passed directly to the `URLSearchParams` constructor The transmitted data is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to `"multipart/form-data"`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.append() The **`append()`** method of the `FormData` interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. ## Syntax ```js append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.delete() The **`delete()`** method of the `FormData` interface removes all key/value pairs with the given name from the `FormData` object. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.entries() The **`entries()`** method of the `FormData` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator yields a new array for each key/value pair, with the first element being the key and the second element being the value. ## Syntax ```js entries() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.forEach() The **`forEach()`** method of the `FormData` interface executes the provided callback function once for each key/value pair in the `FormData` object. ## Syntax ```js forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each entry in the object. The function will be passed the following arguments: - `value` - : The value of the current entry. - `key` - : The key of the current entry. - `formData` - : The `FormData` object being traversed. - `thisArg` _**optional**_ - : A value to use as `this` when executing `callbackFn`. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.get() The **`get()`** method of the `FormData` interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the [`getAll()`](../../../globals/FormData/prototype/getAll.mdx) method instead. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value A `FormDataEntryValue` containing the value. If the key does not exist, it returns `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/prototype/getAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.getAll() The **`getAll()`** method of the `FormData` interface returns all the values associated with a given key from within a `FormData` object. ## Syntax ```js getAll(name) ``` ### Parameters - `name` - : The name of the key you want to retrieve. ### Return value An array of `FormDataEntryValue` items containing all values with the given key. If the key doesn't exist, an empty array is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.has() The **`has()`** method of the `FormData` interface returns a boolean indicating whether a `FormData` object contains a key/value pair with the given name. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the key you want to test for existence. ### Return value `true` if a key/value pair with the specified name exists; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.keys() The **`keys()`** method of the `FormData` interface returns an iterator allowing iteration through all keys contained in this object. The iterator yields the key for each value. ## Syntax ```js keys() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.set() The **`set()`** method of the `FormData` interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and [`append()`](../../../globals/FormData/prototype/append.mdx) is that if the specified key already exists, `set()` overwrites all existing values with the new one, whereas `append()` appends the new value onto the end of the existing values. ## Syntax ```js set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The value of the field. This can be a string or a `Blob` (including subclasses such as `File`). If none of these, the value is converted to a string. - `filename` _**optional**_ - : The filename reported to the server when a `Blob` or `File` is passed as the second parameter. The default filename for `Blob` objects is "blob". The default filename for `File` objects is the file's filename. ### Return value `undefined` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/FormData/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # FormData.values() The **`values()`** method of the `FormData` interface returns an iterator allowing iteration through all values contained in this object. The iterator yields the value for each key/value pair. ## Syntax ```js values() ``` ### Return value An `iterator`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Function/Function.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function() The **`Function()`** constructor creates a new [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function) object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as `eval()`. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. ## Syntax ```js new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) ``` > **Note:** `Function()` can be called with or without `new`. Both create a new `Function` instance. ### Parameters - `argN` _**optional**_ - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](https://developer.mozilla.org/docs/Glossary/Identifier), [rest parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }` ``` This is observable by calling the function's [`toString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function("count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Function/prototype/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.apply() The **`apply()`** method calls the specified function with a given `this` value, and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ## Syntax ```js apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` _**optional**_ - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Function/prototype/bind.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.bind() The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. ## Syntax ```js bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the `new` operator. - `arg1, …, argN` _**optional**_ - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the `new` operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of [`Reflect.construct`](../../../globals/Reflect/construct.mdx)). If the bound function is directly constructed, [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](../../../globals/Function/prototype/) property, it cannot be used as a base class for [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](../../../globals/Function/prototype/length.mdx) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](../../../globals/Function/prototype/name.mdx) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Function/prototype/call.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.call() The **`call()`** method calls the function with a given `this` value and arguments provided individually. ## Syntax ```js call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) will be replaced with the global object, and primitive values will be converted to objects. - `arg1, …, argN` _**optional**_ - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx), except that `call()` accepts an **argument list**, while `apply()` accepts a **single array of arguments** — for example, `func.apply(this, ['eat', 'bananas'])` vs. `func.call(this, 'eat', 'bananas')`. Normally, when calling a function, the value of [`this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without `new`. Use [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) or [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) instead. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Function/prototype/index.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.prototype The **`prototype`** data property of a `Function` instance is used when the function is used as a constructor with the `new` operator. It will become the new object's prototype. > **Note:** Not all `Function` objects have the `prototype` property — see [description](#description). ## Value An object. > **Note:** The `prototype` property of [classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with `new`, the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](https://developer.mozilla.org/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](../../../globals/Symbol/Symbol.mdx) and [`BigInt`](../../../globals/BigInt/BigInt.mdx) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: (`constructor`)[../../../globals/Object/prototype/constructor.mdx), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an `Object`, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Function/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.length The **`length`** data property of a `Function` instance indicates the number of parameters expected by the function. ## Value A number. ## Description A `Function` object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. The `Function` constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Function/prototype/name.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.name The **`name`** property of a `Function` instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. ## Value A string. > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = 'otherFunction'; console.log(someFunction.name); // someFunction ``` To change it, use [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {}; // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {} }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx) produces a function whose name is "bound " plus the function name. ```js function foo() {}; foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [`set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [telling the constructor name of an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#telling_the_constructor_name_of_an_object) for more details. ### Symbol as function name If a `Symbol` is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Function/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Function.prototype.toString() The **`toString()`** method returns a string representing the source code of the specified `Function`. ## Syntax ```js toString() ``` ### Return value A string representing the source code of the function. ## Description The `Function` object overrides the `toString()` method inherited from `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call('foo'); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by [`Function.prototype.bind()`](../../../globals/Function/prototype/bind.mdx), or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```js "function someName() { [native code] }" ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```js "function anonymous(a,b\n) {\nreturn a + b\n}" ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [browser compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#browser_compatibility). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/Headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers() The **`Headers()`** constructor creates a new `Headers` object. ## Syntax ```js new Headers() new Headers(init) ``` ### Parameters - `init` _**optional**_ - : An object containing any HTTP headers that you want to pre-populate your `Headers` object with. This can be a simple object literal with `String` values, an array of name-value pairs, where each pair is a 2-element string array; or an existing `Headers` object. In the last case, the new `Headers` object copies its data from the existing `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.append() The **`append()`** method of the `Headers` interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `Headers.prototype.set()` and `append()` is that if the specified header already exists and accepts multiple values, `set()` will overwrite the existing value with the new one, whereas `append()` will append the new value onto the end of the set of values. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to add to the `Headers` object. - `value` - : The value of the HTTP header you want to add. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.delete() The **`delete()`** method of the `Headers` interface deletes a header from the current `Headers` object. This method throws a `TypeError` for the following reasons: - The value of the name parameter is not the name of an HTTP header. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to delete from the `Headers` object. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.entries() The **`Headers.entries()`** method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are `String` objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.forEach() The **`Headers.forEach()`** method executes a callback function once per each key/value pair in the `Headers` object. ## Syntax ```js // Arrow function forEach((value, key) => { /* … */ }) forEach((value, key, object) => { /* … */ }) // Inline callback function forEach(function (value, key) { /* … */ }) forEach(function (value, key, object) { /* … */ }) forEach(function (value, key) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` - : Value of the currently visited header entry. - `key` - : Name of the currently visited header entry. - `object` - : The Headers object being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value `undefined`. ## Description The `Headers.forEach()` method executes the provided callback once for each key of the Headers which actually exist. It is not invoked for keys which have been deleted. However, it is executed for keys which are present but have the value undefined. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.get() The **`get()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns a byte string of all the values of a header within a `Headers` object with a given name. If the requested header doesn't exist in the `Headers` object, it returns `null`. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the HTTP header whose values you want to retrieve from the `Headers` object. If the given name doesn't match the [field-name](https://httpwg.org/specs/rfc9110.html#fields.names) production in the HTTP specification, this method throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx). The name is case-insensitive. ### Return value A [`String`](../../../globals/String/String.mdx) sequence representing the values of the retrieved header or `null` if this header is not set. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/prototype/getSetCookie.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.getSetCookie() The **`getSetCookie()`** method of the [`Headers`](../../../globals/Headers/Headers.mdx) interface returns an array of all the values of the `Set-Cookie` headers, returning an empty list if none are present. ## Syntax ```js getSetCookie() ``` ### Return value `String[]` representing the list of `Set-Cookie` headers. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.has() The **`has()`** method of the `Headers` interface returns a boolean stating whether a `Headers` object contains a certain header. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a `TypeError`. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.keys() The **`Headers.keys()`** method returns an iterator allowing to go through all keys contained in this object. The keys are `String` objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.set() The **`set()`** method of the `Headers` interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. The difference between `set()` and `Headers.append` is that if the specified header already exists and accepts multiple values, `set()` overwrites the existing value with the new one, whereas `Headers.append` appends the new value to the end of the set of values. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a `TypeError`. - `value` - : The new value you want to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Headers/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Headers.values() The **`Headers.values()`** method returns an iterator allowing to go through all values contained in this object. The values are `String` objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/HmacImportParams/HmacImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # HmacImportParams The **`HmacImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey`, when generating a key for the `HMAC` algorithm. ## Instance properties - `name` - : A string. This should be set to `HMAC`. - `hash` - : A string representing the name of the digest function to use. The can take a value of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`. - `length` _optional_ - : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Infinity.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Infinity The global property **`Infinity`** is a numeric value representing infinity. ## Value The same number value as `Number.POSITIVE_INFINITY`. ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see `Number.POSITIVE_INFINITY` for details. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Int16Array/Int16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int16Array() The **`Int16Array()`** typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int16Array() new Int16Array(length) new Int16Array(typedArray) new Int16Array(object) new Int16Array(buffer) new Int16Array(buffer, byteOffset) new Int16Array(buffer, byteOffset, length) ``` > **Note:** `Int16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Int32Array/Int32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int32Array() The **`Int32Array()`** typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int32Array() new Int32Array(length) new Int32Array(typedArray) new Int32Array(object) new Int32Array(buffer) new Int32Array(buffer, byteOffset) new Int32Array(buffer, byteOffset, length) ``` > **Note:** `Int32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Int8Array/Int8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Int8Array() The **`Int8Array()`** constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/JSON/parse.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.parse() The **`JSON.parse()`** method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned. ## Syntax ```js JSON.parse(text) JSON.parse(text, reviver) ``` ### Parameters - `text` - : The string to parse as JSON. - `reviver` _**optional**_ - : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments: - `key` - : The key associated with the value. - `value` - : The value produced by parsing. ### Return value The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`. ### Exceptions - [`SyntaxError`](../../globals/SyntaxError/SyntaxError.mdx) - : Thrown if the string to parse is not valid JSON. ## Description `JSON.parse()` parses a JSON string according to the [JSON grammar](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see [Object literal syntax vs. JSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json). ### The reviver parameter If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`. The `reviver` is called with the object containing the property being processed as `this`, and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns [`undefined`](../../globals/undefined.mdx) (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object. Similar to the `replacer` parameter of [`JSON.stringify()`](../../globals/JSON/stringify.mdx), `reviver` will be last called on the root object with an empty string as the `key` and the root object as the `value`. For JSON text parsing to primitive values, `reviver` will be called once. Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/JSON/stringify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JSON.stringify() The **`JSON.stringify()`** method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. ## Syntax ```js JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space) ``` ### Parameters - `value` - : The value to convert to a JSON string. - `replacer` _**optional**_ - : A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of `value` that should be included in the output. If `replacer` is an array, all elements that are not strings or numbers (can be either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided), all properties of the object are included in the resulting JSON string. - `space` _**optional**_ - : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or not provided — no white space is used. ### Return value A JSON string representing the given value, or undefined. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following is true: - `value` contains a circular reference. - A `BigInt` value is encountered. ## Description `JSON.stringify()` converts a value to JSON notation representing it: - `Boolean`, `Number`, `String`, and `BigInt` (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via [`Object()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects. - Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkeypatching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user. - [`undefined`](../../globals/undefined.mdx), `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`. - The numbers [`Infinity`](../../globals/Infinity.mdx) and [`NaN`](../../globals/NaN.mdx), as well as the value [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.) - Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored. - For other objects: - All `Symbol`-keyed properties will be completely ignored, even when using the [`replacer`](#the-replacer-parameter) parameter. - If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the-replacer-parameter) function: - if this object is a property value, the property name - if it is in an array, the index in the array, as a string - if `JSON.stringify()` was directly called on this object, an empty string `Date` objects implement the [`toJSON()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings. - Only [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means [Map](../../globals/Map/Map.mdx), [Set](../../globals/Set/Set.mdx), etc. will become `"{}"`. You can use the [`replacer`](#the-replacer-parameter) parameter to serialize them to something more useful. Properties are visited using the same algorithm as [`Object.keys()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable). ### The replacer parameter The `replacer` parameter can be either a function or an array. As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored. As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context. The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means: - If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.) - If you return a `Function`, `Symbol`, or [`undefined`](../../globals/undefined.mdx), the property is not included in the output. - If you return any other object, the object is recursively stringified, calling the `replacer` function on each property. > **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation. Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array. ### The space parameter The `space` parameter may be used to control spacing in the final string. - If it is a number, successive levels in the stringification will each be indented by this many space characters. - If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Map\[Symbol.species] The **`Map[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Map` objects. ## Syntax ```js Map[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Map` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Map` methods. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/Map.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map() The **`Map()` constructor** creates [Map](../../globals/Map/Map.mdx) objects. ## Syntax ```js new Map() new Map(iterable) ``` > **Note:** `Map()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : An `Array` or other [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) object whose elements are key-value pairs. (For example, arrays with two elements, such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the new `Map`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a `Map` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows maps to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the key-value pairs of the map. The initial value of this property is the same function object as the initial value of the [`Map.prototype.entries`](../../../globals/Map/prototype/entries.mdx) property. ## Syntax ```js map[Symbol.iterator]() ``` ### Return value The same return value as [`Map.prototype.entries()`](../../../globals/Map/prototype/entries.mdx): a new iterable iterator object that yields the key-value pairs of the map. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.clear() The **`clear()`** method removes all elements from a `Map` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.delete() The **`delete()`** method removes the specified element from a `Map` object by key. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `Map` object. ### Return value `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.entries() The **`entries()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the `[key, value]` pairs for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so the for-of loop can be used. When the protocol `[Symbol.iterator]` is used, it returns a function that, when invoked, returns this iterator itself. ## Syntax ```js entries() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.forEach() The **`forEach()`** method executes a provided function once per each key/value pair in the `Map` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* … */ } ) forEach((value) => { /* … */ } ) forEach((value, key) => { /* … */ } ) forEach((value, key, map) => { /* … */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* … */ }) forEach(function(value) { /* … */ }) forEach(function(value, key) { /* … */ }) forEach(function(value, key, map) { /* … */ }) forEach(function(value, key, map) { /* … */ }, thisArg) ``` ### Parameters - `callbackFn` - : Function to execute for each entry in the map. It takes the following arguments: - `value` _**optional**_ - : Value of each iteration. - `key` _**optional**_ - : Key of each iteration. - `map` _**optional**_ - : The map being iterated. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach` method executes the provided `callback` once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the entry's `value` - the entry's `key` - the **`Map` object** being traversed If a `thisArg` parameter is provided to `forEach`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach` has finished will be visited. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.get() The **`get()`** method returns a specified element from a `Map` object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the `Map` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : The key of the element to return from the `Map` object. ### Return value The element associated with the specified key, or [`undefined`](../../../globals/undefined.mdx) if the key can't be found in the `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : The key of the element to test for presence in the `Map` object. ### Return value `true` if an element with the specified key exists in the `Map` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.keys() The **`keys()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the keys for each element in the `Map` object in insertion order. In this particular case, this iterator object is also an iterable, so a [for...of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loop can be used. ## Syntax ```js keys() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.set() The **`set()`** method adds or updates an entry in a `Map` object with a specified key and a value. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : The key of the element to add to the `Map` object. The key may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). - `value` - : The value of the element to add to the `Map` object. The value may be any [JavaScript type](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures) (any [primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#objects)). ### Return value The `Map` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.size The **`size`** accessor property returns the number of elements in a [Map](../../../globals/Map/Map.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Map` object has. A set accessor function for `size` is `undefined`; you can not change this property. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Map/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Map.prototype.values() The **`values()`** method returns a new _[iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators)_ object that contains the values for each element in the `Map` object in insertion order. ## Syntax ```js values() ``` ### Return value A new [Map](../../../globals/Map/Map.mdx) iterator object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/E.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.E The **`Math.E`** property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718. ## Value `2.718281828459045` ## Description Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/LN10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN10 The **`Math.LN10`** property represents the natural logarithm of 10, approximately 2.302. ## Value `2.302585092994046` ## Description Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/LN2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LN2 The **`Math.LN2`** property represents the natural logarithm of 2, approximately 0.693: ## Value `0.6931471805599453` ## Description Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/LOG10e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG10E The **`Math.LOG10E`** property represents the base 10 logarithm of [E](./E.mdx), approximately 0.434. ## Value `0.4342944819032518` ## Description Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/LOG2e.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.LOG2E The **`Math.LOG2E`** property represents the base 2 logarithm of [E](./E.mdx), approximately 1.442. ## Value `1.4426950408889634` ## Description Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/PI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.PI The **`Math.PI`** property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159. ## Value `3.141592653589793` ## Description Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/SQRT1_2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT1_2 The **`Math.SQRT1_2`** property represents the square root of 1/2, which is approximately 0.707. ## Value `0.7071067811865476` ## Description `Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](./sqrt.mdx). Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/SQRT2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.SQRT2 The **`Math.SQRT2`** property represents the square root of 2, approximately 1.414. ## Value `0.7071067811865476` ## Description `Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](./sqrt.mdx). Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/abs.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.abs() The **`Math.abs()`** function returns the absolute value of a number. ## Syntax ```js Math.abs(x) ``` ### Parameters - `x` - : A number. ### Return value The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`. ## Description Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/acos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acos() The **`Math.acos()`** function returns the inverse cosine (in radians) of a number. ## Syntax ```js Math.acos(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's cosine value. ### Return value The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/acosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.acosh() The **`Math.acosh()`** function returns the inverse hyperbolic cosine of a number. ## Syntax ```js Math.acosh(x) ``` ### Parameters - `x` - : A number greater than or equal to 1. ### Return value The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`. ## Description Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/asin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asin() The **`Math.asin()`** function returns the inverse sine (in radians) of a number. ## Syntax ```js Math.asin(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive, representing the angle's sine value. ### Return value The inverse sine (angle in radians between -π2, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/asinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.asinh() The **`Math.asinh()`** function returns the inverse hyperbolic sine of a number. ## Syntax ```js Math.asinh(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse hyperbolic sine of `x`. ## Description Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/atan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan() The **`Math.atan()`** function returns the inverse tangent (in radians) of a number. ## Syntax ```js Math.atan(x) ``` ### Parameters - `x` - : A number. ### Return value The inverse tangent (angle in radians between -π2 and π2, inclusive) of `x`. If `x` is `Infinity`, it returns π2. If `x` is `-Infinity`, it returns -π2. ## Description Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/atan2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atan2() The **`Math.atan2()`** function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`. ## Syntax ```js Math.atan2(y, x) ``` ### Parameters - `y` - : The y coordinate of the point. - `x` - : The x coordinate of the point. ### Return value The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y). ## Description The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. `Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](./atan.mdx) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases: | `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` | | -------------------- | ----------- | ------------------ | ------------------ | | `Infinity` | `Infinity` | π / 4 | `NaN` | | `Infinity` | `-Infinity` | -π / 4 | `NaN` | | `-Infinity` | `Infinity` | 3π / 4 | `NaN` | | `-Infinity` | `-Infinity` | -3π / 4 | `NaN` | | 0 | 0 | 0 | `NaN` | | 0 | -0 | -0 | `NaN` | | < 0 (including `-0`) | 0 | π | 0 | | < 0 (including `-0`) | -0 | -π | 0 | | `-Infinity` | > 0 | π | -0 | | -0 | > 0 | π / 2 | -π / 2 | | `-Infinity` | < 0 | -π | 0 | | -0 | < 0 | -π / 2 | π / 2 | In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than -π2 or greater than π2. Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/atanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.atanh() The **`Math.atanh()`** function returns the inverse hyperbolic tangent of a number. ## Syntax ```js Math.atanh(x) ``` ### Parameters - `x` - : A number between -1 and 1, inclusive. ### Return value The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`. ## Description Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/cbrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cbrt() The **`Math.cbrt()`** function returns the cube root of a number. ## Syntax ```js Math.cbrt(x) ``` ### Parameters - `x` - : A number. ### Return value The cube root of `x`. ## Description Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/ceil.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.ceil() The **`Math.ceil()`** function always rounds up and returns the smaller integer greater than or equal to a given number. ## Syntax ```js Math.ceil(x) ``` ### Parameters - `x` - : A number. ### Return value The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](./floor.mdx). ## Description Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/clz32.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.clz32() The **`Math.clz32()`** function returns the number of leading zero bits in the 32-bit binary representation of a number. ## Syntax ```js Math.clz32(x) ``` ### Parameters - `x` - : A number. ### Return value The number of leading zero bits in the 32-bit binary representation of `x`. ## Description `clz32` is short for **C**ount**L**eading**Z**eros**32**. If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned. This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/cos.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cos() The **`Math.cos()`** function returns the cosine of a number in radians. ## Syntax ```js Math.cos(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/cosh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.cosh() The **`Math.cosh()`** function returns the hyperbolic cosine of a number. ## Syntax ```js Math.cosh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic cosine of `x`. ## Description Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/exp.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.exp() The **`Math.exp()`** function returns [E](./E.mdx) raised to the power of a number. ## Syntax ```js Math.exp(x) ``` ### Parameters - `x` - : A number. ### Return value A nonnegative number representing ex, where e is [the base of the natural logarithm](./E.mdx). ## Description Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/expm1.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.expm1() The **`Math.expm1()`** function returns [E](./E.mdx) raised to the power of a number, subtracted by 1. ## Syntax ```js Math.expm1(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing ex - 1, where e is [the base of the natural logarithm](./E.mdx). ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate ex where x is a number very close to 0, you should get an answer very close to 1 + x, because limx0ex1x=1. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision. Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/floor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.floor() The **`Math.floor()`** function always rounds down and returns the largest integer less than or equal to a given number. ## Syntax ```js Math.floor(x) ``` ### Parameters - `x` - : A number. ### Return value The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](./ceil.mdx). ## Description Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/fround.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.fround() The **`Math.fround()`** function returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number. ## Syntax ```js Math.fround(doubleFloat) ``` ### Parameters - `doubleFloat` - : A number. ### Return value The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`. ## Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned. Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/hypot.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.hypot() The **`Math.hypot()`** function returns the square root of the sum of squares of its arguments. ## Syntax ```js Math.hypot() Math.hypot(value0) Math.hypot(value0, value1) Math.hypot(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Numbers. ### Return value The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns `0` if no arguments are given or all arguments are ±0. ## Description Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`. This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* … ,*/, vN)`. `Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](../Number/MAX_VALUE.mdx), which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`. With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](./abs.mdx). [`Math.hypot.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/imul.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.imul() The **`Math.imul()`** function returns the result of the C-like 32-bit multiplication of the two parameters. ## Syntax ```js Math.imul(a, b) ``` ### Parameters - `a` - : First number. - `b` - : Second number. ### Return value The result of the C-like 32-bit multiplication of the given arguments. ## Description `Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log() The **`Math.log()`** function returns the natural logarithm (base [E](./E.mdx)) of a number. ## Syntax ```js Math.log(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The natural logarithm (base [E](./E.mdx)) of `x`. If `x` is ±0, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < 0`, returns `NaN`. ## Description Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster. Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/log10.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log10() The **`Math.log10()`** function returns the base 10 logarithm of a number. ## Syntax ```js Math.log10(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 10 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/log1p.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log1p() The **`Math.log1p()`** function returns the natural logarithm (base [E](./E.mdx)) of `1 + x`, where `x` is the argument. ## Syntax ```js Math.log1p(x) ``` ### Parameters - `x` - : A number greater than or equal to -1. ### Return value The natural logarithm (base [E](./E.mdx)) of `x + 1`. If `x` is -1, returns [`-Infinity`](../Number/NEGATIVE_INFINITY.mdx). If `x < -1`, returns `NaN`. ## Description For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because limx0log(1+x)x=1. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case). If the value of `x` is less than -1, the return value is always `NaN`. Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/log2.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.log2() The **`Math.log2()`** function returns the base 2 logarithm of a number. ## Syntax ```js Math.log2(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The base 2 logarithm of `x`. If `x < 0`, returns `NaN`. ## Description Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/max.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.max() The **`Math.max()`** function returns the largest of the numbers given as input parameters, or `-Infinity` if there are no parameters. ## Syntax ```js Math.max() Math.max(value0) Math.max(value0, value1) Math.max(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, `value2`, … , `valueN` - : Zero or more numbers among which the largest value will be selected and returned. ### Return value The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `-Infinity` if no parameters are provided. ## Description Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.max.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/min.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.min() The **`Math.min()`** function returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters. ## Syntax ```js Math.min() Math.min(value0) Math.min(value0, value1) Math.min(value0, value1, /* … ,*/ valueN) ``` ### Parameters - `value1`, …, `valueN` - : Zero or more numbers among which the lowest value will be selected and returned. ### Return value The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided. ## Description Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). [`Math.min.length`](../Function/prototype/length.mdx) is 2, which weakly signals that it's designed to handle at least two parameters. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/pow.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.pow() The **`Math.pow()`** method returns the value of a base raised to a power. ## Syntax ```js Math.pow(base, exponent) ``` ### Parameters - `base` - : The base number. - `exponent` - : The exponent number. ### Return value A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases: - `exponent` is `NaN`. - `base` is `NaN` and `exponent` is not `0`. - `base` is ±1 and `exponent` is ±`Infinity`. - `base < 0` and `exponent` is not an integer. ## Description `Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers. `Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior. Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/random.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.random() The **`Math.random()`** function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. > **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `crypto.getRandomValues()` method. ## Syntax ```js Math.random() ``` ### Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/round.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.round() The **`Math.round()`** function returns the value of a number rounded to the nearest integer. ## Syntax ```js Math.round(x) ``` ### Parameters - `x` - : A number. ### Return value The value of `x` rounded to the nearest integer. ## Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. > **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5. `Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](./floor.mdx). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent. Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sign() The **`Math.sign()`** function returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is. ## Syntax ```js Math.sign(x) ``` ### Parameters - `x` - : A number. ### Return value A number representing the sign of `x`: - If `x` is positive, returns `1`. - If `x` is negative, returns `-1`. - If `x` is positive zero, returns `0`. - If `x` is negative zero, returns `-0`. - Otherwise, returns `NaN`. ## Description Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/sin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sin() The **`Math.sin()`** function returns the sine of a number in radians. ## Syntax ```js Math.sin(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. ## Description Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/sinh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sinh() The **`Math.sinh()`** function returns the hyperbolic sine of a number. ## Syntax ```js Math.sinh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic sine of `x`. ## Description Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/sqrt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.sqrt() The **`Math.sqrt()`** function returns the square root of a number. ## Syntax ```js Math.sqrt(x) ``` ### Parameters - `x` - : A number greater than or equal to 0. ### Return value The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`. ## Description Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/tan.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tan() The **`Math.tan()`** function returns the tangent of a number in radians. ## Syntax ```js Math.tan(x) ``` ### Parameters - `x` - : A number representing an angle in radians. ### Return value The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`. > **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`. ## Description Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/tanh.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.tanh() The **`Math.tanh()`** function returns the hyperbolic tangent of a number. ## Syntax ```js Math.tanh(x) ``` ### Parameters - `x` - : A number. ### Return value The hyperbolic tangent of `x`. ## Description Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Math/trunc.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Math.trunc() The **`Math.trunc()`** function returns the integer part of a number by removing any fractional digits. ## Syntax ```js Math.trunc(x) ``` ### Parameters - `x` - : A number. ### Return value The integer part of `x`. ## Description Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # NaN The global **`NaN`** property is a value representing Not-A-Number. ## Value The same number value as [`Number.NaN`](./Number/NaN.mdx). ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See see [silently escaping NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#silently_escaping_nan) for a counter-example.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value — including to another `NaN` value. `NaN` is also one of the [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) values in JavaScript. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/MAX_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_SAFE_INTEGER The **`Number.MAX_SAFE_INTEGER`** constant represents the maximum safe integer in JavaScript (253 – 1). For larger integers, consider using `BigInt`. ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/MAX_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MAX_VALUE The **`Number.MAX_VALUE`** property represents the maximum numeric value representable in JavaScript. ## Value 21024 - 1, or approximately `1.7976931348623157E+308`. ## Description Values larger than `MAX_VALUE` are represented as [`Infinity`](../../globals/Infinity.mdx) and will lose their actual value. Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/MIN_SAFE_INTEGER.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_SAFE_INTEGER The **`Number.MIN_SAFE_INTEGER`** constant represents the minimum safe integer in JavaScript, or -(253 - 1). To represent integers smaller than this, consider using `BigInt`. ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information. Because `MIN_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MIN_SAFE_INTEGER`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/MIN_VALUE.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.MIN_VALUE The **`Number.MIN_VALUE`** property represents the smallest positive numeric value representable in JavaScript. ## Value 2-1074, or `5E-324`. ## Description `Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, _"must be the smallest non-zero positive value that can actually be represented by the implementation"_. This is because small IEEE-754 floating point numbers are [denormalized](https://en.wikipedia.org/wiki/Subnormal_number), but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger. In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`. Because `MIN_VALUE` is a static property of `Number`, you always use it as `Number.MIN_VALUE`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/NEGATIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NEGATIVE_INFINITY The **`Number.NEGATIVE_INFINITY`** property represents the negative Infinity value. ## Value The same as the negative value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.NEGATIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any positive value divided by `Number.NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `Number.NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - [`NaN`](../../globals/NaN.mdx) multiplied by `Number.NEGATIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.NEGATIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.NEGATIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `x > Number.NEGATIVE_INFINITY` is true for any number _x_ that isn't `Number.NEGATIVE_INFINITY`. You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.NEGATIVE_INFINITY` is a static property of `Number`, you always use it as `Number.NEGATIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/NaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.NaN The **`Number.NaN`** property represents Not-A-Number, which is equivalent to [description for the global property](../../globals/NaN.mdx). For more information about the behaviors of `NaN`, see the [`NaN`](../../globals/NaN.mdx). ## Value The number value [`NaN`](../../globals/NaN.mdx). ## Description Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/Number.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number() constructor The **`Number()` constructor** creates a `Number` object. When called instead as a function, it performs type conversion to a primitive number, which is usually more useful. ## Syntax ```js new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns [`NaN`](../../globals/NaN.mdx). > **Warning:** You should rarely find yourself using `Number` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/POSITIVE_INFINITY.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.POSITIVE_INFINITY The **`Number.POSITIVE_INFINITY`** property represents the positive Infinity value. ## Value The same as the value of the global [`Infinity`](../../globals/Infinity.mdx) property. ## Description The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including `Number.POSITIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.POSITIVE_INFINITY`. - Any negative value, including `Number.NEGATIVE_INFINITY`, multiplied by `Number.POSITIVE_INFINITY` is `Number.NEGATIVE_INFINITY`. - Any positive number divided by `Number.POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `Number.POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `NaN` multiplied by `Number.POSITIVE_INFINITY` is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY`, divided by any negative value except `Number.NEGATIVE_INFINITY`, is `Number.NEGATIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by any positive value except `Number.POSITIVE_INFINITY`, is `Number.POSITIVE_INFINITY`. - `Number.POSITIVE_INFINITY`, divided by either `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`, is [`NaN`](../../globals/NaN.mdx). - `Number.POSITIVE_INFINITY > x` is true for any number _x_ that isn't `Number.POSITIVE_INFINITY`. You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that [`NaN`](../../globals/NaN.mdx) would be more appropriate in such a case. Because `Number.POSITIVE_INFINITY` is a static property of `Number`, you always use it as `Number.POSITIVE_INFINITY`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/epsilon.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.EPSILON The **`Number.EPSILON`** property represents the difference between 1 and the smallest floating point number greater than 1. ## Value 2-52, or approximately `2.2204460492503130808472633361816E-16`. ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2-52. Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of `Number`, you always use it as `Number.EPSILON`, rather than as a property of a number value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isFinite() The **`Number.isFinite()`** method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive [`Infinity`](../../globals/Infinity.mdx), negative `Infinity`, nor [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.isFinite(value) ``` ### Parameters - `value` - : The value to be tested for finiteness. ### Return value The boolean value `true` if the given value is a finite number. Otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/isInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isInteger() The **`Number.isInteger()`** method determines whether the passed value is an integer. ## Syntax ```js Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../../globals/NaN.mdx) or [`Infinity`](../../globals/Infinity.mdx), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isNaN() The **`Number.isNaN()`** method determines whether the passed value is the number value [`NaN`](../../globals/NaN.mdx), and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function. ## Syntax ```js Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for [`NaN`](../../globals/NaN.mdx). ### Return value The boolean value `true` if the given value is a number with value [`NaN`](../../globals/NaN.mdx). Otherwise, `false`. ## Description The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is [`NaN`](../../globals/NaN.mdx), even if the other operand is also [`NaN`](../../globals/NaN.mdx). Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable. As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to [`NaN`](../../globals/NaN.mdx) but aren't actually the same value as [`NaN`](../../globals/NaN.mdx). This also means that only values of the Number type that are also [`NaN`](../../globals/NaN.mdx) return `true`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/isSafeInteger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.isSafeInteger() The **`Number.isSafeInteger()`** method determines whether the provided value is a number that is a _safe integer_. ## Syntax ```js Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the `BigInt` type. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseFloat() The **`Number.parseFloat()`** method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns [`NaN`](../../globals/NaN.mdx). ## Syntax ```js Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or [`NaN`](../../globals/NaN.mdx) when the first non-whitespace character cannot be converted to a number. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.parseInt() The **`Number.parseInt()`** method parses a string argument and returns an integer of the specified radix or base. ## Syntax ```js Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, [`NaN`](../../globals/NaN.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/prototype/toExponential.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toExponential() The **`toExponential()`** method returns a string representing the `Number` object in exponential notation. ## Syntax ```js toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` _**optional**_ - : Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. ### Return value A string representing the given `Number` object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `fractionDigits` is too small or too large. Values between `0` and `100`, inclusive, will not cause a [`RangeError`](../../../globals/RangeError/RangeError.mdx). - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toExponential()`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/prototype/toFixed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toFixed() The **`toFixed()`** method formats a number using fixed-point notation. ## Syntax ```js toFixed() toFixed(digits) ``` ### Parameters - `digits` _**optional**_ - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : If `digits` is smaller than `0`, larger than `100`, or is `NaN`. - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If this method is invoked on an object that is not a `Number`. ## Description The `toFixed()` method returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of `numObj` is greater or equal to 1021, this method uses the same algorithm as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of `numObj` is non-finite. The output of `toFixed()` may be more precise than [`toString()`](../../../globals/Number/prototype/toString.mdx) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js 0.3.toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toLocaleString() The **`toLocaleString()`** method returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. ## Syntax ```js toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string with a language-sensitive representation of the given number. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. ## Performance When formatting large numbers of numbers, it is better to create a `Intl.NumberFormat` object and use the function provided by its `format` property. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/prototype/toPrecision.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toPrecision() The **`toPrecision()`** method returns a string representing the `Number` object to the specified precision. ## Syntax ```js toPrecision() toPrecision(precision) ``` ### Parameters - `precision` _**optional**_ - : An integer specifying the number of significant digits. ### Return value A string representing a `Number` object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the [`Number.prototype.toFixed()`](../../../globals/Number/prototype/toFixed.mdx) method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx). If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - `RangeError` - : If `precision` is not between `1` and `100` (inclusive), a [`RangeError`](../../../globals/RangeError/RangeError.mdx) is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.toString() The **`toString()`** method returns a string representing the specified number value. ## Syntax ```js toString() toString(radix) ``` ### Parameters - `radix` _**optional**_ - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - [`RangeError`](../../../globals/RangeError/RangeError.mdx) - : Thrown if `radix` is less than 2 or greater than 36. ## Description The `Number` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. [`Infinity`](../../../globals/Infinity.mdx) returns `"Infinity"` and [`NaN`](../../../globals/NaN.mdx) returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Number/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Number.prototype.valueOf() The **`valueOf()`** method returns the wrapped primitive value of a `Number` object. ## Syntax ```js valueOf() ``` ### Return value A number representing the primitive value of the specified `Number` object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/Object.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object() The **`Object` constructor** turns the input into an object. Its behavior depends on the input's type. - If the value is [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx), it creates and returns an empty object. - Otherwise, it returns an object of a Type that corresponds to the given value. - If the value is an object already, it returns the value. ## Syntax ```js new Object(value) Object(value) ``` > **Note:** `Object()` can be called with or without `new`. Both create a new object. ### Parameters - `value` - : Any value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/assign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.assign() The **`Object.assign()`** method copies all [enumerable](../../globals/Object/prototype/propertyIsEnumerable.mdx) [own properties](../../globals/Object/hasOwn.mdx) from one or more _source objects_ to a _target object_. It returns the modified target object. ## Syntax ```js Object.assign(target, ...sources) ``` ### Parameters - `target` - : The target object — what to apply the sources' properties to, which is returned after it is modified. - `sources` - : The source object(s) — objects containing the properties you want to apply. ### Return value The target object. ## Description Properties in the target object are overwritten by properties in the sources if they have the same "key". Later sources' properties overwrite earlier ones. The `Object.assign()` method only copies _enumerable_ and _own_ properties from a source object to a target object. It uses `[[Get]]` on the source and `[[Set]]` on the target, so it will invoke [getters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/get) and [setters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/set). Therefore it _assigns_ properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) and [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) instead. Both `String` and `Symbol` properties are copied. In case of an error, for example if a property is non-writable, a [`TypeError`](../../globals/TypeError/TypeError.mdx) is raised, and the `target` object is changed if any properties are added before the error is raised. > **Note:** `Object.assign()` does not throw on > [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../globals/undefined.mdx) sources. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/create.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.create() The **`Object.create()`** method creates a new object, using an existing object as the prototype of the newly created object. ## Syntax ```js Object.create(proto) Object.create(proto, propertiesObject) ``` ### Parameters - `proto` - : The object which should be the prototype of the newly-created object. - `propertiesObject` _**optional**_ - : If specified and not [`undefined`](../../globals/undefined.mdx), an object whose [enumerable own properties](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of [`Object.defineProperties()`](../../globals/Object/defineProperties.mdx). ### Return value A new object with the specified prototype object and properties. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if `proto` is neither [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) nor an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/defineProperties.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperties() The **`Object.defineProperties()`** method defines new or modifies existing properties directly on an object, returning the object. ## Syntax ```js Object.defineProperties(obj, props) ``` ### Parameters - `obj` - : The object on which to define or modify properties. - `props` - : An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in `props` must be either a data descriptor or an accessor descriptor; it cannot be both (see [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) for more details). Data descriptors and accessor descriptors may optionally contain the following keys: - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A data descriptor also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if and only if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An accessor descriptor also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. The function's return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. The function will receive as its only argument the new value being assigned to the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both `value` or `writable` and `get` or `set` keys, an exception is thrown. ### Return value The object that was passed to the function. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.defineProperty() The static method **`Object.defineProperty()`** defines a new property directly on an object, or modifies an existing property on an object, and returns the object. ## Syntax ```js Object.defineProperty(obj, prop, descriptor) ``` ### Parameters - `obj` - : The object on which to define the property. - `prop` - : The name or `Symbol` of the property to be defined or modified. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The object that was passed to the function. ## Description This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (`for...in` loop or [`Object.keys`](../../globals/Object/keys.mdx) method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using `Object.defineProperty()` are not writable, not enumerable, and not configurable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A **data descriptor** is a property that has a value, which may or may not be writable. An **accessor descriptor** is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (please note: the **defaults** mentioned here are in the case of defining properties using `Object.defineProperty()`): - `configurable` - : when this is set to `false`, - the type of this property cannot be changed between data property and accessor property, and - the property may not be deleted, and - other attributes of its descriptor cannot be changed (however, if it's a data descriptor with `writable: true`, the `value` can be changed, and `writable` can be changed to `false`). **Defaults to `false`.** - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. **Defaults to `false`.** A **data descriptor** also has the following optional keys: - `value` - : The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). **Defaults to [`undefined`](../../globals/undefined.mdx).** - `writable` - : `true` if the value associated with the property may be changed with an assignment operator. **Defaults to `false`.** An **accessor descriptor** also has the following optional keys: - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter. When the property is accessed, this function is called without arguments and with `this` set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. **Defaults to [`undefined`](../../globals/undefined.mdx).** - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with `this` set to the object through which the property is assigned. **Defaults to [`undefined`](../../globals/undefined.mdx).** If a descriptor has neither of `value`, `writable`, `get` and `set` keys, it is treated as a data descriptor. If a descriptor has both \[`value` or `writable`] and \[`get` or `set`] keys, an exception is thrown. Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or point to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) with [`Object.create(null)`](../../globals/Object/create.mdx). ```js const obj = {}; // 1. Using a null prototype: no inherited properties const descriptor = Object.create(null); descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults Object.defineProperty(obj, 'key', descriptor); // 2. Being explicit by using a throw-away object literal with all attributes present Object.defineProperty(obj, 'key2', { enumerable: false, configurable: false, writable: false, value: 'static' }); // 3. Recycling same object function withValue(value) { const d = withValue.d || ( withValue.d = { enumerable: false, writable: false, configurable: false, value, } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // and Object.defineProperty(obj, 'key', withValue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (Object.freeze || Object)(Object.prototype); ``` When the property already exists, `Object.defineProperty()` attempts to modify the property according to the values in the descriptor and the property's current configuration. If the old descriptor had its `configurable` attribute set to `false`, the property is said to be _non-configurable_. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with `writable: true`, it is possible to modify the value and change the `writable` attribute from `true` to `false`. A [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown when attempts are made to change non-configurable property attributes (except `value` and `writable`, if permitted), except when defining a value same as the original value on a data property. When the current property is configurable, defining an attribute to `undefined` effectively deletes it. For example, if `o.k` is an accessor property, `Object.defineProperty(o, "k", { set: undefined })` will remove the setter, making `k` only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to `undefined`). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with `value` or `writable`), the original descriptor's `get` and `set` attributes will both be dropped. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.entries() The **`Object.entries()`** method returns an array of a given object's own enumerable string-keyed property key-value pairs. ## Syntax ```js Object.entries(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value. ## Description `Object.entries()` returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.entries()` is the same as that provided by a `for...in` loop. If you only need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you only need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/freeze.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.freeze() The **`Object.freeze()`** method _freezes_ an object. Freezing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. `freeze()` returns the same object that was passed in. Freezing an object is the highest integrity level that JavaScript provides. ## Syntax ```js Object.freeze(obj) ``` ### Parameters - `obj` - : The object to freeze. ### Return value The object that was passed to the function. ## Description Freezing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing [properties' descriptors'](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description) `configurable` to `false` — and for data properties, `writable` to `false` as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) exception (most commonly, but not exclusively, when in "strict mode"). For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. `freeze()` returns the same object that was passed into the function. It _does not_ create a frozen copy. A `TypedArray` or a [`DataView`](../../globals/DataView/DataView.mdx) with elements will cause a [`TypeError`](../../globals/TypeError/TypeError.mdx), as they are views over memory and will definitely cause other possible issues: ```js Object.freeze(new Uint8Array(0)) // No elements // Uint8Array [] Object.freeze(new Uint8Array(1)) // Has elements // TypeError: Cannot freeze array buffer views with elements Object.freeze(new DataView(new ArrayBuffer(32))) // No elements // DataView {} Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements // Float64Array [] Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements // TypeError: Cannot freeze array buffer views with elements ``` Note that as the standard three properties (`buf.byteLength`, `buf.byteOffset` and `buf.buffer`) are read-only (as are those of an `ArrayBuffer`, there is no reason for attempting to freeze these properties. Unlike [`Object.seal()`](../../globals/Object/seal.mdx), existing properties in objects frozen with `Object.freeze()` are made immutable and data properties cannot be re-assigned. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/fromEntries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.fromEntries() The **`Object.fromEntries()`** method transforms a list of key-value pairs into an object. ## Syntax ```js Object.fromEntries(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), such as an `Array` or [Map](../../globals/Map/Map.mdx), containing a list of objects. Each object should have two properties: - `0` - : A string or `Symbol` representing the property key. - `1` - : The property value. Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value. ### Return value A new object whose properties are given by the entries of the iterable. ## Description The `Object.fromEntries()` method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The `iterable` argument is expected to be an object that implements an `@@iterator` method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key. `Object.fromEntries()` performs the reverse of [`Object.entries()`](../../globals/Object/entries.mdx), except that `Object.entries()` only returns string-keyed properties, while `Object.fromEntries()` can also create symbol-keyed properties. > **Note:** Unlike [`Array.from()`](../../globals/Array/from.mdx), `Object.fromEntries()` does not use the value of `this`, so calling it on another constructor does not create objects of that type. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptor() The **`Object.getOwnPropertyDescriptor()`** method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration. ## Syntax ```js Object.getOwnPropertyDescriptor(obj, prop) ``` ### Parameters - `obj` - : The object in which to look for the property. - `prop` - : The name or `Symbol` of the property whose description is to be retrieved. ### Return value A property descriptor of the given property if it exists on the object, [`undefined`](../../globals/undefined.mdx) otherwise. ## Description This method permits examination of the precise description of a property. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/getOwnPropertyDescriptors.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyDescriptors() The **`Object.getOwnPropertyDescriptors()`** method returns all own property descriptors of a given object. ## Syntax ```js Object.getOwnPropertyDescriptors(obj) ``` ### Parameters - `obj` - : The object for which to get all own property descriptors. ### Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. ## Description This method permits examination of the precise description of all own properties of an object. A _property_ in JavaScript consists of either a string-valued name or a `Symbol` and a property descriptor. Further information about property descriptor types and their attributes can be found in [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx). A _property descriptor_ is a record with some of the following attributes: - `value` - : The value associated with the property (data descriptors only). - `writable` - : `true` if and only if the value associated with the property may be changed (data descriptors only). - `get` - : A function which serves as a getter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no getter (accessor descriptors only). - `set` - : A function which serves as a setter for the property, or [`undefined`](../../globals/undefined.mdx) if there is no setter (accessor descriptors only). - `configurable` - : `true` if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - `enumerable` - : `true` if and only if this property shows up during enumeration of the properties on the corresponding object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/getOwnPropertyNames.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertyNames() The **`Object.getOwnPropertyNames()`** method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. ## Syntax ```js Object.getOwnPropertyNames(obj) ``` ### Parameters - `obj` - : The object whose enumerable and non-enumerable properties are to be returned. ### Return value An array of strings that corresponds to the properties found directly in the given object. ## Description `Object.getOwnPropertyNames()` returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object `obj`. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a `for...in` loop (or by [`Object.keys()`](../../globals/Object/keys.mdx)) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/getOwnPropertySymbols.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getOwnPropertySymbols() The **`Object.getOwnPropertySymbols()`** method returns an array of all symbol properties found directly upon a given object. ## Syntax ```js Object.getOwnPropertySymbols(obj) ``` ### Parameters - `obj` - : The object whose symbol properties are to be returned. ### Return value An array of all symbol properties found directly upon the given object. ## Description Similar to [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx), you can get all symbol properties of a given object as an array of symbols. Note that [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, `Object.getOwnPropertySymbols()` returns an empty array unless you have set symbol properties on your object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.getPrototypeOf() The **`Object.getPrototypeOf()`** method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Object.getPrototypeOf(obj) ``` ### Parameters - `obj` - : The object whose prototype is to be returned. ### Return value The prototype of the given object, which may be `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/hasOwn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.hasOwn() The **`Object.hasOwn()`** static method returns `true` if the specified object has the indicated property as its _own_ property. If the property is inherited, or does not exist, the method returns `false`. > **Note:** `Object.hasOwn()` is intended as a replacement for [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx). ## Syntax ```js hasOwn(instance, prop) ``` ### Parameters - `instance` - : The JavaScript object instance to test. - `prop` - : The `String` name or [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol) of the property to test. ### Return value `true` if the specified object has directly defined the specified property. Otherwise `false` ## Description The **`Object.hasOwn()`** method returns `true` if the specified property is a direct property of the object — even if the property value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. It is recommended over [`Object.prototype.hasOwnProperty()`](../../globals/Object/prototype/hasOwnProperty.mdx) because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/is.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.is() The **`Object.is()`** method determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). ## Syntax ```js Object.is(value1, value2) ``` ### Parameters - `value1` - : The first value to compare. - `value2` - : The second value to compare. ### Return value A boolean indicating whether or not the two arguments are the same value. ## Description `Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is). Two values are the same if one of the following holds: - both [`undefined`](../../globals/undefined.mdx) - both `null` - both `true` or both `false` - both strings of the same length with the same characters in the same order - both the same object (meaning both values reference the same object in memory) - both `BigInts` with the same numeric value - both `Symbols` that reference the same symbol value - both numbers and - both `+0` - both `-0` - both [`NaN`](../../globals/NaN.mdx) - or both non-zero, not [`NaN`](../../globals/NaN.mdx), and have the same value `Object.is()` is not equivalent to the [`==`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Equality) operator. The `==` operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is()` doesn't coerce either value. `Object.is()` is also _not_ equivalent to the [`===`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats [`NaN`](../../globals/NaN.mdx) as not equal to each other. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isExtensible() The **`Object.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). ## Syntax ```js Object.isExtensible(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is extensible. ## Description Objects are extensible by default: they can have new properties added to them, and their `[[Prototype]]` can be re-assigned. An object can be marked as non-extensible using one of [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), [`Object.seal()`](../../globals/Object/seal.mdx), [`Object.freeze()`](../../globals/Object/freeze.mdx), or [`Reflect.preventExtensions()`](../../globals/Reflect/preventExtensions.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/isFrozen.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isFrozen() The **`Object.isFrozen()`** determines if an object is [frozen](../../globals/Object/freeze.mdx). ## Syntax ```js Object.isFrozen(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is frozen. ## Description An object is frozen if and only if it is not [extensible](../../globals/Object/isExtensible.mdx), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/isSealed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.isSealed() The **`Object.isSealed()`** method determines if an object is sealed. ## Syntax ```js Object.isSealed(obj) ``` ### Parameters - `obj` - : The object which should be checked. ### Return value A `Boolean` indicating whether or not the given object is sealed. ## Description Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](../../globals/Object/isExtensible.mdx) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.keys() The **`Object.keys()`** method returns an array of a given object's own enumerable string-keyed property names. ## Syntax ```js Object.keys(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array of strings representing the given object's own enumerable string-keyed property keys. ## Description `Object.keys()` returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.keys()` is the same as that provided by a `for...in` loop. If you need the property values, use [`Object.values()`](../../globals/Object/values.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.preventExtensions() The **`Object.preventExtensions()`** method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned. ## Syntax ```js Object.preventExtensions(obj) ``` ### Parameters - `obj` - : The object which should be made non-extensible. ### Return value The object being made non-extensible. ## Description An object is extensible if new properties can be added to it. `Object.preventExtensions()` marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be _deleted_. Attempting to add new properties to a non-extensible object will fail, either silently or, in [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx). Unlike [`Object.seal()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) and [`Object.freeze()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), `Object.preventExtensions()` invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its `Reflect` counterpart (which only exists for intrinsic operations), [`Reflect.preventExtensions()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions). `Object.preventExtensions()` only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the `[[Prototype]]` of the target immutable; any `[[Prototype]]` re-assignment will throw a `TypeError`. This behavior is specific to the internal `[[Prototype]]` property; other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/prototype/constructor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.constructor The **`constructor`** data property of an `Object` instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to _the function itself_, not a string containing the function's name. > **Note:** This is a property of JavaScript objects. For the `constructor` method in classes, see [its own reference page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor). ## Value A reference to the constructor function that created the instance object. > **Note:** This property is created by default on the [`prototype`](../../../globals/Function/prototype/) property of every constructor function and is inherited by all objects created by that constructor. ## Description Any object (with the exception of [`null` prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) will have a `constructor` property on its `[[Prototype]]`. Objects created with literals will also have a `constructor` property that points to the constructor type for that object — for example, array literals create `Array` objects, and [object literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) create plain objects. ```js const o1 = {}; o1.constructor === Object; // true const o2 = new Object(); o2.constructor === Object; // true const a1 = []; a1.constructor === Array; // true const a2 = new Array(); a2.constructor === Array; // true const n = 3; n.constructor === Number; // true ``` Note that `constructor` usually comes from the constructor's [`prototype`](../../../globals/Function/prototype/) property. If you have a longer prototype chain, you can usually expect every object in the chain to have a `constructor` property. ```js const o = new TypeError(); // Inheritance: TypeError -> Error -> Object const proto = Object.getPrototypeOf; proto(o).constructor === TypeError; // true proto(proto(o)).constructor === Error; // true proto(proto(proto(o))).constructor === Object; // true ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/prototype/hasOwnProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.hasOwnProperty() The **`hasOwnProperty()`** method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). > **Note:** [`Object.hasOwn()`](../../../globals/Object/hasOwn.mdx) is recommended over > `hasOwnProperty()`, in browsers where it is supported. ## Syntax ```js hasOwnProperty(prop) ``` ### Parameters - `prop` - : The `String` name or `Symbol` of the property to test. ### Return value Returns `true` if the object has the specified property as own property; `false` otherwise. ## Description The **`hasOwnProperty()`** method returns `true` if the specified property is a direct property of the object — even if the value is `null` or `undefined`. The method returns `false` if the property is inherited, or has not been declared at all. Unlike the `in` operator, this method does not check for the specified property in the object's prototype chain. The method can be called on _most_ JavaScript objects, because most objects descend from `Object`, and hence inherit its methods. For example `Array` is an `Object`, so you can use `hasOwnProperty()` method to check whether an index exists: ```js const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined ``` The method will not be available in objects where it is reimplemented, or on objects created using `Object.create(null)` (as these don't inherit from `Object.prototype`). Examples for these cases are given below. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/prototype/isPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.isPrototypeOf() The **`isPrototypeOf()`** method checks if an object exists in another object's prototype chain. > **Note:** `isPrototypeOf()` differs from the [`instanceof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/instanceof) operator. In the expression `object instanceof AFunction`, `object`'s prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. ## Syntax ```js isPrototypeOf(object) ``` ### Parameters - `object` - : The object whose prototype chain will be searched. ### Return value A boolean indicating whether the calling object (`this`) lies in the prototype chain of `object`. Directly returns `false` when `object` is not an object (i.e. a primitive). ### Errors thrown - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if `this` is `null` or `undefined` (because it can't be [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion)). ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `isPrototypeOf()` method. This method allows you to check whether or not the object exists within another object's prototype chain. If the `object` passed as the parameter is not an object (i.e. a primitive), the method directly returns `false`. Otherwise, the `this` value is [converted to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion), and the prototype chain of `object` is searched for the `this` value, until the end of the chain is reached or the `this` value is found. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/prototype/propertyIsEnumerable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.propertyIsEnumerable() The **`propertyIsEnumerable()`** method returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property. ## Syntax ```js propertyIsEnumerable(prop) ``` ### Parameters - `prop` - : The name of the property to test. Can be a string or a `Symbol`. ### Return value A boolean value indicating whether the specified property is enumerable and is the object's own property. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `propertyIsEnumerable()` method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns `false`. This method is equivalent to [`Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/prototype/toLocaleString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toLocaleString() The **`toLocaleString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. ## Syntax ```js toLocaleString() ``` ### Parameters None. However, all objects that override this method are expected to accept at most two parameters, corresponding to `locales` and `options`, such as [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx). The parameter positions should not be used for any other purpose. ### Return value The return value of calling `this.toString()`. ## Description All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toLocaleString()` method. `Object`'s `toLocaleString` returns the result of calling [`this.toString()`](../../../globals/Object/prototype/toString.mdx). This function is provided to give objects a generic `toLocaleString` method, even though not all may use it. In the core language, these built-in objects override `toLocaleString` to provide locale-specific formatting: - `Array`: [`Array.prototype.toLocaleString()`](../../../globals/Array/prototype/toLocaleString.mdx) - `Number`: [`Number.prototype.toLocaleString()`](../../../globals/Number/prototype/toLocaleString.mdx) - `Date`: [`Date.prototype.toLocaleString()`](../../../globals/Date/prototype/toLocaleString.mdx) - `BigInt`: [`BigInt.prototype.toLocaleString()`](../../../globals/BigInt/prototype/toLocaleString.mdx) ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.toString() The **`toString()`** method returns a string representing the object. This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js toString() ``` ### Parameters By default `toString()` takes no parameters. However, objects that inherit from `Object` may override it with their own implementations that do take parameters. For example, the [`Number.prototype.toString()`](../../../globals/Number/prototype/toString.mdx) and [`BigInt.prototype.toString()`](../../../globals/BigInt/prototype/toString.mdx) methods take an optional `radix` parameter. ### Return value A string representing the object. ## Description JavaScript calls the `toString` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `toString` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), but [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) call `valueOf()` in priority. However, because the base [`valueOf()`](../../../globals/Object/prototype/valueOf.mdx) method returns an object, the `toString()` method is usually called in the end, unless the object overrides `valueOf()`. For example, `+[1]` returns `1`, because its [`toString`](../../../globals/Array/prototype/toString.mdx) method returns `"1"`, which is then converted to a number. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. When you create a custom object, you can override `toString()` to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. To use the base `Object.prototype.toString()` with an object that has it overridden (or to invoke it on `null` or `undefined`), you need to call [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) or [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) on it, passing the object you want to inspect as the first parameter (called `thisArg`). ```js const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" ``` `Object.prototype.toString()` returns `"[object Type]"`, where `Type` is the object type. If the object has a [`Symbol.toStringTag`](../../../globals/Symbol/toStringTag.mdx) property whose value is a string, that value will be used as the `Type`. Many built-in objects, including [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Symbol`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol), have a `Symbol.toStringTag`. Some objects predating ES6 do not have `Symbol.toStringTag`, but have a special tag nonetheless. They include (the tag is the same as the type name given below): - [`Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) - [`Function`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions) (anything whose [`typeof`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof) returns `"function"`) - [`Error`](../../../globals/Error/Error.mdx) - [`Boolean`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) - [`Number`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`String`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) - [`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`RegExp`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp) The [`arguments`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments) object returns `"[object Arguments]"`. Everything else, including user-defined classes, unless with a custom `Symbol.toStringTag`, will return `"[object Object]"`. `Object.prototype.toString()` invoked on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](../../../globals/undefined.mdx) returns `[object Null]` and `[object Undefined]`, respectively. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.prototype.valueOf() The **`valueOf()`** method of `Object` converts the `this` value [to an object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion). This method is meant to be overridden by derived objects for custom [type conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) logic. ## Syntax ```js valueOf() ``` ### Parameters None. ### Return value The `this` value, converted to an object. > **Note:** In order for `valueOf` to be useful during type conversion, it must return a primitive. Because all primitive types have their own `valueOf()` methods, calling `aPrimitiveValue.valueOf()` generally does not invoke `Object.prototype.valueOf()`. ## Description JavaScript calls the `valueOf` method to [convert an object to a primitive value](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). You rarely need to invoke the `valueOf` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. This method is called in priority by [numeric conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) and [primitive conversion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion), but [string conversion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) calls `toString()` in priority, and `toString()` is very likely to return a string value (even for the [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx) base implementation), so `valueOf()` is usually not called in this case. All objects that inherit from `Object.prototype` (that is, all except [`null`-prototype objects](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)) inherit the `toString()` method. The `Object.prototype.valueOf()` base implementation is deliberately useless: by returning an object, its return value will never be used by any [primitive conversion algorithm](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion). Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override `valueOf()` to call a custom method, so that your custom object can be converted to a primitive value. Generally, `valueOf()` is used to return a value that is most meaningful for the object — unlike `toString()`, it does not need to be a string. Alternatively, you can add a [`Symbol.toPrimitive`](../../../globals/Symbol/toPrimitive.mdx) method, which allows even more control over the conversion process, and will always be preferred over `valueOf` or `toString` for any type conversion. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/seal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.seal() The **`Object.seal()`** method _seals_ an object. Sealing an object [prevents extensions](../../globals/Object/preventExtensions.mdx) and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. `seal()` returns the same object that was passed in. ## Syntax ```js Object.seal(obj) ``` ### Parameters - `obj` - : The object which should be sealed. ### Return value The object being sealed. ## Description Sealing an object is equivalent to [preventing extensions](../../globals/Object/preventExtensions.mdx) and then changing all existing properties' descriptors to `configurable: false`. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a [`TypeError`](../../globals/TypeError/TypeError.mdx) (most commonly, although not exclusively, when in "strict mode" code). The prototype chain remains untouched. However, due to the effect of [preventing extensions](../../globals/Object/preventExtensions.mdx), the `[[Prototype]]` cannot be reassigned. Unlike [`Object.freeze()`](../../globals/Object/freeze.mdx), objects sealed with `Object.seal()` may have their existing properties changed, as long as they are writable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.setPrototypeOf() The **`Object.setPrototypeOf()`** method sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). > **Warning:** Changing the `[[Prototype]]` of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the `Object.setPrototypeOf(...)` statement, but may extend to **_any_** code that has access to any object whose `[[Prototype]]` has been altered. You can read more in [JavaScript engine fundamentals: optimizing prototypes](https://mathiasbynens.be/notes/prototypes). > > Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the `[[Prototype]]` of an object. Instead, create a new object with the desired `[[Prototype]]` using [`Object.create()`](../../globals/Object/create.mdx). ## Syntax ```js Object.setPrototypeOf(obj, prototype) ``` ### Parameters - `obj` - : The object which is to have its prototype set. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value The specified object. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if one of the following conditions is met: - The `obj` parameter is [non-extensible](../../globals/Object/isExtensible.mdx), or it's an [immutable prototype exotic object](https://tc39.es/ecma262/#sec-immutable-prototype-exotic-objects), such as `Object.prototype`. - The `prototype` parameter is not an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description `Object.setPrototypeOf()` is generally considered the proper way to set the prototype of an object. If the `obj` parameter is not an object (e.g. number, string, etc.), this method does nothing. For security concerns, there are certain built-in objects that are designed to have an _immutable prototype_. This prevents prototype pollution attacks, especially [proxy-related ones](https://github.com/tc39/ecma262/issues/272). The core language only specifies `Object.prototype` as an immutable prototype exotic object, whose prototype is always `null`. ```js Object.isExtensible(Object.prototype); // true; you can add more properties Object.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#' cannot have their prototype set ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Object/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Object.values() The **`Object.values()`** method returns an array of a given object's own enumerable string-keyed property values. ## Syntax ```js Object.values(obj) ``` ### Parameters - `obj` - : An object. ### Return value An array containing the given object's own enumerable string-keyed property values. ## Description `Object.values()` returns an array whose elements are strings corresponding to the enumerable string-keyed property values found directly upon `object`. This is the same as iterating with a `for...in` loop, except that a `for...in` loop enumerates properties in the prototype chain as well. The order of the array returned by `Object.values()` is the same as that provided by a `for...in` loop. If you need the property keys, use [`Object.keys()`](../../globals/Object/keys.mdx) instead. If you need both the property keys and values, use [`Object.entries()`](../../globals/Object/entries.mdx) instead. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Promise[Symbol.species] The **`Promise[Symbol.species]`** accessor property returns the constructor used to construct return values from promise methods. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js Promise[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct return values from promise chaining methods that create new promises. ## Description The `Symbol.species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `Symbol.species` of derived subclasses would also return the constructor itself by default. ```js class SubPromise extends Promise {} SubPromise[Symbol.species] === Promise; // true ``` Promise chaining methods — [`then()`](../../globals/Promise/prototype/then.mdx), [`finally()`](../../globals/Promise/prototype/finally.mdx) — return new promise objects. They get the constructor to construct the new promise through `this.constructor[Symbol.species]`. If `this.constructor` is `undefined`, or if `this.constructor[Symbol.species]` is `undefined` or `null`, the default [`Promise()`](../../globals/Promise/Promise.mdx) constructor is used. Otherwise, the constructor returned by `this.constructor[Symbol.species]` is used to construct the new promise object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/Promise.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise() The **`Promise()`** constructor is primarily used to wrap functions that do not already support promises. ## Syntax ```js new Promise(executor) ``` > **Note:** `Promise()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `executor` - : A `function` to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#resolver-function) promise). The `rejectFunc` has semantics close to the [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](../../globals/Error/Error.mdx) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#resolver-function). The promise may stay pending (in case another [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through [`Promise.prototype.then`](../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../globals/Promise/prototype/finally.mdx). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` ### Resolver function The resolver function `resolveFunc` has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a [`TypeError`](../../globals/TypeError/TypeError.mdx). - If it's called with a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/all.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.all() The **`Promise.all()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. ## Syntax ```js Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by [`Promise.allSettled()`](../../globals/Promise/allSettled.mdx) will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/allSettled.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.allSettled() The **`Promise.allSettled()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. ## Syntax ```js Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promise in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by [`Promise.all()`](../../globals/Promise/all.mdx) may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/any.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.any() The **`Promise.any()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons. ## Syntax ```js Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array` of promises. ### Return value A `Promise` that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an `AggregateError` containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike [`Promise.all()`](../../globals/Promise/all.mdx), which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with [`Array.prototype.some()`](../../globals/Array/prototype/some.mdx) and [`Array.prototype.every()`](../../globals/Array/prototype/every.mdx). Also, unlike [`Promise.race()`](../../globals/Promise/race.mdx), which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/prototype/catch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.catch() The **`catch()`** method of a `Promise` object schedules a function to be called when the promise is rejected. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for [`Promise.prototype.then(undefined, onRejected)`](../../../globals/Promise/prototype/then.mdx). ## Syntax ```js catch(onRejected) catch((reason) => { // rejection handler }) ``` ### Parameters - `onRejected` - : A `Function` called when the `Promise` is rejected. This function has one parameter: the _rejection reason_. ### Return value Returns a new `Promise`. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if `onRejected` throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. ## Description The `catch` method is used for error handling in promise composition. Since it returns a `Promise`, it [can be chained](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx). If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx), [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx), or [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx)), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](../../../globals/Error/Error.mdx). As with synchronous [`throw`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/prototype/finally.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.finally() The **`finally()`** method of a `Promise` object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's [`Promise.prototype.then`](../../../globals/Promise/prototype/then.mdx) and [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) handlers. ## Syntax ```js finally(onFinally) finally(() => { // Code that will run after promise is settled (fulfilled or rejected) }) ``` ### Parameters - `onFinally` - : A `Function` called when the `Promise` is settled. This handler receives no parameters. ### Return value Returns an equivalent `Promise`. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling [`then(onFinally, onFinally)`](../../../globals/Promise/prototype/then.mdx). However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like [`Promise.prototype.catch()`](../../../globals/Promise/prototype/catch.mdx), `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments — which, for [`Promise.prototype.then()`](../../../globals/Promise/prototype/then.mdx), means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the [`Promise.resolve()`](../../../globals/Promise/resolve.mdx) call above — in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[Symbol.species]`](../../../globals/Promise/@@species.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/prototype/then.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.prototype.then() The **`then()`** method of a `Promise` object takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent `Promise` object, allowing you to [chain](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. ## Syntax ```js then(onFulfilled) then(onFulfilled, onRejected) then( (value) => { /* fulfillment handler */ }, (reason) => { /* rejection handler */ }, ) ``` ### Parameters - `onFulfilled` _**optional**_ - : A `Function` asynchronously called if the `Promise` is fulfilled. This function has one parameter, the _fulfillment value_. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` _**optional**_ - : A `Function` asynchronously called if the `Promise` is rejected. This function has one parameter, the _rejection reason_. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new `Promise` immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined`. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: the fulfillment/rejection of the promise returned by `then` will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by `then` will be the same as the resolved value of the promise returned by the handler. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) and [`Promise.prototype.finally`](../../../globals/Promise/prototype/finally.mdx) methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the [`Promise.prototype.catch`](../../../globals/Promise/prototype/catch.mdx) reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) — the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the [`Promise()`](../../../globals/Promise/Promise.mdx) constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`[Symbol.species]`](../../../globals/Promise/@@species.mdx) property. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/race.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.race() The **`Promise.race()`** method takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. ## Syntax ```js Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an `Array`) of promises. ### Return value A `Promise` that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/reject.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.reject() The **`Promise.reject()`** method returns a `Promise` object that is rejected with a given reason. ## Syntax ```js Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A `Promise` that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` [`Error`](../../globals/Error/Error.mdx). `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike [`Promise.resolve()`](../../globals/Promise/resolve.mdx), `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Promise/resolve.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Promise.resolve() The **`Promise.resolve()`** method "resolves" a given value to a `Promise`. If the value is a promise, that promise is returned; if the value is a [thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value. ## Syntax ```js Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A `Promise` that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](../../globals/Promise/Promise.mdx) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by the [resolver function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolver_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the resolver function receives another thenable object, it will be resolved agin, so that the eventual fulfillment value of the promise will never be thenable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/Proxy.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy() The **`Proxy()`** constructor is used to create `Proxy` objects. ## Syntax ```js new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - [`handler.apply()`](../../globals/Proxy/proxy/apply.mdx) - : A trap for a function call. - [`handler.construct()`](../../globals/Proxy/proxy/construct.mdx) - : A trap for the `new` operator. - [`handler.defineProperty()`](../../globals/Proxy/proxy/defineProperty.mdx) - : A trap for [`Object.defineProperty`](../../globals/Object/defineProperty.mdx). - [`handler.deleteProperty()`](../../globals/Proxy/proxy/deleteProperty.mdx) - : A trap for the `delete` operator. - [`handler.get()`](../../globals/Proxy/proxy/get.mdx) - : A trap for getting property values. - [`handler.getOwnPropertyDescriptor()`)}](../../globals/Proxy/proxy/getOwnPropertyDescriptor.mdx) - : A trap for [`Object.getOwnPropertyDescriptor`](../../globals/Object/getOwnPropertyDescriptor.mdx). - [`handler.getPrototypeOf()`](../../globals/Proxy/proxy/getPrototypeOf.mdx) - : A trap for [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). - [`handler.has()`](../../globals/Proxy/proxy/has.mdx) - : A trap for the `in` operator. - [`handler.isExtensible()`](../../globals/Proxy/proxy/isExtensible.mdx) - : A trap for [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx). - [`handler.ownKeys()`](../../globals/Proxy/proxy/ownKeys.mdx) - : A trap for [`Object.getOwnPropertyNames()`](../../globals/Object/getOwnPropertyNames.mdx) and [`Object.getOwnPropertySymbols()`](../../globals/Object/getOwnPropertySymbols.mdx). - [`handler.preventExtensions()`)}](../../globals/Proxy/proxy/preventExtensions.mdx) - : A trap for [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx). - [`handler.set()`](../../globals/Proxy/proxy/set.mdx) - : A trap for setting property values. - [`handler.setPrototypeOf()`](../../globals/Proxy/proxy/setPrototypeOf.mdx) - : A trap for [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.apply() The **`handler.apply()`** method is a trap for a function call. ## Syntax ```js new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description The **`handler.apply()`** method is a trap for a function call. ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - [`Function.prototype.apply()`](../../../globals/Function/prototype/apply.mdx) and [`Function.prototype.call()`](../../../globals/Function/prototype/call.mdx) - [`Reflect.apply()`](../../../globals/Reflect/apply.mdx) Or any other operation that invokes the `[[Call]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The `target` must be a callable itself. That is, it must be a function object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.construct() The **`handler.construct()`** method is a trap for the `new` operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid). ## Syntax ```js new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called, `p` above. ### Return value The `construct` method must return an object. ## Description The **`handler.construct()`** method is a trap for the `new` operator. ### Interceptions This trap can intercept these operations: - The `new` operator: `new myFunction(...args)` - [`Reflect.construct()`](../../../globals/Reflect/construct.mdx) Or any other operation that invokes the `[[Construct]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result must be an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.defineProperty() The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ## Syntax ```js new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a `Boolean` indicating whether or not the property has been successfully defined. ## Description The **`handler.defineProperty()`** method is a trap for [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx). ### Interceptions This trap can intercept these operations: - [`Object.defineProperty()`](../../../globals/Object/defineProperty.mdx), [`Object.defineProperties()`](../../../globals/Object/defineProperties.mdx) - [`Reflect.defineProperty()`](../../../globals/Reflect/defineProperty.mdx) Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.deleteProperty() The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ## Syntax ```js new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to delete. ### Return value The `deleteProperty()` method must return a `Boolean` indicating whether or not the property has been successfully deleted. ## Description The **`handler.deleteProperty()`** method is a trap for the `delete` operator. ### Interceptions This trap can intercept these operations: - The [`delete`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - [`Reflect.deleteProperty()`](../../../globals/Reflect/deleteProperty.mdx) Or any other operation that invokes the `[[Delete]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.get() The **`handler.get()`** method is a trap for getting a property value. ## Syntax ```js new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description The **`handler.get()`** method is a trap for getting a property value. ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - [`Reflect.get()`](../../../globals/Reflect/get.mdx) Or any other operation that invokes the `[[Get]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getOwnPropertyDescriptor() The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ## Syntax ```js new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description The **`handler.getOwnPropertyDescriptor()`** method is a trap for [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyDescriptor()`](../../../globals/Object/getOwnPropertyDescriptor.mdx) - [`Reflect.getOwnPropertyDescriptor()`](../../../globals/Reflect/getOwnPropertyDescriptor.mdx) Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.getPrototypeOf() The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` internal method. ## Syntax ```js new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - [`Object.getPrototypeOf()`](../../../globals/Object/getPrototypeOf.mdx) - [`Reflect.getPrototypeOf()`](../../../globals/Reflect/getPrototypeOf.mdx) - [`Object.prototype.isPrototypeOf()`](../../../globals/Object/prototype/isPrototypeOf.mdx) - `instanceof` Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.has() The **`handler.has()`** method is a trap for the `in` operator. ## Syntax ```js new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or `Symbol` of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description The **`handler.has()`** method is a trap for the `in` operator. ### Interceptions This trap can intercept these operations: - The [`in`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - [`Reflect.has()`](../../../globals/Reflect/has.mdx) Or any other operation that invokes the `[[HasProperty]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.isExtensible() The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ## Syntax ```js new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description The **`handler.isExtensible()`** method is a trap for [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx). ### Interceptions This trap can intercept these operations: - [`Object.isExtensible()`](../../../globals/Object/isExtensible.mdx) - [`Reflect.isExtensible()`](../../../globals/Reflect/isExtensible.mdx) Or any other operation that invokes the `[[IsExtensible]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.ownKeys() The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ## Syntax ```js new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description The **`handler.ownKeys()`** method is a trap for [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx). ### Interceptions This trap can intercept these operations: - [`Object.getOwnPropertyNames()`](../../../globals/Object/getOwnPropertyNames.mdx) - [`Object.getOwnPropertySymbols()`](../../../globals/Object/getOwnPropertySymbols.mdx) - [`Object.keys()`](../../../globals/Object/keys.mdx) - [`Reflect.ownKeys()`](../../../globals/Reflect/ownKeys.mdx) Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a `String` or a `Symbol`. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.preventExtensions() The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ## Syntax ```js new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description The **`handler.preventExtensions()`** method is a trap for [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx). ### Interceptions This trap can intercept these operations: - [`Object.preventExtensions()`](../../../globals/Object/preventExtensions.mdx) - [`Reflect.preventExtensions()`](../../../globals/Reflect/preventExtensions.mdx) - [`Object.seal()`](../../../globals/Object/seal.mdx) - [`Object.freeze()`](../../../globals/Object/freeze.mdx) Or any other operation that invokes the `[[PreventExtensions]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.set() The **`handler.set()`** method is a trap for setting a property value. ## Syntax ```js new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or `Symbol` of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) will be thrown. ## Description The **`handler.set()`** method is a trap for setting property value. ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - [`Reflect.set()`](../../../globals/Reflect/set.mdx) Or any other operation that invokes the `[[Set]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) exception. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/proxy/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # handler.setPrototypeOf() The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ## Syntax ```js new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description The **`handler.setPrototypeOf()`** method is a trap for [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx). ### Interceptions This trap can intercept these operations: - [`Object.setPrototypeOf()`](../../../globals/Object/setPrototypeOf.mdx) - [`Reflect.setPrototypeOf()`](../../../globals/Reflect/setPrototypeOf.mdx) Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Proxy/revocable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Proxy.revocable() The **`Proxy.revocable()`** static method creates a revocable `Proxy` object. ## Syntax ```js Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](../../globals/Proxy/Proxy.mdx) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](../../globals/Proxy/Proxy.mdx) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](https://developer.mozilla.org/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/RangeError/RangeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RangeError The **`RangeError()`** constructor creates an error when a value is not in the set or range of allowed values. ## Syntax ```js new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without `new`. Both create a new `RangeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableByteStreamController/prototype/byobRequest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # byobRequest The **`byobRequest`** read-only property of the `ReadableByteStreamController` interface returns the current BYOB request, or `null` if there are no pending requests. An underlying byte source should check this property, and use it to write data to the stream if it exists (rather than using `ReadableByteStreamController.enqueue()`). This will result in an efficient zero-byte transfer of the data to the consumer. ## Value A `ReadableStreamBYOBRequest` object instance, or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableByteStreamController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # close() The **`close()`** method of the `ReadableByteStreamController` interface closes the associated stream. This might be called by the underlying source when its data source has been exhausted/completed. > **Note:** Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. > However if there is an outstanding and partially written `byobRequest` when `close()` is called, the stream will be errored. ## Syntax ```js close() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, it is already closed, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableByteStreamController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # desiredSize The **`desiredSize`** read-only property of the`ReadableByteStreamController` interface returns the number of bytes required to fill the stream's internal queue to its "desired size". The value is used by the stream to indicate a preferred flow rate to the underlying source. Sources that support throttling or pausing their inflow of data (not all do!) should control the inflow such that `desiredSize` of the stream buffer is kept positive and as close to zero as possible. The `desiredSize` is used to apply backpressure from downstream consumers. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream has errored and `0` if it is closed. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableByteStreamController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # enqueue() The **`enqueue()`** method of the `ReadableByteStreamController` interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). This should only be used to transfer data to the queue when `byobRequest` is `null`. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existent, zero-length, or detached. It is also thrown if the stream has been closed. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableByteStreamController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # error() The **`error()`** method of the `ReadableByteStreamController` interface causes any future interactions with the associated stream to error with the specified reason. This is commonly called by an underlying source to surface an error from the interface where it gets its data (such as a file-read or socket error). It can also be called from elsewhere to trigger a stream error, for example if another part of the system that the stream relies on fails. ## Syntax ```js error(errorObject) ``` ### Parameters - `errorObject` - : Any object that you want future interactions to fail with. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableByteStreamController`, or the stream is not readable for some other reason. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStream/ReadableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream() The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. ## Syntax ```js new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) _**optional**_ - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a `ReadableStreamDefaultController` or a `ReadableByteStreamController`, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. - `cancel` (reason) _**optional**_ - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if `ReadableStream.cancel()` is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` _**optional**_ - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a `ReadableByteStreamController` capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a `ReadableStreamDefaultController`. - `autoAllocateChunkSize` _**optional**_ - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in `ReadableByteStreamController.byobRequest` when required. This must be set to enable zero-copy transfers to be used with a default `ReadableStreamDefaultReader`. If not set, a default reader will still stream data, but `ReadableByteStreamController.byobRequest` will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the `ReadableStream` object. ### Exceptions - `RangeError` - Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStream/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.cancel() The **`cancel()`** method of the `ReadableStream` interface returns a `Promise` that resolves when the stream is canceled. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to cancel is not a `ReadableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStream/prototype/getReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.getReader() The **`getReader()`** method of the `ReadableStream` interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js getReader() getReader(options) ``` ### Parameters - `options` _**optional**_ - : An object containing the following properties: - `mode` _**optional**_ - : A property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a `ReadableStreamBYOBReader` being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all — this is the default), which results in a `ReadableStreamDefaultReader` being created that can read individual chunks from a stream. ### Return value A `ReadableStreamDefaultReader` or `ReadableStreamBYOBReader` object instance, depending on the `mode` value. ### Exceptions - `RangeError` - : Thrown if the provided mode value is not `"byob"` or `undefined`. - `TypeError` - : Thrown if the stream you are trying to create a reader for is already locked, or not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.locked The **`locked`** read-only property of the `ReadableStream` interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using `ReadableStream.getReader()` and released using the reader's `releaseLock()` method. ## Value A `boolean` value indicating whether or not the readable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStream/prototype/pipeThrough.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeThrough() The **`pipeThrough()`** method of the `ReadableStream` interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A `TransformStream` (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a `TextDecoder`, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value The `readable` side of the `transformStream`. ### Exceptions - `TypeError` - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStream/prototype/pipeTo.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.pipeTo() The **`pipeTo()`** method of the `ReadableStream` interface pipes the current `ReadableStream` to a given `WritableStream` and returns a `Promise` that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally `lock` it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A `WritableStream` that acts as the final destination for the `ReadableStream`. - `options` _**optional**_ - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. ### Return value A `Promise` that resolves when the piping process has completed. ### Exceptions - `TypeError` - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStream/prototype/tee.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStream.tee() The **`tee()`** method of the `ReadableStream` interface [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) the current readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. This is useful for allowing two readers to read a stream sequentially or simultaneously, perhaps at different speeds. For example, you might do this in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. A teed stream will partially signal backpressure at the rate of the _faster_ consumer of the two `ReadableStream` branches, and unread data is enqueued internally on the slower consumed `ReadableStream` without any limit or backpressure. That is, when _both_ branches have an unread element in their internal queue, then the original `ReadableStream`'s controller's internal queue will start to fill up, and once its `ReadableStreamDefaultController.desiredSize", "desiredSize` ≤ 0 or byte stream controller `ReadableByteStreamController.desiredSize", "desiredSize` ≤ 0, then the controller will stop calling `pull(controller)` on the underlying source passed to `ReadableStream.ReadableStream", "new ReadableStream()`. If only one branch is consumed, then the entire body will be enqueued in memory. Therefore, you should not use the built-in `tee()` to read very large streams in parallel at different speeds. Instead, search for an implementation that fully backpressures to the speed of the _slower_ consumed branch. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. ## Syntax ```js tee() ``` ### Parameters None. ### Return value An `Array` containing two `ReadableStream` instances. ### Exceptions - `TypeError` - : Thrown if the source stream is not a `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamBYOBReader/ReadableStreamBYOBReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamBYOBReader() The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance. > **Note:** You generally wouldn't use this constructor manually; > instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`. ## Syntax ```js new ReadableStreamBYOBReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamBYOBReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamBYOBReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # cancel() The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. > **Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` __optional__ - : A human-readable reason for the cancellation. The underlying source may or may not use it. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamBYOBReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # closed The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamBYOBReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # read() The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`. The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled. If the stream is errored, the promise will be rejected with the relevant error object. If a chunk of data is supplied, the `value` property will contain a new view. This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data. Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable. The promise will fulfill with a `value: undefined` if the stream has been cancelled. In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost). The `done` property indicates whether or not more data is expected. The value is set `true` if the stream is closed or cancelled, and `false` otherwise. ## Syntax ```js read(view) ``` ### Parameters - `view` - : The view that data is to be read into. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The following are possible: - If a chunk is available and the stream is still active, the promise fulfills with an object of the form: ``` { value: theChunk, done: false } ``` `theChunk` is a view containing the new data. This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method. The original `view` will be detached and no longer usable. - If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above): ``` { value: theChunk, done: true } ``` - If the stream is cancelled, the promise fulfills with an object of the form: ``` { value: undefined, done: true } ``` In this case the backing memory is discarded. - If the stream throws an error, the promise rejects with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamBYOBReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # releaseLock() The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value `undefined`. ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBReader`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamBYOBRequest/prototype/respond.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respond() The **`respond()`** method of the `ReadableStreamBYOBRequest` interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the `ReadableStreamBYOBRequest.view`. After this method is called, the `view` will be transferred and no longer modifiable. ## Syntax ```js respond(bytesWritten) ``` ### Parameters - `bytesWritten` - : The number of bytes written into `ReadableStreamBYOBRequest.view`. ### Return value `undefined`. ### Exceptions - `TypeError` - : The request does not have an associated `ReadableByteStreamController` or the view buffer is not detached/cannot be transferred into. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamBYOBRequest/prototype/respondWithNewView.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # respondWithNewView() The **`respondWithNewView()`** method of the `ReadableStreamBYOBRequest` interface specifies a new view that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. The new view must be a `TypedArray` or a `DataView` that provides a view onto the same backing memory region as `ReadableStreamBYOBRequest.view`. After this method is called, the view that was passed into the method will be transferred and no longer modifiable. The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response. For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled. ## Syntax ```js respondWithNewView(view) ``` ### Parameters - `view` - : A `TypedArray` or a `DataView` that the consumer of the associated readable byte stream should write to instead of `ReadableStreamBYOBRequest.view`. This must be a view onto the same backing memory region as `ReadableStreamBYOBRequest.view` and occupy the same or less memory. Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view. ### Return value `undefined` ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached. It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream. - `RangeError` - : Thrown if the new `view` does not match the backing memory region of `ReadableStreamBYOBRequest.view`. For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamBYOBRequest/prototype/view.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # view The **`view`** getter property of the `ReadableStreamBYOBRequest` interface returns the current view. ## Value A typed array representing the destination region to which the controller can write generated data. `null` if the request has already been responded to, by calling `ReadableStreamBYOBRequest.respond()` or `ReadableStreamBYOBRequest.respondWithNewView()`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamDefaultController/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.close() The **`close()`** method of the `ReadableStreamDefaultController` interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use `ReadableStream.cancel()` or `ReadableStreamDefaultReader.cancel()`. ## Syntax ```js close() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `ReadableStreamDefaultController` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.enqueue() The **`enqueue()`** method of the `ReadableStreamDefaultController` interface enqueues a given chunk in the associated stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk to enqueue. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultController.error() The **`error()`** method of the `ReadableStreamDefaultController` interface causes any future interactions with the associated stream to error. > **Note:** The `error()` method can be called > more than once, and can be called when the stream is not readable. ## Syntax ```js error(e) ``` ### Parameters - `e` - : The error you want future interactions to fail with. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultController`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamDefaultReader/ReadableStreamDefaultReader.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader() The **`ReadableStreamDefaultReader()`** constructor creates and returns a `ReadableStreamDefaultReader` object instance. ## Syntax ```js new ReadableStreamDefaultReader(stream) ``` ### Parameters - `stream` - : The `ReadableStream` to be read. ### Return value An instance of the `ReadableStreamDefaultReader` object. ### Exceptions - `TypeError` - : Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamDefaultReader/prototype/cancel.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- ~ ReadableStreamDefaultReader.cancel() The **`cancel()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use `ReadableStreamDefaultController.close()`. > **Note:** If the reader is active, the > `cancel()` method behaves the same as that for the associated stream > (`ReadableStream.cancel()`). ## Syntax ```js cancel() cancel(reason) ``` ### Parameters - `reason` _**optional**_ - : A human-readable reason for the cancellation. This value may or may not be used. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, or the stream has no owner. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamDefaultReader/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.closed The **`closed`** read-only property of the `ReadableStreamDefaultReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamDefaultReader/prototype/read.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.read() The **`read()`** method of the `ReadableStreamDefaultReader` interface returns a `Promise` providing access to the next chunk in the stream's internal queue. ## Syntax ```js read() ``` ### Parameters None. ### Return value A `Promise`, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: - If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`. - If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`. - If the stream becomes errored, the promise will be rejected with the relevant error. ### Exceptions - `TypeError` - : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or `ReadableStreamDefaultReader.releaseLock()` is called (when there's a pending read request). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReadableStreamDefaultReader/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReadableStreamDefaultReader.releaseLock() The **`releaseLock()`** method of the `ReadableStreamDefaultReader` interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamDefaultReader.read()` method are immediately rejected with a `TypeError`. Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None (`undefined`). ### Exceptions - `TypeError` - : Thrown if the source object is not a `ReadableStreamDefaultReader`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/ReferenceError/ReferenceError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # ReferenceError The **`ReferenceError`** object represents an error when a non-existent variable is referenced. ## Syntax ```js new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without `new`. Both create a new `ReferenceError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/apply.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.apply() The static **`Reflect.apply()`** method calls a target function with arguments as specified. ## Syntax ```js Reflect.apply(target, thisArgument, argumentsList) ``` ### Parameters - `target` - : The target function to call. - `thisArgument` - : The value of `this` provided for the call to `target`. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. ### Return value The result of calling the given `target` function with the specified `this` value and arguments. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if the `target` is not callable. ## Description In ES5, you typically use the [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx) method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). ```js Function.prototype.apply.call(Math.floor, undefined, [1.75]); ``` With `Reflect.apply()` this becomes less verbose and easier to understand. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/construct.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.construct() The static **`Reflect.construct()`** method acts like the `new` operator, but as a function. It is equivalent to calling `new target(...args)`. It gives also the added option to specify a different prototype. ## Syntax ```js Reflect.construct(target, argumentsList) Reflect.construct(target, argumentsList, newTarget) ``` ### Parameters - `target` - : The target function to call. - `argumentsList` - : An array-like object specifying the arguments with which `target` should be called. - `newTarget` _**optional**_ - : The constructor whose prototype should be used. See also the [`new.target`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new.target) operator. If `newTarget` is not present, its value defaults to `target`. ### Return value A new instance of `target` (or `newTarget`, if present), initialized by `target` as a constructor with the given `argumentsList`. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` or `newTarget` are not constructors. ## Description `Reflect.construct()` allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) combined with the [`new` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/new).) ```js const obj = new Foo(...args); const obj = Reflect.construct(Foo, args); ``` ### Reflect.construct() vs Object.create() Prior to the introduction of `Reflect`, objects could be constructed using an arbitrary combination of constructor and prototype by using [`Object.create()`](../../globals/Object/create.mdx). ```js function OneClass() { this.name = "one"; } function OtherClass() { this.name = "other"; } // Calling this: const obj1 = Reflect.construct(OneClass, args, OtherClass); // ...has the same result as this: const obj2 = Object.create(OtherClass.prototype); OneClass.apply(obj2, args); console.log(obj1.name); // 'one' console.log(obj2.name); // 'one' console.log(obj1 instanceof OneClass); // false console.log(obj2 instanceof OneClass); // false console.log(obj1 instanceof OtherClass); // true console.log(obj2 instanceof OtherClass); // true // Another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { console.log(arguments[3]); } const obj1 = Reflect.construct(func1, ["I", "Love", "my", "country"]); ``` However, while the end result is the same, there is one important difference in the process. When using `Object.create()` and [`Function.prototype.apply()`](../../globals/Function/prototype/apply.mdx), the `new.target` operator will point to `undefined` within the function used as the constructor, since the `new` keyword is not being used to create the object. When invoking `Reflect.construct()`, on the other hand, the `new.target` operator will point to the `newTarget` parameter if supplied, or `target` if not. ```js function OneClass() { console.log("OneClass"); console.log(new.target); } function OtherClass() { console.log("OtherClass"); console.log(new.target); } const obj1 = Reflect.construct(OneClass, args); // Logs: // OneClass // function OneClass { ... } const obj2 = Reflect.construct(OneClass, args, OtherClass); // Logs: // OneClass // function OtherClass { ... } const obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args); // Logs: // OneClass // undefined ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/defineProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.defineProperty() The static **`Reflect.defineProperty()`** method is like [`Object.defineProperty()`](../../globals/Object/defineProperty.mdx) but returns a `Boolean`. ## Syntax ```js Reflect.defineProperty(target, propertyKey, attributes) ``` ### Parameters - `target` - : The target object on which to define the property. - `propertyKey` - : The name of the property to be defined or modified. - `attributes` - : The attributes for the property being defined or modified. ### Return value A `Boolean` indicating whether or not the property was successfully defined. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.defineProperty` method allows precise addition to or modification of a property on an object. For more details, see the [`Object.defineProperty`](../../globals/Object/defineProperty.mdx) which is similar. > **Note:** `Object.defineProperty` returns the > object or throws a [`TypeError`](../../globals/TypeError/TypeError.mdx) if the property has not been successfully > defined. `Reflect.defineProperty`, however, returns a `Boolean` > indicating whether or not the property was successfully defined. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/deleteProperty.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.deleteProperty() The static **`Reflect.deleteProperty()`** method allows to delete properties. It is like the [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete) as a function. ## Syntax ```js Reflect.deleteProperty(target, propertyKey) ``` ### Parameters - `target` - : The target object on which to delete the property. - `propertyKey` - : The name of the property to be deleted. ### Return value A `Boolean` indicating whether or not the property was successfully deleted. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.deleteProperty` method allows you to delete a property on an object. It returns a `Boolean` indicating whether or not the property was successfully deleted. It is almost identical to the non-strict [`delete` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.get() The static **`Reflect.get()`** method works like getting a property from an object (`target[propertyKey]`) as a function. ## Syntax ```js Reflect.get(target, propertyKey) Reflect.get(target, propertyKey, receiver) ``` ### Parameters - `target` - : The target object on which to get the property. - `propertyKey` - : The name of the property to get. - `receiver` _**optional**_ - : The value of `this` provided for the call to `target` if a getter is encountered. When used with `Proxy`, it can be an object that inherits from `target`. ### Return value The value of the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.get` method allows you to get a property on an object. It is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/getOwnPropertyDescriptor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getOwnPropertyDescriptor() The static **`Reflect.getOwnPropertyDescriptor()`** method is similar to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx). It returns a property descriptor of the given property if it exists on the object, `undefined` otherwise. ## Syntax ```js Reflect.getOwnPropertyDescriptor(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to get an own property descriptor for. ### Return value A property descriptor object if the property exists in `target` object; otherwise, [`undefined`](../../globals/undefined.mdx). ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getOwnPropertyDescriptor` method returns a property descriptor of the given property if it exists in the `target` object, [`undefined`](../../globals/undefined.mdx) otherwise. The only difference to [`Object.getOwnPropertyDescriptor()`](../../globals/Object/getOwnPropertyDescriptor.mdx) is how non-object targets are handled. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/getPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.getPrototypeOf() The static **`Reflect.getPrototypeOf()`** method is almost the same method as [`Object.getPrototypeOf()`](../../globals/Object/getPrototypeOf.mdx). It returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ## Syntax ```js Reflect.getPrototypeOf(target) ``` ### Parameters - `target` - : The target object of which to get the prototype. ### Return value The prototype of the given object. If there are no inherited properties, [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) is returned. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.getPrototypeOf` method returns the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.has() The static **`Reflect.has()`** method works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ## Syntax ```js Reflect.has(target, propertyKey) ``` ### Parameters - `target` - : The target object in which to look for the property. - `propertyKey` - : The name of the property to check. ### Return value A `Boolean` indicating whether or not the `target` has the property. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.has` method allows you to check if a property is in an object. It works like the [`in` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/in) as a function. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/isExtensible.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.isExtensible() The static **`Reflect.isExtensible()`** method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../../globals/Object/isExtensible.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible#difference_with_object.isextensible). ## Syntax ```js Reflect.isExtensible(target) ``` ### Parameters - `target` - : The target object which to check if it is extensible. ### Return value A `Boolean` indicating whether or not the target is extensible. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/ownKeys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.ownKeys() The static **`Reflect.ownKeys()`** method returns an array of the `target` object's own property keys. ## Syntax ```js Reflect.ownKeys(target) ``` ### Parameters - `target` - : The target object from which to get the own keys. ### Return value An `Array` of the `target` object's own property keys. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.ownKeys` method returns an array of the `target` object's own property keys. Its return value is equivalent to `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/preventExtensions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.preventExtensions() The static **`Reflect.preventExtensions()`** method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to [`Object.preventExtensions()`](../../globals/Object/preventExtensions.mdx), but with [some differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions#difference_with_object.preventextensions). ## Syntax ```js Reflect.preventExtensions(target) ``` ### Parameters - `target` - : The target object on which to prevent extensions. ### Return value A `Boolean` indicating whether or not the target was successfully set to prevent extensions. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.set() The static **`Reflect.set()`** method works like setting a property on an object. ## Syntax ```js Reflect.set(target, propertyKey, value) Reflect.set(target, propertyKey, value, receiver) ``` ### Parameters - `target` - : The target object on which to set the property. - `propertyKey` - : The name of the property to set. - `value` - : The value to set. - `receiver` _**optional**_ - : The value of `this` provided for the call to the setter for `propertyKey` on `target`. If provided and `target` does not have a setter for `propertyKey`, the property will be set on `receiver` instead. ### Return value A `Boolean` indicating whether or not setting the property was successful. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object`. ## Description The `Reflect.set` method allows you to set a property on an object. It does property assignment and is like the [property accessor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors) syntax as a function. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Reflect/setPrototypeOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Reflect.setPrototypeOf() The static **`Reflect.setPrototypeOf()`** method is the same method as [`Object.setPrototypeOf()`](../../globals/Object/setPrototypeOf.mdx), except for its return type. It sets the prototype (i.e., the internal `[[Prototype]]` property) of a specified object to another object or to [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null), and returns `true` if the operation was successful, or `false` otherwise. ## Syntax ```js Reflect.setPrototypeOf(target, prototype) ``` ### Parameters - `target` - : The target object of which to set the prototype. - `prototype` - : The object's new prototype (an object or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null)). ### Return value A `Boolean` indicating whether or not the prototype was successfully set. ### Exceptions A [`TypeError`](../../globals/TypeError/TypeError.mdx), if `target` is not an `Object` or if `prototype` is neither an object nor [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null). ## Description The `Reflect.setPrototypeOf` method changes the prototype (i.e. the value of the internal `[[Prototype]]` property) of the specified object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/Request.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request() The **`Request()`** constructor creates a new `Request` object. ## Syntax ```js new Request(input) new Request(input, options) ``` ### Parameters - `input` - : Defines the resource that you wish to fetch. This can either be: - A string containing the direct URL of the resource you want to fetch. - A `Request` object, effectively creating a copy. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. The default is `GET`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, a `ReadableStream` object, a [`Blob`](../../globals/Blob/Blob.mdx) object, or a [`FormData`](../../globals/FormData/FormData.mdx) object. - `backend` _**Fastly-specific**_ - `cacheOverride` _**Fastly-specific**_, see [`CacheOverride`](../../fastly:cache-override/CacheOverride/CacheOverride.mdx). - `cacheKey` _**Fastly-specific**_ - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.arrayBuffer() The **`arrayBuffer()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with an `ArrayBuffer`. ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.blob() The **`blob()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.body The read-only **`body`** property of the `Request` interface contains a `ReadableStream` with the body contents that have been added to the request. Note that a request using the `GET` or `HEAD` method cannot have a body and `null` is returned in these cases. ## Value A `ReadableStream` or `null`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.bodyUsed The read-only **`bodyUsed`** property of the `Request` interface is a boolean value that indicates whether the request body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/clone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.clone() The **`clone()`** method of the `Request` interface creates a copy of the current `Request` object. Like the underlying `ReadableStream.tee`` api, the `body` of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Beware when you construct a `Request` from a stream and then `clone` it. `clone()` throws a `TypeError` if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) If you intend to modify the request, you may prefer the `Request` constructor. ## Syntax ```js clone() ``` ### Parameters None. ### Return value A `Request` object, which is an exact copy of the `Request` that `clone()` was called on. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.formData() The **`formData()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the request body has already been used or if the request's method is `GET` or `HEAD`. - `SyntaxError` - : Thrown if the request's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.headers The **`headers`** read-only property of the `Request` interface contains the `Headers` object associated with the request. ## Value A `Headers` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.json() The **`json()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/method.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.method The **`method`** read-only property of the `Request` interface contains the request's method (`GET`, `POST`, etc.) ## Value A `String` indicating the method of the request. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Request` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Request instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Requests sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.text() The **`text()`** method of the `Request` interface reads the request body and returns it as a promise that resolves with a `String`. The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Request/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Request.url The **`url`** read-only property of the `Request` interface contains the URL of the request. ## Value A string indicating the URL of the request. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/Response.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response() The **`Response()`** constructor creates a new `Response` object. ## Syntax ```js new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` _**optional**_ - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - [`ArrayBuffer`](../../globals/ArrayBuffer/ArrayBuffer.mdx) - `TypedArray` - [`DataView`](../../globals/DataView/DataView.mdx) - [`ReadableStream`](../../globals/ReadableStream/ReadableStream.mdx) - [`URLSearchParams`](../../globals/URLSearchParams/URLSearchParams.mdx) - [`String`](../../globals/String/String.mdx) - string literal - [`Blob`](../../globals/Blob/Blob.mdx) - [`FormData`](../../globals/FormData/FormData.mdx) - `options` _**optional**_ - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response, e.g., `200`. - `statusText` - : The status message associated with the status code, e.g., `OK`. - `headers` - : Any headers you want to add to your response, contained within a [`Headers`](../../globals/Headers/Headers.mdx) object or object literal of [`String`](../../globals/String/String.mdx) key/value pairs. - `manualFramingHeaders`_: boolean_ _**optional**_ _**Fastly-specific**_ - : The default value is `false`, which means that the framing headers are automatically created based on the message body. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.arrayBuffer() The **`arrayBuffer()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ## Syntax ```js arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an [`ArrayBuffer`](../../../globals/ArrayBuffer/ArrayBuffer.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/blob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.blob() The **`blob()`** method of the [`Response`](../Response.mdx) interface takes a [`Response`](../Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `Blob`. ## Syntax ```js blob() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`Blob`](../../../globals/Blob/Blob.mdx). ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.body The **`body`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx) of the body contents. ## Value A [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx), or else `null` for any `Response` object [constructed](../../../globals/Response/Response.mdx) with a null `body` property, or for any actual HTTP response that has no body. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.bodyUsed The **`bodyUsed`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/formData.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.formData() The **`formData()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a `FormData` object. ## Syntax ```js formData() ``` ### Parameters None. ### Return value A `Promise` that resolves with a [`FormData`](../../../globals/FormData/FormData.mdx) object. ### Exceptions - `TypeError` - : Thrown if the response body has already been consumed. - `SyntaxError` - : Thrown if the response's content type is not `multipart/form-data` or `application/x-www-form-urlencoded`, or if the content cannot be parsed as form data. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/headers.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.headers The **`headers`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the [`Headers`](../../../globals/Headers/Headers.mdx) object associated with the response. ## Value A [`Headers`](../../Headers/Headers.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/ip.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ip The **`ip`** getter of the `Response` interface returns the IP address associated with the request, as either an IPv6 or IPv4 string. In the case where no IP address is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with an IP, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `string`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.json() The **`json()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A [`Promise`](../../../globals/Promise/Promise.mdx) that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/ok.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.ok The **`ok`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.port The **`port`** getter of the `Response` interface returns the port associated with the request, as a number. In the case where no port is available (say the response is cached, or was manually created), `undefined` will be returned. To ensure an origin request with a port, pass a [`CacheOverride`](../../../fastly:cache-override/CacheOverride/CacheOverride.mdx) value. ## Value `undefined` or `number`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/setManualFramingHeaders.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.setManualFramingHeaders() The **`setManualFramingHeaders()`** method of the `Response` interface controls how the framing headers should be determined. By default the framing headers are set to "automatic" mode, which means they are created based on the body of the associated Response instance. In "automatic" mode, a `Content-Length` is used when the size of the body can be determined before it is sent. Responses sent in streaming mode, where headers are sent immediately but the content of the body is streamed later, will receive a `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. In "manual" mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. You must ensure that those headers have correct values permitted by the [HTTP/1.1 specification](https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1). If the provided headers are not permitted by the specification, the headers will revert to "automatic" mode and a diagnostic message will be logged about what was wrong. If a `Content-Length` is permitted by the specification, but the value does not match the size of the actual body, the body will either be truncated (if it is too long), or the connection will be hung up early (if it is too short). ## Syntax ```js setManualFramingHeaders(manual) ``` ### Parameters - `manual` _: boolean_ - : Whether or not to use "manual" mode for the framing headers. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/status.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.status The **`status`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the HTTP status code of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/statusText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.statusText The **`statusText`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the status message corresponding to the HTTP status code in [`status`](../../../globals/Response/prototype/status.mdx). For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A [`String`](../../../globals/String/String.mdx) containing the HTTP status message associated with the response. The default value is "". ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.text() The **`text()`** method of the [`Response`](../../../globals/Response/Response.mdx) interface takes a [`Response`](../../../globals/Response/Response.mdx) stream and reads it to completion. It returns a promise that resolves with a [`String`](../../../globals/String/String.mdx). The response is _always_ decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A Promise that resolves with a [`String`](../../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/prototype/url.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.url The **`url`** read-only property of the [`Response`](../../../globals/Response/Response.mdx) interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Response/redirect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Response.redirect() The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL. ## Syntax ```js Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` __optional__ - : An optional status code for the response (e.g., `302`.) ### Return value A `Response` object. ### Exceptions - `RangeError` - : The specified status is not a redirect status. - `TypeError` - : The specified URL is invalid. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/RsaHashedImportParams/RsaHashedImportParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # RsaHashedImportParams The **`RsaHashedImportParams`** dictionary represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.importKey()`, when importing any RSA-based key pair. ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`. - `hash` - : A string representing the name of the digest function to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/@@species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # get Set\[Symbol.species] The **`Set[Symbol.species]`** accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get Symbol.species` was called. The return value is used to construct copied `Set` instances. ## Description The `Symbol.species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/Set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set() The **`Set` constructor** lets you create `Set` objects that store unique values of any type, whether [primitive values](https://developer.mozilla.org/docs/Glossary/Primitive) or object references. ## Syntax ```js new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype\[Symbol.iterator]() The **`[Symbol.iterator`** method of a `Set` object implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows sets to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the values of the set. The initial value of this property is the same function object as the initial value of the [`Set.prototype.values`](../../../globals/Set/prototype/values.mdx) property. ## Syntax ```js set[Symbol.iterator]() ``` ### Return value The same return value as [`Set.prototype.values()`](../../../globals/Set/prototype/values.mdx): a new iterable iterator object that yields the values of the set. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.add() The **`add()`** method inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. ## Syntax ```js add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/prototype/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.clear() The **`clear()`** method removes all elements from a `Set` object. ## Syntax ```js clear() ``` ### Return value [`undefined`](../../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.delete() The **`delete()`** method removes a specified value from a `Set` object, if it is in the set. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.entries() The **`entries()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. ## Syntax ```js entries() ``` ### Return value A new iterator object that contains an array of `[value, value]` for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.forEach() The **`forEach()`** method executes a provided function once for each value in the `Set` object, in insertion order. ## Syntax ```js // Arrow function forEach(() => { /* ... */ } ) forEach((value) => { /* ... */ } ) forEach((value, key) => { /* ... */ } ) forEach((value, key, set) => { /* ... */ } ) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function() { /* ... */ }) forEach(function(value) { /* ... */ }) forEach(function(value, key) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }) forEach(function(value, key, set) { /* ... */ }, thisArg) ``` ### Parameters - `callback` - : Function to execute for each element, taking three arguments: - `value`, `key` - : The current element being processed in the `Set`. As there are no keys in `Set`, the value is passed for both arguments. - `set` - : The `Set` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value [`undefined`](../../../globals/undefined.mdx). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the [Set](../../../globals/Set/Set.mdx). This is to make it consistent with other `forEach()` methods for [`Map.prototype.forEach()`](../../../globals/Map/prototype/forEach.mdx) and [`Array.prototype.forEach()`](../../../globals/Array/prototype/forEach.mdx). If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified value exists in a `Set` object or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.keys() The **`keys()`** method is an alias for the [`values()`](../../../globals/Set/prototype/values.mdx) method. ## Syntax ```js keys() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/prototype/size.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.size The **`size`** accessor property returns the number of (unique) elements in a [Set](../../../globals/Set/Set.mdx) object. ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Set/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Set.prototype.values() The **`values()`** method returns a new [Iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each element in the `Set` object in insertion order. > **Note:** The **`keys()`** method is an alias > for this method (for similarity with [Map](../../../globals/Map/Map.mdx) objects), hence the > `keys()` page redirecting here. It behaves exactly the same and returns > **values** of `Set` elements. ## Syntax ```js values() ``` ### Return value A new iterator object containing the values for each element in the given `Set`, in insertion order. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/String.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String() constructor The **`String`** constructor is used to create a new `String` object. When called instead as a function, it performs type conversion to a "primitive string" which is usually more useful. ## Syntax ```js new String(thing) String(thing) ``` > **Note:** `String()` can be called with or without `new`, but with different effects. See [Return value](#return-value). ### Parameters - `thing` - : Anything to be converted to a string. ### Return value When `String` is called as a constructor (with `new`), it creates a `String` object, which is **not** a primitive. When `String` is called as a function, it coerces the parameter to a string primitive. `Symbol` values would be converted to `"Symbol(description)"`, where `description` is the [description](../../globals/Symbol/prototype/description.mdx) of the Symbol, instead of throwing. > **Warning:** You should rarely find yourself using `String` as a constructor. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/fromCharCode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCharCode() The static **`String.fromCharCode()`** method returns a string created from the specified sequence of UTF-16 code units. ## Syntax ```js String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed. ### Return value A string of length `N` consisting of the `N` specified UTF-16 code units. ## Description This method returns a string and not a `String` object. Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/fromCodePoint.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.fromCodePoint() The static **`String.fromCodePoint()`** method returns a string created by using the specified sequence of code points. ## Syntax ```js String.fromCodePoint(num1) String.fromCodePoint(num1, num2) String.fromCodePoint(num1, num2, /* …, */ numN) ``` ### Parameters - `num1, ..., numN` - : A sequence of code points. ### Return value A string created by using the specified sequence of code points. ### Exceptions - A `RangeError` is thrown if an invalid Unicode code point is given (e.g. `"RangeError: NaN is not a valid code point"`). ## Description This method returns a string (and _not_ a `String` object). Because `fromCodePoint()` is a static method of `String`, you must call it as `String.fromCodePoint()`, rather than as a method of a `String` object you created. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/@@iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype\[Symbol.iterator]() The **`Symbol.iterator`** method of a string implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) loops. It returns an iterator that yields the Unicode code points of the string value as individual strings. ## Syntax ```js string[Symbol.iterator]() ``` ### Return value A new iterable iterator object that yields the Unicode code points of the string value as individual strings. ## Description Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved. ```js // "Backhand Index Pointing Right: Dark Skin Tone" [..."👉🏿"]; // ['👉', '🏿'] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [..."👨‍👦"]; // [ '👨', '‍', '👦' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/at.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.at() The **`at()`** method takes an integer value and returns a `('String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character. ## Syntax ```js at(index) ``` ### Parameters - `index` - : The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string. ### Return value `('String` consisting of the single UTF-16 code unit located at the specified position. Returns [`undefined`](../../../globals/undefined.mdx) if the given index can not be found. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/charAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charAt() The `String` object's **`charAt()`** method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. ## Syntax ```js charAt(index) ``` ### Parameters - `index` - : An integer between `0` and `str.length - 1`. If the `index` cannot be converted to the integer or no `index` is provided, the default is `0`, so the first character of `str` is returned. ### Return value A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of range, `charAt()` returns an empty string. ## Description Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character—in a string called `stringName` is `stringName.length - 1`. If the `index` you supply is out of this range, JavaScript returns an empty string. If no `index` is provided to `charAt()`, the default is `0`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/charCodeAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.charCodeAt() The **`charCodeAt()`** method returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be _the first part of a surrogate pair_ for the code point. If you want the entire code point value, use [`codePointAt()`](../../../globals/String/prototype/codePointAt.mdx). ## Syntax ```js charCodeAt(index) ``` ### Parameters - `index` - : An integer greater than or equal to `0` and less than the `length` of the string. If `index` is not a number, it defaults to `0`. ### Return value A number representing the UTF-16 code unit value of the character at the given `index`. If `index` is out of range, `charCodeAt()` returns `NaN`. ## Description Unicode code points range from `0` to `1114111` (`0x10FFFF`). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see [UTF-16 characters, Unicode codepoints, and grapheme clusters](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters).) > **Note:** `charCodeAt()` will always return a value that is > less than `65536`. This is because the higher code points are represented > by _a pair_ of (lower valued) "surrogate" pseudo-characters which are used to > comprise the real character. > > Because of this, in order to examine (or reproduce) the full character for individual > character values of `65536` or greater, for such characters, it is > necessary to retrieve not only `charCodeAt(i)`, but also > `charCodeAt(i+1)` (as if manipulating a string with two > letters), or to use `codePointAt(i)` instead. See examples 2 and > 3 (below). `charCodeAt()` returns `NaN` if the given index is less than `0`, or if it is equal to or greater than the `length` of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the `charCodeAt()` method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from `0` to `255`. The first `0` to `127` are a direct match of the ASCII character set. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/codePointAt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.codePointAt() The **`codePointAt()`** method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index. ## Syntax ```js codePointAt(pos) ``` ### Parameters - `pos` - : Position of an element in `str` to return the code point value from. ### Return value A decimal number representing the code point value of the character at the given `pos`. - If there is no element at `pos`, returns [`undefined`](../../../globals/undefined.mdx). - If the element at `pos` is a UTF-16 high surrogate, returns the code point of the surrogate _pair_. - If the element at `pos` is a UTF-16 low surrogate, returns _only_ the low surrogate code point. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/concat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.concat() The **`concat()`** method concatenates the string arguments to the calling string and returns a new string. ## Syntax ```js concat(str1) concat(str1, str2) concat(str1, str2, /* …, */ strN) ``` ### Parameters - `strN` - : One or more strings to concatenate to `str`. ### Return value A new string containing the combined text of the strings provided. ## Description The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. The `concat()` method is very similar to the [addition/string concatenation operators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Addition). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/endsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.endsWith() The **`endsWith()`** method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js endsWith(searchString) endsWith(searchString, endPosition) ``` ### Parameters - `searchString` - : The characters to be searched for at the end of `str`. Cannot be a regex. - `endPosition` _**optional**_ - : The end position at which `searchString` is expected to be found (the index of `searchString`'s last character plus 1). Defaults to `str.length`. ### Return value **`true`** if the given characters are found at the end of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/includes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.includes() The **`includes()`** method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate. ## Syntax ```js includes(searchString) includes(searchString, position) ``` ### Parameters - `searchString` - : A string to be searched for within `str`. Cannot be a regex. - `position` _**optional**_ - : The position within the string at which to begin searching for `searchString`. (Defaults to `0`.) ### Return value **`true`** if the search string is found anywhere within the given string; otherwise, **`false`** if not. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` is a regex. ## Description This method lets you determine whether or not a string includes another string. ### Case-sensitivity The `includes()` method is case sensitive. For example, the following expression returns `false`: ```js "Blue Whale".includes("blue"); // returns false ``` You can work around this constraint by transforming both the original string and the search string to all lowercase: ```js "Blue Whale".toLowerCase().includes("blue"); // returns true ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/indexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.indexOf() The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number. ## Syntax ```js indexOf(searchString) indexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".indexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".indexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`. - `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`. - `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`. - `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all. ### Return value The index of the first occurrence of `searchString` found, or `-1` if not found. #### Return value when using an empty search string Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument: ```js "hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 ``` However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length: ```js "hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 ``` In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 ``` The `indexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale".indexOf("blue"); // returns -1 ``` ### Checking occurrences When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`: ```js "Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/lastIndexOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.lastIndexOf() The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number. ## Syntax ```js lastIndexOf(searchString) lastIndexOf(searchString, position) ``` ### Parameters - `searchString` - : Substring to search for, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). If the method is called with no arguments, `searchString` is coerced to `"undefined"`. Therefore,`"undefined".lastIndexOf()` returns `0` — because the substring `"undefined"` is found at position `0` in the string `"undefined"`. But `"undefine".lastIndexOf()`, returns `-1` — because the substring `"undefined"` is not found in the string `"undefine"`. - `position` _**optional**_ - : The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`. - `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`. - `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`. - `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`. ### Return value The index of the last occurrence of `searchString` found, or `-1` if not found. ## Description Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1. ```js "canal".lastIndexOf("a"); // returns 3 "canal".lastIndexOf("a", 2); // returns 1 "canal".lastIndexOf("a", 0); // returns -1 "canal".lastIndexOf("x"); // returns -1 "canal".lastIndexOf("c", -5); // returns 0 "canal".lastIndexOf("c", 0); // returns 0 "canal".lastIndexOf(""); // returns 5 "canal".lastIndexOf("", 2); // returns 2 ``` ### Case-sensitivity The `lastIndexOf()` method is case sensitive. For example, the following expression returns `-1`: ```js "Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1 ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/length.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.length The **`length`** data property of a string contains the length of the string in UTF-16 code units. ## Value A non-negative integer. ## Description This property returns the number of code units in the string. JavaScript uses [UTF-16](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters) encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, [mathematical symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols), or obscure Chinese characters, you may need to account for the difference between code units and characters. The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for [precise integers](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer. - In V8 (used by Chrome and Node), the maximum length is 229 - 24 (\~1GiB). On 32-bit systems, the maximum length is 228 - 16 (\~512MiB). - In Firefox, the maximum length is 230 - 2 (\~2GiB). Before Firefox 65, the maximum length was 228 - 1 (\~512MiB). - In Safari, the maximum length is 231 - 1 (\~4GiB). For an empty string, `length` is 0. The static property `String.length` is unrelated to the length of strings. It's the [arity](../../../globals/Function/prototype/length.mdx) of the `String` function (loosely, the number of formal parameters it has), which is 1. Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its [iterator](../../../globals/String/prototype/@@iterator.mdx), which iterates by characters: ```js function getCharacterLength(str) { // The string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/localeCompare.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.localeCompare() The **`localeCompare()`** method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`. ## Syntax ```js localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.Collator` API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_. - `compareString` - : The string against which the `referenceStr` is compared. - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used. - `options` _**optional**_ - : An object adjusting the output format. Corresponds to the [`options`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor. In implementations without `Intl.Collator` support, this parameter is ignored. See the [`Intl.Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them. ### Return value A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent. In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`. ## Description Returns an integer indicating whether the `referenceStr` comes before, after or is equivalent to the `compareString`. - Negative when the `referenceStr` occurs before `compareString` - Positive when the `referenceStr` occurs after `compareString` - Returns `0` if they are equivalent > **Warning:** Do not rely on exact return values of `-1` or `1`! > > Negative and positive integer results vary between browsers (as well as between > browser versions) because the W3C specification only mandates negative and positive > values. Some browsers may return `-2` or `2`, or even some other > negative or positive value. ## Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an [`Intl.Collator`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) object and use the function provided by its [`compare()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) method. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.match() The **`match()`** method retrieves the result of matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions). ## Syntax ```js match(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.match`](../../../globals/Symbol/match.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.match` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. If you don't give any parameter and use the `match()` method directly, you will get an `Array` with an empty string: `[""]`, because this is equivalent to `match(/(?:)/)`. ### Return value An `Array` whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) if no matches are found. - If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as `RegExp.prototype.exec()` (an array with some extra properties). ## Description The implementation of `String.prototype.match` itself is very simple — it simply calls the `Symbol.match` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). - If you need to know if a string matches a regular expression `RegExp`, use `RegExp.prototype.test()`. - If you only want the first match found, you might want to use `RegExp.prototype.exec()` instead. - If you want to obtain capture groups and the global flag is set, you need to use `RegExp.prototype.exec()` or [`String.prototype.matchAll()`](../../../globals/String/prototype/matchAll.mdx) instead. For more information about the semantics of `match()` when a regex is passed, see [`RegExp.prototype[@@match]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.matchAll() The **`matchAll()`** method returns an iterator of all results matching a string against a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions), including [capturing groups](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences). ## Syntax ```js matchAll(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.matchAll`](../../../globals/Symbol/matchAll.mdx) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`. If `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Return value An [iterable iterator](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of `RegExp.prototype.exec()`. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `regexp` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from [`RegExp.prototype[@@matchAll]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/padEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padEnd() The **`padEnd()`** method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. ## Syntax ```js padEnd(targetLength) padEnd(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within `targetLength`, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is " " (`U+0020`). ### Return value A `String` of the specified `targetLength` with the `padString` applied at the end of the current `str`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/padStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.padStart() The **`padStart()`** method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. ## Syntax ```js padStart(targetLength) padStart(targetLength, padString) ``` ### Parameters - `targetLength` - : The length of the resulting string once the current `str` has been padded. If the value is less than `str.length`, then `str` is returned as-is. - `padString` _**optional**_ - : The string to pad the current `str` with. If `padString` is too long to stay within the `targetLength`, it will be truncated from the end. The default value is the unicode "space" character (U+0020). ### Return value A `String` of the specified `targetLength` with `padString` applied from the start. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/repeat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.repeat() The **`repeat()`** method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. ## Syntax ```js repeat(count) ``` ### Parameters - `count` - : An integer between `0` and [`+Infinity`](../../../globals/Number/POSITIVE_INFINITY.mdx), indicating the number of times to repeat the string. ### Return value A new string containing the specified number of copies of the given string. ### Exceptions - Throws a `RangeError` if repeat count is negative. - Throws a `RangeError` if repeat count is infinity or overflows maximum string size. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replace() The **`replace()`** method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged. ## Syntax ```js replace(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. - `replacement` - : Can be a string or a function. - If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying-a-string-as-the-replacement) section below. - If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying-a-function-as-the-replacement) section below. ### Return value A new string, with one, some, or all matches of the pattern replaced by the specified replacement. ## Description This method does not mutate the string value it's called on. It returns a new string. A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead. If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). If the `pattern` is an empty string, the replacement is prepended to the start of the string. ```js "xxx".replace("", "_"); // "_xxx" ``` A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ### Specifying a string as the replacement The replacement string can include the following special replacement patterns: | Pattern | Inserts | | --------- | ---------------------------------------------------------------------------------------------- | | `$$` | Inserts a `"$"`. | | `$&` | Inserts the matched substring. | | `` $` `` | Inserts the portion of the string that precedes the matched substring. | | `$'` | Inserts the portion of the string that follows the matched substring. | | `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. | | `$` | Inserts the named capturing group where `Name` is the group name. | `$n` and `$` are only available if the `pattern` argument is a `RegExp` object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string. ```js "foo".replace(/(f)/, "$2"); // "$2oo"; the regex doesn't have the second group "foo".replace("f", "$1"); // "$1oo"; the pattern is a string, so it doesn't have any groups "foo".replace(/(f)|(g)/, "$2"); // "oo"; the second group exists but isn't matched ``` ### Specifying a function as the replacement You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. > **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function. The function has the following signature: ```js function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) { return replacement; } ``` The arguments to the function are as follows: - `match` - : The matched substring. (Corresponds to `$&` above.) - `p1, p2, …, pN` - : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a `RegExp` object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`. - `offset` - : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`. - `string` - : The whole string being examined. - `groups` - : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group. The exact number of arguments depends on whether the first argument is a `RegExp` object — and, if so, how many capture groups it has. The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is non-digits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(" - "); } const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newString); // abc - 12345 - #$*% ``` The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/replaceAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.replaceAll() The **`replaceAll()`** method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a `RegExp`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged. ## Syntax ```js replaceAll(pattern, replacement) ``` ### Parameters - `pattern` - : Can be a string or an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method — the typical example being a [regular expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string. If `pattern` is a regex, then it must have the global (`g`) flag set, or a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. - `replacement` - : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx). ### Return value A new string, with all matches of a pattern replaced by a replacement. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : Thrown if the `pattern` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`). ## Description This method does not mutate the string value it's called on. It returns a new string. Unlike [`String.prototype.replace()`](../../../globals/String/prototype/replace.mdx), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics. ```js function unsafeRedactName(text, name) { return text.replace(new RegExp(name, "g"), "[REDACTED]"); } function safeRedactName(text, name) { return text.replaceAll(name, "[REDACTED]"); } const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." ``` If `pattern` is an object with a [`Symbol.replace`](../../../globals/Symbol/replace.mdx) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `Symbol.replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global). If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`String.prototype.split()`](../../../globals/String/prototype/split.mdx) behavior. ```js "xxx".replaceAll("", "_"); // "_x_x_x_" ``` For more information about how regex properties (especially the [sticky](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.search() The **`search()`** method executes a search for a match between a regular expression and this `String` object. ## Syntax ```js search(regexp) ``` ### Parameters - `regexp` - : A regular expression object, or any object that has a [`Symbol.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search) method. If `regexp` is not a `RegExp` object and does not have a `Symbol.search` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp)`. ### Return value The index of the first match between the regular expression and the given string, or `-1` if no match was found. ## Description The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see [`RegExp.prototype[@@search]()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search). When you want to know whether a pattern is found, and _also_ know its index within a string, use `search()`. - If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean. - If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/slice.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.slice() The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string. ## Syntax ```js slice(indexStart) slice(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the extracted section of the string. ## Description `slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. `slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`). - If `indexStart >= str.length`, an empty string is returned. - If `indexStart < 0`, the index is counted from the end of the string. More formally, in this case, the substring starts at `max(indexStart + str.length, 0)`. - If `indexStart` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), it's treated as `0`. - If `indexEnd` is omitted, undefined, or cannot be converted to a number (using [`Number()`](../../../globals/Number/Number.mdx)), or if `indexEnd >= str.length`, `slice()` extracts to the end of the string. - If `indexEnd < 0`, the index is counted from the end of the string. More formally, in this case, the substring ends at `max(indexEnd + str.length, 0)`. - If `indexEnd <= indexStart` after normalizing negative values (i.e. `indexEnd` represents a character that's before `indexStart`), an empty string is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.split() The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. ## Syntax ```js split() split(separator) split(separator, limit) ``` ### Parameters - `separator` _**optional**_ - : The pattern describing where each split should occur. Can be a string or an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method — the typical example being a regular expression. If undefined, the original target string is returned wrapped in an array. - `limit` _**optional**_ - : A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all. - The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached. - If `limit` is `0`, `[]` is returned. ### Return value An `Array` of strings, split at each point where the `separator` occurs in the given string. ## Description If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string. If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string. > **Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator`. > **Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by _user-perceived characters_ ([grapheme clusters](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) or unicode characters (codepoints), but by UTF-16 codeunits. This destroys [surrogate pairs](https://unicode.org/faq/utf_bom.html#utf16-2). See ["How do you get a string to a character array in JavaScript?" on StackOverflow](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402). If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode codepoints depends on if the [`u`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) flag is set. ```js "😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] ``` If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's [`Symbol.split`](../../../globals/Symbol/split.mdx) method. If `separator` is an object with a [`Symbol.split`](../../../globals/Symbol/split.mdx) method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`. Any other value will be coerced to a string before being used as separator. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/startsWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.startsWith() The **`startsWith()`** method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate. ## Syntax ```js startsWith(searchString) startsWith(searchString, position) ``` ### Parameters - `searchString` - : The characters to be searched for at the start of this string. Cannot be a regex. - `position` _**optional**_ - : The start position at which `searchString` is expected to be found (the index of `searchString`'s first character). Defaults to `0`. ### Return value **`true`** if the given characters are found at the beginning of the string; otherwise, **`false`**. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : If `searchString` [is a regex](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). ## Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/substr.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substr() The **`substr()`** method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. > **Note:** `substr()` is not part of the main ECMAScript specification — it's defined in [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods. ## Syntax ```js substr(start) substr(start, length) ``` ### Parameters - `start` - : The index of the first character to include in the returned substring. - `length` _**optional**_ - : The number of characters to extract. ### Return value A new string containing the specified part of the given string. ## Description A string's `substr()` method extracts `length` characters from the string, counting from the `start` index. - If `start >= str.length`, an empty string is returned. - If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`. - If `start` is omitted or [`undefined`](../../../globals/undefined.mdx), it's treated as `0`. - If `length` is omitted or [`undefined`](../../../globals/undefined.mdx), or if `start + length >= str.length`, `substr()` extracts characters to the end of the string. - If `length < 0`, an empty string is returned. - For both `start` and `length`, [`NaN`](../../../globals/NaN.mdx) is treated as `0`. Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/substring.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.substring() The **`substring()`** method returns the part of the `string` from the start index up to and excluding the end index, or to the end of the string if no end index is supplied. ## Syntax ```js substring(indexStart) substring(indexStart, indexEnd) ``` ### Parameters - `indexStart` - : The index of the first character to include in the returned substring. - `indexEnd` _**optional**_ - : The index of the first character to exclude from the returned substring. ### Return value A new string containing the specified part of the given string. ## Description `substring()` extracts characters from `indexStart` up to _but not including_ `indexEnd`. In particular: - If `indexEnd` is omitted, `substring()` extracts characters to the end of the string. - If `indexStart` is equal to `indexEnd`, `substring()` returns an empty string. - If `indexStart` is greater than `indexEnd`, then the effect of `substring()` is as if the two arguments were swapped; see example below. Any argument value that is less than `0` or greater than `str.length` is treated as if it were `0` and `str.length`, respectively. Any argument value that is [`NaN`](../../../globals/NaN.mdx) is treated as if it were `0`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/toLocaleLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleLowerCase() The **`toLocaleLowerCase()`** method returns the calling string value converted to lower case, according to any locale-specific case mappings. ## Syntax ```js toLocaleLowerCase() toLocaleLowerCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleLowerCase()` method returns the value of the string converted to lower case according to any locale-specific case mappings. `toLocaleLowerCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toLowerCase()`](../../../globals/String/prototype/toLowerCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/toLocaleUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLocaleUpperCase() The **`toLocaleUpperCase()`** method returns the calling string value converted to upper case, according to any locale-specific case mappings. ## Syntax ```js toLocaleUpperCase() toLocaleUpperCase(locales) ``` ### Parameters - `locales` _**optional**_ - : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation). ### Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. ### Exceptions - A [`RangeError`](../../../globals/RangeError/RangeError.mdx) ("invalid language tag: xx_yy") is thrown if a `locale` argument isn't a valid language tag. - A [`TypeError`](../../../globals/TypeError/TypeError.mdx) ("invalid element in locales argument") is thrown if an array element isn't of type string. ## Description The `toLocaleUpperCase()` method returns the value of the string converted to upper case according to any locale-specific case mappings. `toLocaleUpperCase()` does not affect the value of the string itself. In most cases, this will produce the same result as [`String.prototype.toUpperCase()`](../../../globals/String/prototype/toUpperCase.mdx), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return `false`: `x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/toLowerCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toLowerCase() The **`toLowerCase()`** method returns the calling string value converted to lower case. ## Syntax ```js toLowerCase() ``` ### Return value A new string representing the calling string converted to lower case. ## Description The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toString() The **`toString()`** method returns a string representing the specified string value. ## Syntax ```js toString() ``` ### Return value A string representing the specified string value. ## Description The `String` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as [`String.prototype.valueOf()`](../../../globals/String/prototype/valueOf.mdx). The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to string values. Because `String` doesn't have a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, JavaScript calls the `toString()` method automatically when a `String` _object_ is used in a context expecting a string, such as in a [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). However, String _primitive_ values do not consult the `toString()` method to be [coerced to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — since they are already strings, no conversion is performed. ```js String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); // "foo" console.log(`${new String("foo")}`); // "Overridden" ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/toUpperCase.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.toUpperCase() The **`toUpperCase()`** method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). ## Syntax ```js toUpperCase() ``` ### Return value A new string representing the calling string converted to upper case. ### Exceptions - [`TypeError`](../../../globals/TypeError/TypeError.mdx) - : When called on [`null`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](../../../globals/undefined.mdx), for example, `String.prototype.toUpperCase.call(undefined)`. ## Description The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/trim.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trim() The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use [`String.prototype.trimStart()`](../../../globals/String/prototype/trimStart.mdx) or [`String.prototype.trimEnd()`](../../../globals/String/prototype/trimEnd.mdx). ## Syntax ```js trim() ``` ### Return value A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/trimEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimEnd() The **`trimEnd()`** method removes whitespace from the end of a string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method. ## Syntax ```js trimEnd() trimRight() ``` ### Return value A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with [`String.prototype.pedEnd()`](../../../globals/String/prototype/trim.mdx), when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimRight.name === "trimEnd"; ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/trimStart.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.trimStart() The **`trimStart()`** method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method. ## Syntax ```js trimStart() trimLeft() ``` ### Return value A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`). ### Aliasing After [`String.prototype.trim()`](../../../globals/String/prototype/trim.mdx) was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with [`String.prototype.padEnd()`](../../../globals/String/prototype/padEnd.mdx), when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means: ```js String.prototype.trimLeft.name === "trimStart"; ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a `String` object. ## Syntax ```js valueOf() ``` ### Return value A string representing the primitive value of a given `String` object. ## Description The `valueOf()` method of `String` returns the primitive value of a `String` object as a string data type. This value is equivalent to [`String.prototype.toString()`](../../../globals/String/prototype/toString.mdx). This method is usually called internally by JavaScript and not explicitly in code. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/String/raw.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # String.raw() The static **`String.raw()`** method is a tag function of [template literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not. ## Syntax ```js String.raw(strings, ...substitutions) String.raw`templateString` ``` ### Parameters - `strings` - : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings. - `...substitutions` - : Contains substitution values. - `templateString` - : A [template literal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`). ### Return value The raw string form of a given template literal. ### Exceptions - [`TypeError`](../../globals/TypeError/TypeError.mdx) - : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`. ## Description In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)). `String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code. > **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag) for how to implement this. If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/SubtleCrypto/SubtleCrypto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SubtleCrypto The **`SubtleCrypto`** interface provides a number of low-level cryptographic functions. Access to the features of `SubtleCrypto` is obtained through the [`crypto.subtle`](../crypto/subtle.mdx) property. > **Warning:** This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. > > Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. > > Errors in security system design and implementation can make the security of the system completely ineffective. > > Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/SubtleCrypto/prototype/digest.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # digest() The **`digest()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digest of the given data. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a [`Promise`](../../Promise/Promise.mdx) which will be fulfilled with the digest. ## Syntax ```js digest(algorithm, data) ``` ### Parameters - `algorithm` - : This may be a string or an object with a single property `name` that is a string. The string names the hash function to use. Supported values are: - `"MD5"` (but don't use this in cryptographic applications) - `"SHA-1"` (but don't use this in cryptographic applications) - `"SHA-256"` - `"SHA-384"` - `"SHA-512"`. - `data` - : An `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the data to be digested. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with an `ArrayBuffer` containing the digest. ## Supported algorithms Digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. They have a variety of applications in cryptography. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/SubtleCrypto/prototype/importKey.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # importKey() The **`importKey()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface imports a key: that is, it takes as input a key in an external, portable format and gives you a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object that you can use. The function accepts several import formats: see [Supported formats](#supported-formats) for details. ## Syntax ```js importKey(format, keyData, algorithm, extractable, keyUsages) ``` ### Parameters - `format` - : A string describing the data format of the key to import. It can be one of the following: - `raw`: [Raw](#raw) format. - `jwk`: [JSON Web Key](#json-web-key) format. - `keyData` - : An `ArrayBuffer`, a TypedArray, a `DataView`, or a `JSONWebKey` object containing the key in the given format. - `algorithm` - : An object defining the type of key to import and providing extra algorithm-specific parameters. - For RSASSA-PKCS1-v1_5: Pass an [`RsaHashedImportParams`](../../RsaHashedImportParams/RsaHashedImportParams.mdx) object. - For HMAC: Pass an [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object. - For ECDSA: Pass an [`EcKeyImportParams`](../../EcKeyImportParams/EcKeyImportParams.mdx) object. - `extractable` - : A boolean value indicating whether it will be possible to export the key. - `keyUsages` - : An `Array` indicating what can be done with the key. Possible array values are: - `encrypt`: The key may be used to encrypt messages. - `decrypt`: The key may be used to decrypt messages. - `sign`: The key may be used to sign messages. - `verify`: The key may be used to verify signatures. - `deriveKey`: The key may be used in deriving a new key. - `deriveBits`: The key may be used in deriving bits. - `wrapKey`: The key may be used to wrap a key. - `unwrapKey`: The key may be used to unwrap a key. ### Return value A [`Promise`](../../Promise/Promise.mdx) that fulfills with the imported key as a [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object. ### Exceptions The promise is rejected when one of the following exceptions is encountered: - `SyntaxError` - : Raised when `keyUsages` is empty but the unwrapped key is of type `secret` or `private`. - `TypeError` - : Raised when trying to use an invalid format or if the `keyData` is not suited for that format. ## Supported formats This API currently supports one key import/export format: JSON Web Key. ### Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an `ArrayBuffer` containing the raw bytes for the key. ### JSON Web Key You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517). It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): ```json { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/SubtleCrypto/prototype/sign.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # sign() The **`sign()`** method of the [`SubtleCrypto`](../SubtleCrypto.mdx) interface generates a digital signature. It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a `Promise` which will be fulfilled with the signature. You can use the corresponding [`verify()`](./verify.mdx) method to verify the signature. ## Syntax ```js sign(algorithm, key, data) ``` ### Parameters - `algorithm` - : A string or object that specifies the signature algorithm to use and its parameters: - To use [RSASSA-PKCS1-v1_5](#rsassa-pkcs1-v1_5), pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use [HMAC](#hmac), pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) object containing the key to be used for signing. If `algorithm` identifies a public-key cryptosystem, this is the private key. - `data` - : An `ArrayBuffer`, a TypedArray or a `DataView` object containing the data to be signed. ### Return value A `Promise` that fulfills with an `ArrayBuffer` containing the signature. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. ## Supported algorithms ### RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447). ### HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the [FIPS 198-1 standard](https://csrc.nist.gov/csrc/media/publications/fips/198/1/final/documents/fips-198-1_final.pdf). The digest algorithm to use is specified in the [`HmacImportParams`](../../HmacImportParams/HmacImportParams.mdx) object that you pass into [`SubtleCrypto.importKey()`](./importKey.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/SubtleCrypto/prototype/verify.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # verify() The **`verify()`** method verifies a digital signature. It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. It returns a `Promise` which will be fulfilled with a boolean value indicating whether the signature is valid. ## Syntax ```js verify(algorithm, key, signature, data) ``` ### Parameters - `algorithm` - : A string or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding [`sign()`](./sign.mdx) call. - To use RSASSA-PKCS1-v1_5, pass the string `"RSASSA-PKCS1-v1_5"` or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`. - To use HMAC, pass the string `"HMAC"` or an object of the form `{ "name": "HMAC" }`. - `key` - : A [`CryptoKey`](../../CryptoKey/CryptoKey.mdx) containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. - `signature` - : A `ArrayBuffer` containing the signature to verify. - `data` - : A `ArrayBuffer` containing the data whose signature is to be verified. ### Return value A `Promise` that fulfills with a boolean value: `true` if the signature is valid, `false` otherwise. ### Exceptions The promise is rejected when the following exception is encountered: - `InvalidAccessError` - : Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ## Supported algorithms The `verify()` method supports the same algorithms as the [`sign()`](./sign.mdx) method. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/Symbol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol() The `Symbol()` constructor returns a value of type **symbol**, but is incomplete as a constructor because it does not support the syntax "`new Symbol()`" and it is not intended to be subclassed. It may be used as the value of an [`extends`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/extends) clause of a `class` definition but a [`super`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/super) call to it will cause an exception. ## Syntax ```js Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `description` _**optional**_ - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/asyncIterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.asyncIterator The **`Symbol.asyncIterator`** well-known symbol specifies the default [async iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) for an object. If this property is set on an object, it is an async iterable and can be used in a [`for await...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of) loop. ## Value The well-known symbol `Symbol.asyncIterator`. ## Description The `Symbol.asyncIterator` symbol is a builtin symbol that is used to access an object's `Symbol.asyncIterator` method. In order for an object to be async iterable, it must have a `Symbol.asyncIterator` key. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/for.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.for() The **`Symbol.for(key)`** method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. ## Syntax ```js Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/hasInstance.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.hasInstance The **`Symbol.hasInstance`** well-known symbol is used to determine if a constructor object recognizes an object as its instance. The `instanceof` operator's behavior can be customized by this symbol. ## Value The well-known symbol `Symbol.hasInstance`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/isConcatSpreadable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.isConcatSpreadable The **`Symbol.isConcatSpreadable`** well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../../globals/Array/prototype/concat.mdx) method. ## Value The well-known symbol `Symbol.isConcatSpreadable`. ## Description The `Symbol.isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/iterator.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.iterator The well-known **`Symbol.iterator`** symbol specifies the default iterator for an object. Used by [`for...of`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of). ## Value The well-known symbol `Symbol.iterator`. ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `Symbol.iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as `Object`) do not. The built-in types with a `Symbol.iterator` method are: - [`Array.prototype[Symbol.iterator]()`](../../globals/Array/prototype/@@iterator.mdx) - [`String.prototype[Symbol.iterator]()`](../../globals/String/prototype/@@iterator.mdx) - [`Map.prototype[Symbol.iterator]()`](../../globals/Map/prototype/@@iterator.mdx) - [`Set.prototype[Symbol.iterator]()`](../../globals/Set/prototype/@@iterator.mdx) See also [Iteration protocols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/keyFor.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.keyFor() The **`Symbol.keyFor(sym)`** method retrieves a shared symbol key from the global symbol registry for the given symbol. ## Syntax ```js Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/match.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.match The **`Symbol.match`** well-known symbol specifies the matching of a regular expression against a string. This function is called by the [`String.prototype.match()`](../../globals/String/prototype/match.mdx) method. For more information, see `RegExp.prototype[Symbol.match]()` and [`String.prototype.match()`](../../globals/String/prototype/match.mdx). ## Value The well-known symbol `Symbolmatch`. ## Description This function is also used to identify [if objects have the behavior of regular expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods [`String.prototype.startsWith()`](../../globals/String/prototype/startsWith.mdx), [`String.prototype.endsWith()`](../../globals/String/prototype/endsWith.mdx) and [`String.prototype.includes()`](../../globals/String/prototype/includes.mdx), check if their first argument is a regular expression and will throw a [`TypeError`](../../globals/TypeError/TypeError.mdx) if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/matchAll.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.matchAll The **`Symbol.matchAll`** well-known symbol specifies the method that returns an iterator, that yields matches of the regular expression against a string. This function is called by the [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx) method. For more information, see `RegExp.prototype[Symbol.matchAll]()` and [`String.prototype.matchAll()`](../../globals/String/prototype/matchAll.mdx). ## Value The well-known symbol `Symbol.matchAll`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/prototype/@@toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype[Symbol.toPrimitive] The **`[Symbol.toPrimitive]()`** method converts a Symbol object to a primitive value. ## Syntax ```js Symbol()[Symbol.toPrimitive](hint) ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `[Symbol.toPrimitive]()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[Symbol.toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[Symbol.toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/prototype/description.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.description The read-only **`description`** property is a string returning the optional description of `Symbol` objects. ## Description `Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.toString() The **`toString()`** method returns a string representing the specified symbol value. ## Syntax ```js toString() ``` ### Return value A string representing the specified symbol value. ## Description The `Symbol` object overrides the `toString` method of `Object`; it does not inherit [`Object.prototype.toString()`](../../../globals/Object/prototype/toString.mdx). For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [`Symbol.prototype.description`](../../../globals/Symbol/prototype/description.mdx). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a [`TypeError`](../../../globals/TypeError/TypeError.mdx) for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[Symbol.toPrimitive]()`](../../../globals/Symbol/toPrimitive.mdx) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[Symbol.toPrimitive]()` returns a symbol primitive, and symbol primitives throw a [`TypeError`](../../../globals/TypeError/TypeError.mdx) when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/prototype/valueOf.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.prototype.valueOf() The **`valueOf()`** method returns the primitive value of a Symbol object. ## Syntax ```js valueOf() ``` ### Return value The primitive value of the specified `Symbol` object. ## Description The `valueOf()` method of `Symbol` returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/replace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.replace The **`Symbol.replace`** well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx) method. For more information, see `RegExp.prototype[Symbol.replace]()` and [`String.prototype.replace()`](../../globals/String/prototype/replace.mdx). ## Value The well-known symbol `Symbol.replace`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.search The **`Symbol.search`** well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the [`String.prototype.search()`](../../globals/String/prototype/search.mdx) method. For more information, see `RegExp.prototype[Symbol.search]()` and [`String.prototype.search()`](../../globals/String/prototype/search.mdx). ## Value The well-known symbol `Symbol.search`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/species.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.species The well-known symbol **`Symbol.species`** specifies a function-valued property that the constructor function uses to create derived objects. > **Warning:** The existence of `Symbol.species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Value The well-known symbol `Symbol.species`. ## Description The `Symbol.species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as [`Array.prototype.map()`](../../globals/Array/prototype/map.mdx). the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. All built-in implementations of `Symbol.species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/split.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.split The **`Symbol.split`** well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the [`String.prototype.split()`](../../globals/String/prototype/split.mdx) method. For more information, see `RegExp.prototype[Symbol.split]()` and [`String.prototype.split()`](../../globals/String/prototype/split.mdx). ## Value The well-known symbol `Symbol.split`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/toPrimitive.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toPrimitive The **`Symbol.toPrimitive`** well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) algorithms. ## Value The well-known symbol `Symbol.toPrimitive`. ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[Symbol.toPrimitive]()`](../../globals/Symbol/prototype/@@toPrimitive.mdx) does). The language does not enforce alignment between the `hint` and the result type, although `[Symbol.toPrimitive]()` must return a primitive, or a [`TypeError`](../../globals/TypeError/TypeError.mdx) is thrown. Objects without the `Symbol.toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#type_coercion) section. `Symbol.toPrimitive` allows full control over the primitive conversion process. For example, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](../../globals/String/String.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/toStringTag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.toStringTag The **`Symbol.toStringTag`** well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the [`Object.prototype.toString()`](../../globals/Object/prototype/toString.mdx) method. ## Value The well-known symbol `Symbol.toStringTag`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Symbol/unscopables.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Symbol.unscopables The **`Symbol.unscopables`** well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Value The well-known symbol `@@unscopables`. ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](https://developer.mozilla.org/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](https://developer.mozilla.org/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](../../globals/Object/prototype/toString.mdx) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables#avoid_using_a_non-null-prototype_object_as_symbol.unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[Symbol.unscopables]`](../../globals/Array/prototype/@@unscopables.mdx) does. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/SyntaxError/SyntaxError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SyntaxError The **`SyntaxError`** constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ## Syntax ```js new SyntaxError() new SyntaxError(message) new SyntaxError(message, options) new SyntaxError(message, fileName) new SyntaxError(message, fileName, lineNumber) SyntaxError() SyntaxError(message) SyntaxError(message, options) SyntaxError(message, fileName) SyntaxError(message, fileName, lineNumber) ``` > **Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TextDecoder/TextDecoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder() The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter. ## Syntax ```js new TextDecoder() new TextDecoder(label) new TextDecoder(label, options) ``` ### Parameters - `label` _**optional**_ - : A string, defaulting to `"utf-8"`. - `options` _**optional**_ - : An object with the property: - `fatal` - : A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data. It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character. - `ignoreBOM` - : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. It defaults to `false`. ### Exceptions - `RangeError` - : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TextDecoder/prototype/decode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.decode() The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. The decoding method is defined in the current `TextDecoder` object. This includes the expected encoding of the data, and how decoding errors are handled. ## Syntax ```js decode() decode(buffer) decode(buffer, options) ``` ### Parameters - `buffer` _**optional**_ - : Is an `ArrayBuffer`, a `TypedArray` or a `DataView` object containing the encoded text to decode. - `options` _**optional**_ - : An object with the property: - `stream` - : A boolean flag indicating that additional data will follow in subsequent calls to `decode()`. Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked. It defaults to `false`. ### Exceptions - `TypeError` - : Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TextDecoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.encoding The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object. The encoding is set by the constructor `label` parameter, and defaults to `utf-8`. ## Value A lower-cased ASCII string, which can be one of the following values: - The recommended encoding for the Web: `'utf-8'`. - The legacy single-byte encodings: ['ibm866'](https://en.wikipedia.org/wiki/Code_page_866), ['iso-8859-2'](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), ['iso-8859-3'](https://en.wikipedia.org/wiki/ISO/IEC_8859-3), ['iso-8859-4'](https://en.wikipedia.org/wiki/ISO/IEC_8859-4), ['iso-8859-5'](https://en.wikipedia.org/wiki/ISO/IEC_8859-5), ['iso-8859-6'](https://en.wikipedia.org/wiki/ISO/IEC_8859-6), ['iso-8859-7'](https://en.wikipedia.org/wiki/ISO/IEC_8859-7), ['iso-8859-8'](https://en.wikipedia.org/wiki/ISO/IEC_8859-8)'`, ['iso-8859-8i'](https://en.wikipedia.org/wiki/ISO-8859-8-I), ['iso-8859-10'](https://en.wikipedia.org/wiki/ISO/IEC_8859-10), ['iso-8859-13'](https://en.wikipedia.org/wiki/ISO/IEC_8859-13), ['iso-8859-14'](https://en.wikipedia.org/wiki/ISO/IEC_8859-14), ['iso-8859-15'](https://en.wikipedia.org/wiki/ISO/IEC_8859-15), ['iso-8859-16'](https://en.wikipedia.org/wiki/ISO/IEC_8859-16), ['koi8-r'](https://en.wikipedia.org/wiki/KOI8-R), ['koi8-u'](https://en.wikipedia.org/wiki/KOI8-U), ['macintosh'](https://en.wikipedia.org/wiki/Mac_OS_Roman), ['windows-874'](https://en.wikipedia.org/wiki/Windows-874), ['windows-1250'](https://en.wikipedia.org/wiki/Windows-1250), ['windows-1251'](https://en.wikipedia.org/wiki/Windows-1251), ['windows-1252'](https://en.wikipedia.org/wiki/Windows-1252), ['windows-1253'](https://en.wikipedia.org/wiki/Windows-1253), ['windows-1254'](https://en.wikipedia.org/wiki/Windows-1254), ['windows-1255'](https://en.wikipedia.org/wiki/Windows-1255), ['windows-1256'](https://en.wikipedia.org/wiki/Windows-1256), ['windows-1257'](https://en.wikipedia.org/wiki/Windows-1257), ['windows-1258'](https://en.wikipedia.org/wiki/Windows-1258), or ['x-mac-cyrillic'](https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding). - The legacy multi-byte Chinese (simplified) encodings: ['gbk'](https://en.wikipedia.org/wiki/GBK), ['gb18030'](https://en.wikipedia.org/wiki/GB_18030) - The legacy multi-byte Chinese (traditional) encoding: ['big5'](https://en.wikipedia.org/wiki/Big5). - The legacy multi-byte Japanese encodings: ['euc-jp'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP), ['iso-2022-jp'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP), ['shift-jis'](https://en.wikipedia.org/wiki/Shift_JIS). - The legacy multi-byte Korean encodings: ['euc-kr'](https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR) - The legacy miscellaneous encodings: ['utf-16be'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), ['utf-16le'](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes), `'x-user-defined'`. - A special encoding, `'replacement'`. This decodes empty input into empty output and any other arbitrary-length input into a single replacement character. It is used to prevent attacks that mismatch encodings between the client and server. The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, ['iso-2022-kr'](https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR) and ['hz-gb-2312'](https://en.wikipedia.org/wiki/HZ_(character_encoding)). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TextDecoder/prototype/fatal.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.fatal The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal. If the property is `true` then a decoder will throw a `TypeError` if it encounters malformed data while decoding. If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�). The value of the property is set in the `TextDecoder()` constructor. ## Value A `boolean` which will return `true` if the error mode is set to `fatal`. Otherwise it returns `false`, indicating that the error mode is "replacement". ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TextDecoder/prototype/ignoreBOM.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextDecoder.ignoreBOM The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) is ignored. ## Value `true` if the byte order mark is ignored; `false` otherwise. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TextEncoder/TextEncoder.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder() The **`TextEncoder()`** constructor returns a newly created `TextEncoder` object that will generate a byte stream with UTF-8 encoding. ## Syntax ```js new TextEncoder() ``` ### Parameters None. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TextEncoder/prototype/encode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encode() The **`TextEncoder.encode()`** method takes a string as input, and returns a `Uint8Array` containing the text given in parameters encoded with the specific method for that `TextEncoder` object. ## Syntax ```js encode(string) ``` ### Parameters - `string` - : A string containing the text to encode. ### Return value A `Uint8Array` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TextEncoder/prototype/encoding.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TextEncoder.encoding The **`TextEncoder.encoding`** read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. It can only have the following value `utf-8`. ## Value A string with the value `utf-8`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TransformStream/TransformStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream() The **`TransformStream()`** constructor creates a new `TransformStream` object which represents a pair of streams: a `WritableStream` representing the writable side, and a `ReadableStream` representing the readable side. ## Syntax ```js new TransformStream() new TransformStream(transformer) new TransformStream(transformer, writableStrategy) new TransformStream(transformer, writableStrategy, readableStrategy) ``` ### Parameters - `transformer` _**optional**_ - : An object representing the `transformer`. If not supplied the resulting stream will be an **identity transform stream** which forwards all chunks written to its writable side to its readable side, without any changes. The transformer object can contain any of the following methods. In each method `controller` is an instance of `TransformStreamDefaultController`. - `start(controller)` - : Called when the `TransformStream` is constructed. It is typically used to enqueue chunks using `TransformStreamDefaultController.enqueue()`. - `transform(chunk, controller)` - : Called when a chunk written to the writable side is ready to be transformed, and performs the work of the transformation stream. If no `transform()` method is supplied, the identity transform is used, and the chunk will be enqueued with no changes. - `flush(controller)` - : Called after all chunks written to the writable side have been successfully transformed, and the writable side is about to be closed. - `writableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. - `readableStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer. This defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk`. This indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `readableStrategy` or `writableStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for the object values. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TransformStream/prototype/readable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.readable The **`readable`** read-only property of the `TransformStream` interface returns the `ReadableStream` instance controlled by this `TransformStream`. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TransformStream/prototype/writable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStream.writable The **`writable`** read-only property of the `TransformStream` interface returns the `WritableStream` instance controlled by this `TransformStream`. ## Value A `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TransformStreamDefaultController/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.desiredSize The **`desiredSize`** read-only property of the `TransformStreamDefaultController` interface returns the desired size to fill the queue of the associated [`ReadableStream`](../../../globals/ReadableStream/ReadableStream.mdx). The internal queue of a `ReadableStream` contains chunks that have been enqueued, but not yet read. If the `desiredSize` is `0` then the queue is full. Therefore you can use this information to manually apply backpressure to manage the queue. ## Value The desired size. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TransformStreamDefaultController/prototype/enqueue.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.enqueue() The **`enqueue()`** method of the `TransformStreamDefaultController` interface enqueues the given chunk in the readable side of the stream. ## Syntax ```js enqueue(chunk) ``` ### Parameters - `chunk` - : The chunk being queued. A chunk is a single piece of data. It can be any type of data, and a stream can contain chunks of different types. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream is not readable. This might occur if the stream is errored via `controller.error()`, or when it is closed without its controller's `controller.close()` method ever being called. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TransformStreamDefaultController/prototype/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.error() The **`error()`** method of the `TransformStreamDefaultController` interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. ## Syntax ```js error(reason) ``` ### Parameters - `reason` - : A string containing the error message to be returned on any further interaction with the stream. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TransformStreamDefaultController/prototype/terminate.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TransformStreamDefaultController.terminate() The **`terminate()`** method of the `TransformStreamDefaultController` interface closes the readable side and errors the writable side of the stream. ## Syntax ```js terminate() ``` ### Parameters None. ### Return value None (`undefined`). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/TypeError/TypeError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # TypeError The **`TypeError()`** constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. ## Syntax ```js new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URIError/URIError.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URIError The **`URIError()`** constructor creates an error when a global URI handling function was used in a wrong way. ## Syntax ```js new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without `new`. Both create a new `URIError` instance. ### Parameters - `message` _**optional**_ - : Human-readable description of the error. - `options` _**optional**_ - : An object that has the following properties: - `cause` _**optional**_ - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/URL.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL() The **`URL()`** constructor returns a newly created `URL` object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript `TypeError` exception is thrown. ## Syntax ```js new URL(url) new URL(url, base) ``` ### Parameters - `url` - : A string or any other object with a `toString()` method. If `url` is a relative URL, `base` is required, and will be used as the base URL. If `url` is an absolute URL, a given `base` will be ignored. - `base` _**optional**_ - : A string representing the base URL to use in cases where `url` is a relative URL. If not specified, it defaults to `undefined`. > **Note:** The `url` and `base` arguments will > each be stringified from whatever value you pass, just like with other Web APIs > that accept a string. In particular, you can use an existing > `URL` object for either argument, and it will stringify to the > object's `URL.href", "href` property. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hash The **`hash`** property of the `URL` interface is a string containing a `'#'` followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — `""`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.host The **`host`** property of the `URL` interface is a string containing the host, that is the `URL.hostname`, and then, if the `port` of the URL is nonempty, a `':'`, followed by the `port` of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.hostname The **`hostname`** property of the `URL` interface is a string containing the domain name of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.href The **`href`** property of the `URL` interface is a string containing the whole URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.origin The **`origin`** read-only property of the `URL` interface returns a string containing the Unicode serialization of the origin of the represented URL. The exact structure varies depending on the type of URL: - For `http` or `https` URLs, the scheme followed by `'://'`, followed by the domain, followed by `':'`, followed by the port (the default port, `80` and `443` respectively, if explicitly specified). - For `file:` URLs, the value is browser dependent. - for `blob:` URLs, the origin of the URL following `blob:` will be used. For example, `"blob:https://mozilla.org"` will be returned as `"https://mozilla.org".` ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/password.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.password The **`password`** property of the `URL` interface is a string containing the password specified before the domain name. If it is set without first setting the `URL.username` property, it silently fails. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.pathname The **`pathname`** property of the `URL` interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string. URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character. For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string. Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug. Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.port The **`port`** property of the `URL` interface is a string containing the port number of the URL. > **Note:** If an input string passed to the `URL()` constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the `URL` object the constructor returns, the value of the port property will be the empty string: `''`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.protocol The **`protocol`** property of the `URL` interface is a string representing the protocol scheme of the URL, including the final `':'`. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.search The **`search`** property of the `URL` interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/searchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.searchParams The **`searchParams`** readonly property of the `URL` interface returns a `URLSearchParams` object allowing access to the `GET` decoded query arguments contained in the URL. ## Value A `URLSearchParams` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/toJSON.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toJSON() The **`toJSON()`** method of the `URL` interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as `URL.toString()`. ## Syntax ```js toJSON() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.toString() The **`URL.toString()`** method returns a string containing the whole URL. It is effectively a read-only version of `URL.prototype.href`. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URL/prototype/username.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URL.username The **`username`** property of the `URL` interface is a string containing the username specified before the domain name. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/URLSearchParams.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams() The **`URLSearchParams()`** constructor creates and returns a new `URLSearchParams` object. ## Syntax ```js new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` _**optional**_ - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs. - A record of string keys and string values. Note that nesting is not supported. ### Return value A `URLSearchParams` object instance. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.append() The **`append()`** method of the `URLSearchParams` interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. ## Syntax ```js append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.delete() The **`delete()`** method of the `URLSearchParams` interface deletes the given search parameter and all its associated values, from the list of all search parameters. ## Syntax ```js delete(name) ``` ### Parameters - `name` - : The name of the parameter to be deleted. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/entries.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.entries() The **`entries()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. ## Syntax ```js entries() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/forEach.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.forEach() The **`forEach()`** method of the `URLSearchParams` interface allows iteration through all values contained in this object via a callback function. ## Syntax ```js forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` _**optional**_ - : Value to use as `this` when executing `callback`. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.get() The **`get()`** method of the `URLSearchParams` interface returns the first value associated to the given search parameter. ## Syntax ```js get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.has() The **`has()`** method of the `URLSearchParams` interface returns a boolean value that indicates whether a parameter with the specified name exists. ## Syntax ```js has(name) ``` ### Parameters - `name` - : The name of the parameter to find. ### Return value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/keys.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.keys() The **`keys()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all keys contained in this object. The keys are string objects. ## Syntax ```js keys() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.set() The **`set()`** method of the `URLSearchParams` interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. ## Syntax ```js set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/sort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.sort() The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). ## Syntax ```js sort() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.toString() The **`toString()`** method of the `URLSearchParams` interface returns a query string suitable for use in a URL. ## Syntax ```js toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/URLSearchParams/prototype/values.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # URLSearchParams.values() The **`values()`** method of the `URLSearchParams` interface returns an iterator allowing iteration through all values contained in this object. The values are string objects. ## Syntax ```js values() ``` ### Parameters None. ### Return value Returns an iterator. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Uint16Array/Uint16Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint16Array The **`Uint16Array()`** typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. ## Syntax ```js new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Uint32Array/Uint32Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint32Array The **`Uint32Array()`** typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](../../globals/DataView/DataView.mdx) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint32Array() new Uint32Array(length) new Uint32Array(typedArray) new Uint32Array(object) new Uint32Array(buffer) new Uint32Array(buffer, byteOffset) new Uint32Array(buffer, byteOffset, length) ``` > **Note:** `Uint32Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Uint8Array/Uint8Array.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8Array The **`Uint8Array()`** constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8Array() new Uint8Array(length) new Uint8Array(typedArray) new Uint8Array(object) new Uint8Array(buffer) new Uint8Array(buffer, byteOffset) new Uint8Array(buffer, byteOffset, length) ``` > **Note:** `Uint8Array()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/Uint8ClampedArray/Uint8ClampedArray.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Uint8ClampedArray The **`Uint8ClampedArray()`** constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of \[0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ## Syntax ```js new Uint8ClampedArray() new Uint8ClampedArray(length) new Uint8ClampedArray(typedArray) new Uint8ClampedArray(object) new Uint8ClampedArray(buffer) new Uint8ClampedArray(buffer, byteOffset) new Uint8ClampedArray(buffer, byteOffset, length) ``` > **Note:** `Uint8ClampedArray()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakMap/WeakMap.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap The **`WeakMap()` constructor** creates a `WeakMap` object, optionally based on a provided `Array` or other iterable object. ## Syntax ```js new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` - : An `Array` or other object that implements the [iterable protocol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakMap/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.delete() The **`delete()`** method removes the specified element from a `WeakMap` object. ## Syntax ```js delete(key) ``` ### Parameters - `key` - : The key of the element to remove from the `WeakMap` object. ### Return value `true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakMap/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.get() The **`get()`** method returns a specified element from a `WeakMap` object. ## Syntax ```js get(key) ``` ### Parameters - `key` - : Required. The key of the element to return from the `WeakMap` object. ### Return value The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../../../globals/undefined.mdx) is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakMap/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.has() The **`has()`** method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not. ## Syntax ```js has(key) ``` ### Parameters - `key` - : Required. The key of the element to test for presence in the `WeakMap` object. ### Return value - Boolean - : Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakMap/prototype/set.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakMap.prototype.set The **`set()`** method adds a new element with a specified key and value to a `WeakMap` object. ## Syntax ```js set(key, value) ``` ### Parameters - `key` - : Required. Must be `object`. The key of the element to add to the `WeakMap` object. - `value` - : Required. Any value. The value of the element to add to the `WeakMap` object. ### Return value The `WeakMap` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakRef/WeakRef.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef The **`WeakRef`** constructor creates a `WeakRef` object referring to a given target object. ## Syntax ```js new WeakRef(targetObject) ``` > **Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `targetObject` - : The target object the WeakRef should refer to (also called the _referent_). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakRef/prototype/deref.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakRef.prototype.deref() The `deref` method returns the `WeakRef` instance's target object, or `undefined` if the target object has been garbage-collected. ## Syntax ```js deref() ``` ### Return value The target object of the WeakRef, or `undefined` if the object has been garbage-collected. ## Description See the [Notes on WeakRefs](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the `WeakRef` page for some important notes. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakSet/WeakSet.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet The **`WeakSet`** constructor lets you create `WeakSet` objects that store weakly held _objects_ in a collection. ## Syntax ```js new WeakSet() new WeakSet(iterable) ``` > **Note:** `WeakSet()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `iterable` _**optional**_ - : If an [iterable object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakSet/prototype/add.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.add The **`add()`** method appends a new object to the end of a `WeakSet` object. ## Syntax ```js add(value) ``` ### Parameters - value - : Required. The object to add to the `WeakSet` collection. ### Return value The `WeakSet` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakSet/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.delete The **`delete()`** method removes the specified element from a `WeakSet` object. ## Syntax ```js delete(value) ``` ### Parameters - `value` - : Required. The object remove from the `WeakSet` object. ### Return value `true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WeakSet/prototype/has.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WeakSet.prototype.has The **`has()`** method returns a boolean indicating whether an object exists in a `WeakSet` or not. ## Syntax ```js has(value) ``` ### Parameters - `value` - : Required. The object to test for presence in the `WeakSet`. ### Return value - Boolean - : Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/WorkerLocation.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation The **`WorkerLocation`** interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the [`location`](../../globals/location.mdx) property obtained by calling `globalThis.location`. ## Instance properties - [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx) _**read-only**_ - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. - [`WorkerLocation.protocol`](../../globals/WorkerLocation/protocol.mdx) _**read-only**_ - : Returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. - [`WorkerLocation.host`](../../globals/WorkerLocation/host.mdx) _**read-only**_ - : Returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. - [`WorkerLocation.hostname`](../../globals/WorkerLocation/hostname.mdx) _**read-only**_ - : Returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. - [`WorkerLocation.origin`](../../globals/WorkerLocation/origin.mdx) _**read-only**_ - : Returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). - [`WorkerLocation.port`](../../globals/WorkerLocation/port.mdx) _**read-only**_ - : Returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. - [`WorkerLocation.pathname`](../../globals/WorkerLocation/pathname.mdx) _**read-only**_ - : Returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. - [`WorkerLocation.search`](../../globals/WorkerLocation/search.mdx) _**read-only**_ - : Returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. - [`WorkerLocation.hash`](../../globals/WorkerLocation/hash.mdx) _**read-only**_ - : Returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Instance methods - [`WorkerLocation.toString`](../../globals/WorkerLocation/toString.mdx) - : Returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/hash.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hash The **`hash`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hash`](../../globals/URL/prototype/hash.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/host.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.host The **`host`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`host`](../../globals/URL/prototype/host.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/hostname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.hostname The **`hostname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`hostname`](../../globals/URL/prototype/hostname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/href.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.href The **`href`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/origin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.origin The **`origin`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the worker's [`origin`](../../globals/URL/prototype/origin.mdx). ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/pathname.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.pathname The **`pathname`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`pathname`](../../globals/URL/prototype/pathname.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/port.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.port The **`port`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`port`](../../globals/URL/prototype/port.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/protocol.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.protocol The **`protocol`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`protocol`](../../globals/URL/prototype/protocol.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/search.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.search The **`search`** property of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns the [`search`](../../globals/URL/prototype/search.mdx) part of the worker's location. ## Value A string. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WorkerLocation/toString.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WorkerLocation.toString() The **`toString()`** method of a [`WorkerLocation`](../../globals/WorkerLocation/WorkerLocation.mdx) object returns a string containing the serialized [`URL`](../../globals/URL/URL.mdx) for the worker's location. It is a synonym for [`WorkerLocation.href`](../../globals/WorkerLocation/href.mdx). ## Syntax ```js toString() ``` ### Parameters None. ### Return value None [`undefined`](../../globals/undefined.mdx). ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStream/WritableStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream() The **`WritableStream()`** constructor creates a new `WritableStream` object instance. ## Syntax ```js new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` _**optional**_ - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSink` can contain the following: - `start(controller)` _**optional**_ - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a `WritableStreamDefaultController`. This can be used by the developer to control the stream during set up. - `write(chunk, controller)` _**optional**_ - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. The `controller` parameter passed to this method is a `WritableStreamDefaultController` that can be used by the developer to control the stream as more chunks are submitted for writing. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. The `controller` parameter passed to this method is a `WritableStreamDefaultController`, which can be used to control the stream at the end of writing. - `abort(reason)` _**optional**_ - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up — those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` _**optional**_ - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` — this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > `ByteLengthQueuingStrategy` or `CountQueuingStrategy` > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the `WritableStream` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStream/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.abort() The **`abort()`** method of the `WritableStream` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStream/prototype/getWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.getWriter() The **`getWriter()`** method of the `WritableStream` interface returns a new instance of `WritableStreamDefaultWriter` and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js getWriter() ``` ### Parameters None. ### Return value A `WritableStreamDefaultWriter` object instance. ### Exceptions - `TypeError` - : The stream you are trying to create a writer for is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStream/prototype/locked.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStream.locked The **`locked`** read-only property of the `WritableStream` interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStreamDefaultController/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultController.error() The **`error()`** method of the `WritableStreamDefaultController` interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None `undefined`. ### Exceptions - `TypeError` - : The stream you are trying to error is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStreamDefaultWriter/WritableStreamDefaultWriter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter() The **`WritableStreamDefaultWriter()`** constructor creates a new `WritableStreamDefaultWriter` object instance. ## Syntax ```js new WritableStreamDefaultWriter(stream) ``` ### Parameters - `stream` - : The `WritableStream` to be written to. ### Return value An instance of the `WritableStreamDefaultWriter` object. ### Exceptions - `TypeError` - : The provided `stream` value is not a `WritableStream`, or it is locked to another writer already. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStreamDefaultWriter/prototype/abort.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.abort() The **`abort()`** method of the `WritableStreamDefaultWriter` interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. If the writer is active, the `abort()` method behaves the same as that for the associated stream (`WritableStream.abort()`). If not, it returns a rejected promise. ## Syntax ```js abort() abort(reason) ``` ### Parameters - `reason` _**optional**_ - : A string representing a human-readable reason for the abort. ### Return value A `Promise`, which fulfills with the value given in the `reason` parameter. ### Exceptions - `TypeError` - : The stream you are trying to abort is not a `WritableStream`, or it is locked. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStreamDefaultWriter/prototype/close.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.close() The **`close()`** method of the `WritableStreamDefaultWriter` interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). ## Syntax ```js close() ``` ### Parameters None. ### Return value A `Promise`, which fulfills with the `undefined` if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - `TypeError` - : The stream you are trying to close is not a `WritableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStreamDefaultWriter/prototype/closed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.closed The **`closed`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStreamDefaultWriter/prototype/desiredSize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.desiredSize The **`desiredSize`** read-only property of the `WritableStreamDefaultWriter` interface returns the desired size required to fill the stream's internal queue. ## Value An integer. Note that this can be negative if the queue is over-full. The value will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. ### Exceptions - `TypeError` - : The writer's lock is released. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStreamDefaultWriter/prototype/ready.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.ready The **`ready`** read-only property of the `WritableStreamDefaultWriter` interface returns a `Promise` that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ## Value A `Promise`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStreamDefaultWriter/prototype/releaseLock.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.releaseLock() The **`releaseLock()`** method of the `WritableStreamDefaultWriter` interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ## Syntax ```js releaseLock() ``` ### Parameters None. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/WritableStreamDefaultWriter/prototype/write.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # WritableStreamDefaultWriter.write() The **`write()`** method of the `WritableStreamDefaultWriter` interface writes a passed chunk of data to a `WritableStream` and its underlying sink, then returns a `Promise` that resolves to indicate the success or failure of the write operation. Note that what "success" means is up to the underlying sink; it might indicate that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. ## Syntax ```js write(chunk) ``` ### Parameters - `chunk` - : A block of binary data to pass to the `WritableStream`. ### Return value A `Promise`, which fulfills with the `undefined` upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ### Exceptions - `TypeError` - : The target stream is not a writable stream, or it does not have an owner. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/atob.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # atob() The **`atob()`** function decodes a string of data which has been encoded using Base64 encoding. You can use the `btoa()` method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the `atob()` method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for `btoa()`. ## Syntax ```js atob(encodedData) ``` ### Parameters - `encodedData` - : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. ### Return value An ASCII string containing decoded data from `encodedData`. ### Exceptions - `InvalidCharacterError` - : Thrown if `encodedData` is not valid base64. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/btoa.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # btoa() The **`btoa()`** method creates a Base64-encoded ASCII string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the `atob()` method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/clearInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearInterval() The global **`clearInterval()`** method cancels a timed, repeating action which was previously established by a call to `setInterval()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearInterval(intervalID) ``` ### Parameters - `intervalID` - : The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`. It's worth noting that the pool of IDs used by `setInterval()` and `setTimeout()` are shared, which means you can technically use `clearInterval()` and `clearTimeout()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/clearTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # clearTimeout() The global **`clearTimeout()`** method cancels a timeout previously established by calling `setTimeout()`. If the parameter provided does not identify a previously established action, this method does nothing. ## Syntax ```js clearTimeout(timeoutID) ``` ### Parameters - `timeoutID` - : The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setTimeout()`. It's worth noting that the pool of IDs used by `setTimeout()` and `setInterval()` are shared, which means you can technically use `clearTimeout()` and `clearInterval()` interchangeably. However, for clarity, you should avoid doing so. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/assert.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.assert() The **`console.assert()`** method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. ## Syntax ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /* … ,*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /* … ,*/ substN) ``` ### Parameters - `assertion` - : Any boolean expression. If the assertion is false, the message is written to the console. - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. - `msg` - : A JavaScript string containing zero or more substitution strings. - `subst1` … `substN` - : JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/clear.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.clear() The **`console.clear()`** method clears the console if the console allows it. ## Syntax ```js clear() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/count.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.count() The **`console.count()`** method logs the number of times that this particular call to `count()` has been called. ## Syntax ```js count() count(label) ``` ### Parameters - `label` _optional_ - : A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/countReset.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.countReset() The **`console.countReset()`** method resets counter used with `console.count()`. ## Syntax ```js countReset() countReset(label) ``` ### Parameters - `label` __optional__ - : A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/debug.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.debug() The **`console.debug()`** method outputs a message to the console at the "debug" log level. ## Syntax ```js debug(obj1) debug(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/dir.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dir() The method **`console.dir()`** displays a list of the properties of the specified JavaScript object. ## Syntax ```js dir(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/dirxml.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.dirxml() The **`console.dirxml()`** method displays the supplied object in the console. ## Syntax ```js dirxml(object) ``` ### Parameters - `object` - : A JavaScript object whose properties should be output. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/error.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.error() The **`console.error()`** method outputs an error message console. ## Syntax ```js error(obj1) error(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/group.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.group() The **`console.group()`** method creates a new inline group in the console, until `console.groupEnd()` is called. ## Syntax ```js group() group(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/groupCollapsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupCollapsed() The **`console.groupCollapsed()`** method creates a new inline group in the Web Console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. Call `console.groupEnd()` to back out to the parent group. ## Syntax ```js groupCollapsed() groupCollapsed(label) ``` ### Parameters - `label` __optional__ - : Label for the group. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/groupEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.groupEnd() The **`console.groupEnd()`** method exits the current inline group in the console. ## Syntax ```js groupEnd() ``` ### Parameters None. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/info.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.info() The **`console.info()`** method outputs an informational message to the console. ## Syntax ```js info(obj1) info(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.log() The **`console.log()`** method outputs a message to the console. ## Syntax ```js log(obj1) log(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a _reference to the object_, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/time.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.time() The **`console.time()`** method starts a timer you can use to track how long an operation takes. You give each timer a unique name. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. ## Syntax ```js time(label) ``` ### Parameters - `label` - : A `string` representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/timeEnd.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeEnd() The **`console.timeEnd()`** stops a timer that was previously started by calling `console.time()`. ## Syntax ```js timeEnd(label) ``` ### Parameters - `label` - : A `string` representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/timeLog.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.timeLog() The **`console.timeLog()`** method logs the current value of a timer that was previously started by calling `console.time()`. ## Syntax ```js timeLog() timeLog(label) ``` ### Parameters - `label` __optional__ - : The name of the timer to log to the console. If this is omitted the label "default" is used. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/trace.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.trace() The **`console.trace()`** method outputs a stack trace to the console. ## Syntax ```js trace() trace(object1, /* …, */ objectN) ``` ### Parameters - `objects` __optional__ - : Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method. ### Return value `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/console/warn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # console.warn() The **`console.warn()`** method outputs a warning message to the console. ## Syntax ```js warn(obj1) warn(obj1, /* …, */ objN) ``` ### Parameters - `obj1` … `objN` - : A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ### Return value None `undefined`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/crypto/getRandomValues.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.getRandomValues() The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). ## Syntax ```js getRandomValues(typedArray) ``` ### Parameters - `typedArray` - : An integer-based `TypedArray`, that is one of: `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array` (but **not** `Float32Array` nor `Float64Array`). All elements in the array will be overwritten with random numbers. ### Return value The same array passed as `typedArray` but with its contents replaced with the newly generated random numbers. Note that `typedArray` is modified in-place, and no copy is made. ### Exceptions - `QuotaExceededError` - : Thrown if the `byteLength` of `typedArray` exceeds 65,536. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/crypto/randomUUID.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.randomUUID() The **`randomUUID()`** method is used to generate a v4 [UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID) using a cryptographically secure random number generator. ## Syntax ```js randomUUID() ``` ### Parameters None. ### Return value A string containing a randomly generated, 36 character long v4 UUID. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/crypto/subtle.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Crypto.subtle The **`Crypto.subtle`** read-only property returns a [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) which can then be used to perform low-level cryptographic operations. ## Value A [`SubtleCrypto`](../SubtleCrypto/SubtleCrypto.mdx) object you can use to interact with the Web Crypto API's low-level cryptography features. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/decodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURI The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](../globals/encodeURI.mdx) or a similar routine. ## Syntax ```js decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](../globals/URIError/URIError.mdx) is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ``` ; / ? : @ & = + $ , # ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/decodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # decodeURIComponent The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](./encodeURIComponent.mdx) or by a similar routine. ## Syntax ```js decodeURIComponent(encodedURI) ``` ### Parameters - `encodedURI` - : An encoded component of a Uniform Resource Identifier. ### Return value A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component. ### Exceptions - [`URIError`](../globals/URIError/URIError.mdx) - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURIComponent()` is a function property of the global object. `decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](./decodeURI.mdx). It decodes _all_ escape sequences, including those that are not created by [`encodeURIComponent()`](./encodeURIComponent.mdx), like `-.!~*'()`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/encodeURI.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURI() The **`encodeURI()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](./encodeURIComponent.mdx), this function encodes fewer characters, preserving those that are part of the URI syntax. ## Syntax ```js encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uri` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](./URIError/URIError.mdx). `encodeURI()` escapes all characters **except**: ``` A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ``` http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/encodeURIComponent.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # encodeURIComponent The **`encodeURIComponent()`** function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](./encodeURI.mdx), this function encodes more characters, including those that are part of the URI syntax. ## Syntax ```js encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - [`URIError`](./URIError/URIError.mdx) - : Thrown if `uriComponent` contains a [lone surrogate](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_codepoints_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](./encodeURI.mdx). It escapes all characters **except**: ```text A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to [`encodeURI()`](./encodeURI.mdx), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms `POST`'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/escape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # escape() > **Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](./encodeURIComponent.mdx) or [`encodeURI()`](./encodeURI.mdx) if possible. The **`escape()`** function computes a new string in which certain characters have been replaced by hexadecimal escape sequences. ## Syntax ```js escape(str) ``` ### Parameters - `str` - : A string to be encoded. ### Return value A new string in which certain characters have been escaped. ## Description `escape()` is a function property of the global object. The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The escape format is _not_ an [escape sequence](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/eval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # eval > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [never use direct eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_direct_eval!) for details. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. ## Syntax ```js eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, [`undefined`](./undefined.mdx) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including[ `SyntaxError`](./SyntaxError/SyntaxError.mdx) if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/fetch.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fetch() The global **`fetch()`** method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the `Response` object representing the response to your request. A `fetch()` promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A `fetch()` promise _does not_ reject on HTTP errors (`404`, etc.). Instead, a `then()` handler must check the `Response.ok` and/or `Response.status` properties. > **Note:** The `fetch()` method's parameters are identical to > those of the `Request()` constructor. ## Explicit Backends Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service. This `backend` option is then a special Fastly-specific fetch option that is provided to the `fetch()` call: ```js fetch('https://origin.com/path', { backend: 'origin' }); ``` Backends are configured using the Fastly service backend configuration, see the [Backend documentation](https://developer.fastly.com/reference/api/services/backend/) for more information. ## Dynamic Backends Dynamic backends are a compute feature that allow services to define backends for themselves. If the `backend` option is not provided when making `fetch()` requests, a backend will be automatically created by extracting the protocol, host, and port from the provided URL. In addition, custom backend configuration options can then also be provided through the [`Backend()`](../fastly:backend/Backend/Backend.mdx) constructor. ## Syntax ```js fetch(resource) fetch(resource, options) ``` ### Parameters - `resource` - : This defines the resource that you wish to fetch. This can either be: - A string or any other object with a "toString" method. - A `Request` object. - `options` _**optional**_ - : An object containing any custom settings that you want to apply to the request. The possible options are: - `method` - : The request method, e.g., `GET`, `POST`. - `headers` - : Any headers you want to add to your request, contained within a `Headers` object or an object literal with `String` values. - `body` - : Any body that you want to add to your request: this can be an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object. - `backend` _**Fastly-specific**_ - *Fastly-specific* - `cacheOverride` _**Fastly-specific**_ - `cacheKey` _**Fastly-specific**_ - `imageOptimizerOptions` _**Fastly-specific**_, see [`imageOptimizerOptions`](../fastly:image-optimizer/imageOptimizerOptions.mdx). - `fastly` _**Fastly-specific**_ - `decompressGzip`_: boolean_ _**optional**_ - Whether to automatically gzip decompress the Response or not. ### Return value A `Promise` that resolves to a `Response` object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/globalThis.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # globalThis The global **`globalThis`** property contains the [global `this`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/docs/Glossary/Global_object). ## Value The global `this` object. > **Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object. ## Description The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/isFinite.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isFinite The global **`isFinite()`** function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. ## Syntax ```js isFinite(testValue) ``` ### Parameters - `testValue` - : The value to be tested for finiteness. ### Return value **`false`** if the argument is (or will be coerced to) positive or negative [`Infinity`](./Infinity.mdx) or [`NaN`](./NaN.mdx) or [`undefined`](./undefined.mdx); otherwise, **`true`**. ## Description `isFinite` is a function property of the global object. You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/isNaN.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # isNaN() The **`isNaN()`** function determines whether a value is [`NaN`](./NaN.mdx) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](./Number/isNaN.mdx). ## Syntax ```js isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is [`NaN`](./NaN.mdx) after being [converted to a number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](./NaN.mdx). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](./NaN.mdx). This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](./NaN.mdx) value" nor the question "is the input not a number". [`Number.isNaN()`](./Number/isNaN.mdx) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](./NaN.mdx) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/location.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # location The **`location`** read-only property returns a [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object with information about the current location of the document. See [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) for all available properties. ## Value A [`Location`](../globals/WorkerLocation/WorkerLocation.mdx) object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/parseFloat.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseFloat() The **`parseFloat()`** function parses a string argument and returns a floating point number. ## Syntax ```js parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. ### Return value A floating point number parsed from the given `string`, or [`NaN`](./NaN.mdx) when the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](./parseInt.mdx) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as: - The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal. - The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it. - Leading spaces in the argument are trimmed and ignored. - `parseFloat()` can also parse and return [`Infinity`](./Infinity.mdx) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces. - `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it. - If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](./NaN.mdx). Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](./Number/Number.mdx) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`. Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see `Number.MAX_VALUE`), `-Infinity` or `Infinity` is returned. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/parseInt.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # parseInt The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). ## Syntax ```js parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading whitespace in this argument is ignored. - `radix` _**optional**_ - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or [`NaN`](./NaN.mdx) when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](./parseFloat.mdx) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a `Number` 42. ## Description The `parseInt` function converts its first argument to a string, parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is converted to a number. If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](./parseFloat.mdx), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](./Number/isNaN.mdx) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for [`Math.trunc()`](./Math/trunc.mdx). To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](./Number/prototype/toString.mdx). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](./Number/isSafeInteger.mdx). The [`BigInt`](./BigInt/BigInt.mdx) function supports parsing integers of arbitrary length accurately, by returning a `BigInt`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/performance/now.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.now() The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since [`performance.timeOrigin`](./timeOrigin.mdx) (the time when the worker was instantiated). ## Syntax ```js now() ``` ### Parameters None. ### Return value Returns a number which represents the time since worker instantation measured in milliseconds. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/performance/timeOrigin.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # performance.timeOrigin The **`timeOrigin`** read-only property of the Performance interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. This value represents the time when the worker was instantiated. ### Value Returns a number which represents the time when the worker was instantation. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/setInterval.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setInterval() The **`setInterval()`** method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling `clearInterval()`. ## Syntax ```js setInterval(code) setInterval(code, delay) setInterval(func) setInterval(func, delay) setInterval(func, delay, arg0) setInterval(func, delay, arg0, arg1) setInterval(func, delay, arg0, arg1, /* … ,*/ argN) ``` ### Parameters - `func` - : A `function` to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds. - `code` - : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds. This syntax is _not recommended_ for the same reasons that make using `eval() a security risk. - `delay` _**optional**_ - : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified. below for details on the permitted range of `delay` values. - `arg0, …, argN` _**optional**_ - : Additional arguments which are passed through to the function specified by _func_ once the timer expires. ### Return value The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to `clearInterval()` to cancel the interval. It may be helpful to be aware that `setInterval()` and `setTimeout()` share the same pool of IDs, and that `clearInterval()` and `clearTimeout()` can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. > **Note:** The `delay` argument is converted to a > signed 32-bit integer. This effectively limits `delay` to 2147483647 ms, > since it's specified as a signed integer in the IDL. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/setTimeout.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setTimeout() The global **`setTimeout()`** method sets a timer which executes a function or specified piece of code once the timer expires. ## Syntax ```js setTimeout(code) setTimeout(code, delay) setTimeout(functionRef) setTimeout(functionRef, delay) setTimeout(functionRef, delay, param1) setTimeout(functionRef, delay, param1, param2) setTimeout(functionRef, delay, param1, param2, /* … ,*/ paramN) ``` ### Parameters - `functionRef` - : A `function` to be executed after the timer expires. - `code` - : An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is **not recommended** for the same reasons that make using `eval()` a security risk. - `delay` _**optional**_ - : The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. - `param1`, …, `paramN` _**optional**_ - : Additional arguments which are passed through to the function specified by `functionRef`. ### Return value The returned `timeoutID` is a positive integer value which identifies the timer created by the call to `setTimeout()`. This value can be passed to `clearTimeout()` to cancel the timeout. It is guaranteed that a `timeoutID` value will never be reused by a subsequent call to `setTimeout()` or `setInterval()` on the same object (a window or a worker). However, different objects use separate pools of IDs. ## Description Timeouts are cancelled using `clearTimeout()`. To call a function repeatedly (e.g., every _N_ milliseconds), consider using `setInterval()`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/structuredClone.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # structuredClone() The global **`structuredClone()`** method creates a deep clone of a given value. ## Syntax ```js structuredClone(value) ``` ### Parameters - `value` - : The object to be cloned. ### Return value The returned value is a deep copy of the original `value`. ### Exceptions - `DataCloneError` - : Thrown if any part of the input value is not serializable. ## Description This function can be used to deep copy JavaScript values. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/undefined.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # undefined The global **`undefined`** property represents the primitive value `undefined`. It is one of JavaScript's "primitive types". ## Value The primitive value `undefined`. ## Description `undefined` is a property of the _global object_. That is, it is a variable in global scope. `undefined` is a non-configurable, non-writable property. A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not explicitly returned. ================================================ FILE: documentation/versioned_docs/version-3.41.2/globals/unescape.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # unescape() > **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](./decodeURIComponent.mdx) or [`decodeURI()`](./decodeURI.mdx) if possible. The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](./escape.mdx). ## Syntax ```js unescape(str) ``` ### Parameters - `str` - : A string to be decoded. ### Return value A new string in which certain characters have been unescaped. ## Description `unescape()` is a function property of the global object. The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is. > **Note:** This function was used mostly for URL encoding and is partly based on the escape format in rfc(1738). The `unescape()` function does _not_ evaluate [escape sequences](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/after.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # after The `after` method inserts content after the closing tag of the element. ## Syntax ```js element.after(content); element.after(content, options); ``` ### Parameters - `content` _: string_ - The content to insert after the element's closing tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.after("World"); // Result:
Hello
World ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/append.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # append The `append` method inserts content at the end of the element's content. ## Syntax ```js element.append(content); element.append(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the end of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.append(", World"); // Result:
Hello, World
``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/before.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # before The `before` method inserts content before the opening tag of the element. ## Syntax ```js element.before(content); element.before(content, options); ``` ### Parameters - `content` _: string_ - The content to insert before the element's opening tag. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.before("Well"); // Result: Well
Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/hasAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # hasAttribute The `hasAttribute` method returns a `boolean` value indicating whether the specified attribute is present on the element. ## Syntax ```js element.hasAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to check for. ### Return value A boolean value indicating whether the attribute is present. ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/prepend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # prepend The `prepend` method inserts content at the beginning of the element's content. ## Syntax ```js element.prepend(content); element.prepend(content, options); ``` ### Parameters - `content` _: string_ - The content to insert at the beginning of the element's content. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.prepend("Well, "); // Result:
Well, Hello
``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/removeAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # removeAttribute The `removeAttribute` method removes the specified attribute from the element. ## Syntax ```js element.removeAttribute(attributeName); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to remove. ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/replaceChildren.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceChildren The `replaceChildren` method replaces the element's children with new content. ## Syntax ```js element.replaceChildren(content); element.replaceChildren(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element's children with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceChildren("Greetings!"); // Result:
Greetings!
``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/replaceWith.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # replaceWith The `replaceWith` method replaces the element with new content. ## Syntax ```js element.replaceWith(content); element.replaceWith(content, options); ``` ### Parameters - `content` _: string_ - The content to replace the element with. - `options` _: ElementRewriterOptions_ - An optional object that can have the following properties: - `escapeHTML` _: boolean_ - If `true`, any HTML markup in `content` will be escaped so it is safe to insert as text. ### Examples ```js // Assuming `e` is an Element representing
Hello
e.replaceWith("

Greetings!

"); // Result:

Greetings!

``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/selector.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # selector The `selector` read-only property is a `string` representing the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) that matches the element. ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/setAttribute.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # setAttribute The `setAttribute` method sets the value of the specified attribute on the element. If the value already exists, it will be updated; otherwise, a new attribute with the specified name and value will be added to the element. ## Syntax ```js element.setAttribute(attributeName, value); ``` ### Parameters - `attributeName` _: string_ - The name of the attribute to set. - `value` _: string_ - The value to assign to the attribute. ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/Element/prototype/tag.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # tag The `tag` read-only property is a `string` representing the tag name of the element. ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/HTMLRewritingStream/HTMLRewritingStream.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `HTMLRewritingStream()` The **`HTMLRewritingStream`** lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback. This callback can manipulate the attributes of the element, and add or remove content from the immediate context. ## Syntax ```js new HTMLRewritingStream() ``` ### Return value A new `HTMLRewritingStream` object. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/html-rewriter/HTMLRewritingStream/prototype/onElement.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # onElement ▸ **onElement**`(selector: string, handler: (element: Element) => void): this` Registers an element handler with the [`HTMLRewritingStream`] that will be called for each [`Element`] that matches the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors) `selector`. Elements added by handlers will not be processed by other handlers. ## Syntax ```js .onElement(selector, handler) ``` ### Parameters - `selector` _: string_ - A CSS selector that determines the elements for which `handler` will be called - The following types of CSS selector are supported: Currently the rewriter supports the following CSS selectors: | Pattern | Description | |----------------------|----------------------------------------------------------------------------| | `*` | Any element | | `E` | All elements of type `E` | | `E F` | `F` elements inside `E` elements | | `E > F` | `F` elements directly inside `E` elements | | `E:nth-child(n)` | The n-th child of type `E` | | `E:first-child` | First child of type `E` | | `E:nth-of-type(n)` | The n-th sibling of type `E` | | `E:first-of-type` | First sibling of type `E` | | `E:not(s)` | Type `E` elements not matching selector `s` | | `E.myclass` | Type `E` elements with class `"myclass"` | | `E#myid` | Type `E` elements with ID `"myid"` | | `E[attr]` | Type `E` elements with attribute `attr` | | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | | `E[attr="val" i]` | Type `E` elements where `attr` is `"val"`, case-insensitive | | `E[attr="val" s]` | Type `E` elements where `attr` is `"val"`, case-sensitive | | `E[attr~="val"]` | Type `E` elements where `attr` contains `"val"` in a space-separated list | | `E[attr`|`;="val"]`| Type `E` elements where `attr` is hyphen-separated and starts with `"val"` | | `E[attr^="val"]` | Type `E` elements where `attr` starts with `"val"` | | `E[attr$="val"]` | Type `E` elements where `attr` ends with `"val"` | | `E[attr*="val"]` | Type `E` elements where `attr` contains `"val"` | - `handler` _: (element: Element) => void_ - A callback function that will be called once for each element that matches `selector` ### Return value The `HTMLRewritingStream`, so multiple calls to `onElement` can be chained. ### Exceptions - `Error` - If the provided `selector` is not a valid CSS selector. - If the provided `handler` is not a function. ## Examples In this example, we fetch an HTML page and use the HTML rewriter to add an attribute to all `div` tags and prepend the text `Header:` to all `h1` tags: ```js /// import { HTMLRewritingStream } from 'fastly:html-rewriter'; async function handleRequest(event) { let transformer = new HTMLRewritingStream() .onElement("h1", e => e.prepend("Header: ")) .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); return new Response(body, { status: 200, headers: new Headers({ "content-type": "text/html; charset=utf-8", }) }) } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/Auto.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Auto` Enumerator options for [`imageOptimizerOptions.auto`](./imageOptimizerOptions.mdx). ## Constants - `AVIF` (`"avif"`) If the browser's Accept header indicates compatibility, deliver an AVIF image. - `WEBP` (`"webp"`) If the browser's Accept header indicates compatibility, deliver a WebP image. ## Examples ```js import { Auto, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, auto: Auto.AVIF }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/BWAlgorithm.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `BWAlgorithm` Enumerator options for [`imageOptimizerOptions.bw`](./imageOptimizerOptions.mdx). ## Constants - `Threshold` (`"threshold"`) Uses a luminance threshold to convert the image to black and white. - `Atkinson` (`"atkinson"`) Uses [Atkinson dithering](https://en.wikipedia.org/wiki/Atkinson_dithering) to convert the image to black and white. ## Examples ```js import { Region, BWAlgorithm } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, bw: BWAlgorithm.Threshold }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/CropMode.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `CropMode` Enumerator options for [`imageOptimizerOptions.crop.mode`](./imageOptimizerOptions.mdx) and `imageOptimizerOptions.precrop.mode`. ## Constants - `Smart` (`"smart"`) Enables content-aware algorithms to attempt to crop the image to the desired aspect ratio while intelligently focusing on the most important visual content, including the detection of faces. - `Safe` (`"safe"`) Allow cropping out-of-bounds regions. ## Examples ```js import { CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Smart, } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/Disable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Disable` Enumerator options for [`imageOptimizerOptions.disable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Prevent images being resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Disable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, disable: Disable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/Enable.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Enable` Enumerator options for [`imageOptimizerOptions.enable`](./imageOptimizerOptions.mdx). ## Constants - `Upscale` (`"upscale"`) Allow images to be resized such that the output image's dimensions are larger than the source image. ## Examples ```js import { Enable, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, enable: Enable.Upscale }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/Fit.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Fit` Enumerator options for [`imageOptimizerOptions.fit`](./imageOptimizerOptions.mdx). ## Constants - `Bounds` (`"bounds"`) Resize the image to fit entirely within the specified region, making one dimension smaller if needed. - `Cover` (`"cover"`) Resize the image to entirely cover the specified region, making one dimension larger if needed. - `Crop` (`"crop"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Fit, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 150, height; 150, fit: Fit.Bounds }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/Format.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Format` Enumerator options for [`imageOptimizerOptions.format`](./imageOptimizerOptions.mdx). ## Constants - `Auto` (`"auto"`) Automatically use the best format based on browser support and image/transform characteristics - `AVIF` (`"avif"`) AVIF - `BJPG` (`"bjpg"`) Baseline JPEG - `GIF` (`"gif"`) Graphics Interchange Format - `JPG` (`"jpg"`) JPEG - `JXL` (`"jxl"`) JPEGXL - `MP4` (`"mp4"`) MP4 (H.264) - `PJPG` (`"pjpg"`) Progressive JPEG - `PJXL` (`"pjxl"`) Progressive JPEGXL - `PNG` (`"png"`) Portable Network Graphics - `PNG8` (`"png8"`) Portable Network Graphics palette image with 256 colors and 8-bit transparency - `SVG` (`"svg"`) Scalable Vector Graphics - `WEBP` (`"webp"`) WebP - `WEBPLL` (`"webpll"`) WebP (Lossless) - `WEBPLY` (`"webply"`) WebP (Lossy) ## Examples ```js import { Format, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/Metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Metadata` Enumerator options for [`imageOptimizerOptions.metadata`](./imageOptimizerOptions.mdx). ## Constants - `Copyright` (`"copyright"`) Preserve [copyright notice](https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#copyright-notice), creator, credit line, licensor, and web statement of rights fields. - `C2PA` (`"c2pa"`) Preserve the [C2PA manifest](https://c2pa.org/) and add any transformations performed by Fastly Image Optimizer. - `CopyRightAndC2PA` (`"copyright,c2pa"`) Resize and crop the image centrally to exactly fit the specified region. ## Examples ```js import { Metadata, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, metadata: Metadata.Copyright }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/Optimize.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Optimize` Enumerator options for [`imageOptimizerOptions.optimize`](./imageOptimizerOptions.mdx). ## Constants - `Low` (`"low"`) Output image quality will be similar to the input image quality. - `Medium` (`"medium"`) More optimization is allowed. We attempt to preserve the visual quality of the input image. - `High` (`"high"`) Minor visual artifacts may be visible. This produces the smallest file. ## Examples ```js import { Optimize, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, optimize: Optimize.High }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/Orient.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Orient` Enumerator options for [`imageOptimizerOptions.orient`](./imageOptimizerOptions.mdx). ## Constants - `Default` (`"1"`) - `FlipHorizontal` (`"2"`) - `FlipHorizontalAndVertical` (`"3"`) - `FlipVertical` (`"4"`) - `FlipHorizontalOrientLeft` (`"5"`) - `OrientRight` (`"6"`) - `FlipHorizontalOrientRight` (`"7"`) - `OrientLeft` (`"8"`) ## Examples ```js import { Orient, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, orient: Orient.FlipHorizontal }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/Profile.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Profile` Enumerator options for [`imageOptimizerOptions.profile`](./imageOptimizerOptions.mdx). ## Constants - `Baseline` (`"baseline"`) The profile recommended for video conferencing and mobile applications. (Default) - `Main` (`"main"`) The profile recommended for standard-definition broadcasts. - `High` (`"high"`) The profile recommended for high-definition broadcasts. ## Examples ```js import { Profile, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, profile: Profile.Main }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/Region.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Region` Enumerator options for [`imageOptimizerOptions.region`](./imageOptimizerOptions.mdx). ## Constants - `UsEast` (`"us_east"`) - `UsCentral` (`"us_central"`) - `UsWest` (`"us_west"`) - `EuCentral` (`"eu_central"`) - `EuWest` (`"eu_west"`) - `Asia` (`"asia"`) - `Australia` (`"australia"`) ## Examples ```js import { Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/ResizeFilter.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `ResizeFilter` Enumerator options for [`imageOptimizerOptions.resizeFilter`](./imageOptimizerOptions.mdx). ## Constants - `Nearest` (`"nearest"`) Uses the value of nearby translated pixel values. - `Bilinear` (`"bilinear"`) Uses an average of a 2x2 environment of pixels. - `Linear` (`"linear"`) Same as `Bilenear`. - `Bicubic` (`"bicubic"`) Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. - `Cubic` (`"cubic"`) Same as `Bicubic`. - `Lanczos2` (`"lanczos2"`) Uses the Lanczos filter to increase the ability to detect edges and linear features within an image and uses sinc resampling to provide the best possible reconstruction. - `Lanczos3` (`"lanczos3"`) Lanczos3 uses a better approximation of the sinc resampling function. (Default) - `Lanczos` (`"lanczos"`) Same as `Lanczos3`. ## Examples ```js import { ResizeFilter, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, width: 2560, resizeFilter: ResizeFilter.Linear }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/image-optimizer/imageOptimizerOptions.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `imageOptimizerOptions` Options specified in the [`Request`](../globals/Request/Request.mdx) constructor for running the [Fastly Image Optimizer](https://docs.fastly.com/products/image-optimizer). More detailed documentation on all Image Optimizer options is available in the [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/). ## Parameters All parameters other than `region` are optional. - `region`: _[`Region`](./Region.mdx)_ Where image optimizations should occur. - `auto`: _[`Auto`](./Auto.mdx)_ Enable optimization features automatically. - `bgColor`: _[`Color`](#color)_ Set the background color of an image. - `blur`: _`number` (0.5-1000) or [`Percentage`](#percentage)_ Set the blurriness of the output image. - `brightness`: _`number` (-100-100)_ Set the brightness of the output image. - `bw`: _[`BWAlgorithm`](./BWAlgorithm.mdx)_ Convert an image to black and white. - `canvas`: _`Object`_ Increase the size of the canvas around an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `contrast`: _`number` (-100-100)_ Set the contrast of the output image. - `crop`: _`Object`_ Remove pixels from an image. - `size`: _[`Size`](#size)_ - `position` (optional): _[`Position`](#position)_ - `mode` (optional): _[`CropMode`](./CropMode.mdx)_ - `disable`: _[`Disable`](./Disable.mdx)_ Disable functionality that is enabled by default. - `dpr`: `number` Ratio between physical pixels and logical pixels. - `enable`: _[`Enable`](./Enable.mdx)_ Enable functionality that is disabled by default. - `fit`: _[`Fit`](./Fit.mdx)_ Set how the image will fit within the size bounds provided. - `format`: _[`Format`](./Format.mdx)_ Specify the output format to convert the image to. - `frame`: _`number` (must have the value 1)_ Extract the first frame from an animated image sequence. - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the height of the image. - `level`: _`String` containing one of the [allowed values](https://www.fastly.com/documentation/reference/io/level/#allowed-values)_ Specify the level constraints when converting to video. - `metadata`: _[`Metadata`](./Metadata.mdx)_ Control which metadata fields are preserved during transformation. - `optimize`: _[`Optimize`](./Optimize.mdx)_ Automatically apply optimal quality compression. - `orient`: _[`Orient`](./Orient.mdx)_ Change the cardinal orientation of the image. - `pad`: _[`Sides`](#sides)_ Add pixels to the edge of an image. - `precrop`: _`Object`_ Remove pixels from an image before any other transformations occur. - `size`: _[`Size`](#size)_ - `position`: _[`Position`](#position)_ - `mode`: _[`CropMode`](./CropMode.mdx)_ - `profile`: _[`Profile`](./Profile.mdx)_ Specify the profile class of application when converting to video. - `quality`: _`integer` (1-100)_ Optimize the image to the given compression level for lossy file formatted images. - `resizeFilter`: _[`ResizeFilter`](./ResizeFilter.mdx)_ Specify the resize filter used when resizing images. - `saturation`: _`number` (-100-100)_ Set the saturation of the output image. - `sharpen`: _`Object`_ Set the sharpness of the output image. - `amount`: _`number` (0-10)_ - `radius`: _`number` (0.5-1000)_ - `threshold`: _`integer` (0-255)_ - `trim`: _[`Sides`](#sides)_ Remove pixels from the edge of an image. - `viewbox`: _`number` (must have the value 1)_ Remove explicit width and height properties in SVG output. - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ Resize the width of the image. ## Types ### Color Either: - a 3 or 6 character hexadecimal string - an `Object` containing: - `r`: _`integer` (0-255)_ Red component - `g`: _`integer` (0-255)_ Green component - `b`: _`integer` (0-255)_ Blue component - `a` (optional): _`number` (0.0-1.0)_ Alpha component ### Percentage A `String` containing a number suffixed with a percent sign (%). ### Position An `Object` containing: - Exactly one of: - `x`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetX`: _`number` (interpreted as a percentage)_ - Exactly one of: - `y`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `offsetY`: _`number` (interpreted as a percentage)_ ### Sides An `Object` containing `top`, `bottom`, `left`, and `right`, all of which are either an `integer` or [`Percentage`](#percentage). ### Size An `Object` containing either: - `absolute`: _`Object`_ - `width`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `height`: _`integer` (number of pixels) or [`Percentage`](#percentage)_ - `ratio`: _`Object`_ - `width`: _`number`_ - `height`: _`number`_ ## Examples ```js import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { imageOptimizerOptions: { region: Region.UsEast, format: Format.PNG, bgColor: { 'r': 100, 'g': 255, 'b': 9, 'a': 0.5 }, blur: '1%', brightness: -20, contrast: -20, height: 600, level: '4.0', orient: Orient.FlipVertical, saturation: 80, sharpen: { 'amount': 5, 'radius': 6, 'threshold': 44 }, canvas: { 'size': { 'absolute': { 'width': 400, 'height': 400 } } }, crop: { size: { absolute: { width: 200, height: 200 }, mode: CropMode.Safe } }, trim: { top: 10, left: 10, right: 10, bottom: 10 }, pad: { top: 30, left: 30, right: "1%", bottom: 30 } }, backend: 'w3' }); } ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # JavaScript for Fastly Compute This site is the full SDK reference for [`@fastly/js-compute`](https://www.npmjs.com/package/%40fastly/js-compute), the module that provides the interface between your JavaScript code and the [Fastly Compute](https://www.fastly.com) platform. If you haven't used Fastly Compute before, start by [setting up your first Fastly Compute program](https://developer.fastly.com/learning/compute/) over on **developer.fastly.com** so that you have a working development environment. To learn more about the fundamentals of using JavaScript with Fastly Compute, see our [using JavaScript](https://developer.fastly.com/learning/compute/javascript/) guide. ## Understanding the JavaScript SDK Incoming HTTP requests to [domains that are attached to your Fastly service](https://developer.fastly.com/learning/concepts/) will start an instance of your application and invoke a `fetch` event, which can be bound using the `addEventListener` function: ```js addEventListener("fetch", event => event.respondWith(handleRequest(event)) ); async function handleRequest(event) { const req = event.request; return fetch(req, { backend: "example_backend" }); } ``` Fastly specific features are available as named imports from `fastly:` prefixed modules, all of which are documented in this site. For example, the [env](https://js-compute-reference-docs.edgecompute.app/docs/fastly:env/env) function provides access to [environment variables](https://developer.fastly.com/reference/compute/ecp-env/) and can be imported into your application like this: ```js import { env } from "fastly:env" ``` JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like [`Date`](https://js-compute-reference-docs.edgecompute.app/docs/globals/Date/) and [`console`](https://js-compute-reference-docs.edgecompute.app/docs/globals/console/log). ## Trying things out [Fastly fiddle](https://fiddle.fastly.dev) is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our [developer hub](https://developer.fastly.com) and this SDK reference. These interactive examples can be executed right on the page by clicking the **RUN** tab: async function app(event) { const request = event.request; return new Response("You made a request to " + request.url) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// async function app(event) { const request = event.request; return new Response(`You made a request to ${request.url}`) } addEventListener("fetch", event => { event.respondWith(app(event)); }); ``` Check out [`fiddle.fastly.dev`](https://fiddle.fastly.dev) to create your own. ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStore/KVStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `KVStore()` The **`KVStore` constructor** lets you connect your Fastly Compute application to a Fastly KV store. A Fastly KV store is a persistent, globally consistent key-value store. See [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) for initialization and usage details. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new KVStore(name) ``` > **Note:** `KVStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a KV store instance using the resource link name. ### Return value A new `KVStore` object. ### Exceptions - `TypeError` - Thrown if no KV Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name does not start with an ascii alphabetical character - Thrown if the provided name contains control characters `(\u0000-\u001F)` ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStore/prototype/delete.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.delete Deletes the value associated with the key `key` in the KV store. ## Syntax ```js delete(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value Returns `undefined` ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - Does not exist ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then delete the entry. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') await files.delete('hello') const entry = await files.get('hello') if (entry) { return new Response(await entry.text()) } else { return new Response('no file named hello exists') } } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the KV store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the KV-store. ### Return value If the key does not exist in the KV store, this returns a `Promise` which resolves with `null`. If the key does exist in the KV store, this returns a `Promise` which resolves with an `KVStoreEntry`. ## Description Send the given message, converted to a string, to this KVStore instance's endpoint. The `get()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStore/prototype/list.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.list The **`list()`** can be used to list the keys of a store. ## Syntax ```js list(options?) ``` ### Parameters - `options` _: object_ _**optional**_ - List options supporting properties: - `cursor` _: string_ _**optional**_ - The cursor used to pick up from a previous iteration. - `limit` _: number_ _**optional**_ - The maximum number of keys to return. - `prefix` _: string_ _**optional**_ - List only those keys that start with the given string prefix. - `noSync` _: boolean_ _**optional**_ - Do not sync the key list first, instead provide a possibly out-of-date listing. May be faster but inconsistent. ### Return value Returns a `Promise` which resolves with `{ list: string[], cursor: string | undefined }`. ## Example In this example we list the keys of a KV Store named `'files'`, iterating 10 at a time, counting the total; ```js /// import { KVStore } from 'fastly:kv-store'; async function app(event) { const files = new KVStore('files'); let cursor, list, total = 0; do { ({ cursor, list } = await files.list({ limit: 10, cursor })); total += list?.length; } while (list); return new Response(`Iterated ${total} entries`); } addEventListener('fetch', (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStore/prototype/put.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStore.prototype.put The **`put()`** method stores a `value` into the KV store under a `key`. > **Note**: KV stores are eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all edge locations immediately and some edge locations may continue returning the previous contents associated with the key. ## Syntax ```js put(key, value, options?) ``` ### Parameters - `key` _: string_ - The key to store the supplied value under within the KV store. - `value` _: ArrayBuffer | TypedArray | DataView| ReadableStream | URLSearchParams | String | string literal_ - The value to store within the KV store. - `options` _: object_ _**optional**_ - An insert options parameter, supporting: - `metadata` _: ArrayBuffer | TypedArray | DataView_ _**optional**_ - Binary metadata associated with the entry, may be up to 1000 bytes. - `ttl` _: number_ _**optional**_ - TTL for the entry - `mode` _: 'overwrite' | 'add' | 'append' | 'prepend'_ _**optional**_ - Insert mode, defaults to 'overwrite' - `gen` _: number_ _**optional**_ - 'generation' header specific to the version of an entry key ### Return value Returns a `Promise` which resolves with `undefined` when the provided `value` has been written into the KV store. ## Description Stores the supplied `value` into the KV store under the supplied `key`. The `put()` method requires its `this` value to be a [`KVStore`](../KVStore.mdx) object. If the `this` value does not inherit from `KVStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is any of the strings `""`, `"."`, or `".."` - Starts with the string `".well-known/acme-challenge/"` - Contains any of the characters `"#;?^|\n\r"` - Is longer than 1024 characters - `TypeError` - If the provided `gen`: - Is not an number ## Examples In this example we connect to an KV Store named `'files'` and save an entry to the store under the key `'hello'` and then read back the value and return it to the client. ```js /// import { KVStore } from "fastly:kv-store"; async function app(event) { const files = new KVStore('files') await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStoreEntry/prototype/arrayBuffer.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.arrayBuffer() The `arrayBuffer()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with an `ArrayBuffer`. ## Syntax ```js text() ``` ### Parameters None. ### Return value A promise that resolves with an `ArrayBuffer`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStoreEntry/prototype/body.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.body The `body` read-only property of the `KVStoreEntry` interface is a `ReadableStream` of the body contents. ## Value A `ReadableStream`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStoreEntry/prototype/bodyUsed.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.bodyUsed The `bodyUsed` read-only property of the `KVStoreEntry` interface is a `boolean` value that indicates whether the body has been read yet. ## Value A boolean value. ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStoreEntry/prototype/json.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.json() The `json()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js json() ``` ### Parameters None. ### Return value A `Promise` that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number… ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStoreEntry/prototype/metadata.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadata() The `metadata()` method of the `KVStoreEntry` interface provides the binary metadata associated with the `KVStoreEntry`. The metadata binary may be up to 1000 bytes, and is returned as a `Uint8Array` TypedArray buffer, if metadata is set, or null otherwise. ## Syntax ```js metadata() ``` ### Parameters None. ### Return value A `Promise` that resolves to a `Uint8Array` buffer object. ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStoreEntry/prototype/metadataText.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.metadataText() The `metadataText()` method of the `KVStoreEntry` interface provides a String interpretation of binary metadata associated with the `KVStoreEntry`. If the binary data is not a valid string, an encoding error will be thrown. ## Syntax ```js metadataText() ``` ### Parameters None. ### Return value A `Promise` that resolves to a String. ================================================ FILE: documentation/versioned_docs/version-3.41.2/kv-store/KVStoreEntry/prototype/text.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # KVStoreEntry.text() The `text()` method of the `KVStoreEntry` interface takes a `KVStoreEntry` stream and reads it to completion. It returns a promise that resolves with a `String`. The `KVStoreEntry `is always decoded using UTF-8. ## Syntax ```js text() ``` ### Parameters None. ### Return value A `Promise` that resolves with a `String`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/logger/Logger/Logger.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Logger()` The **`Logger` constructor** lets you connect your Fastly Compute application to a [Fastly Named Logger](https://developer.fastly.com/learning/integrations/logging/). ## Syntax ```js new Logger(name) ``` > **Note:** `Logger()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - The Fastly Logger which should be associated with this Logger instance ### Return value A new `Logger` object. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; const logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/logger/Logger/prototype/log.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Logger.prototype.log ▸ **log**(): `string` Sends the given message, converted to a string, to this Logger instance's endpoint. **Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js log(message) ``` ### Return value `undefined`. ## Description Send the given message, converted to a string, to this Logger instance's endpoint. The `log()` method requires its `this` value to be a [`Logger`](../Logger.mdx) object. If the `this` value does not inherit from `Logger.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we have a create a logger named `"splunk"` and logs the incoming request method and destination. import { Logger } from "fastly:logger"; let logger = new Logger("splunk"); async function app (event) { logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ` }, "requests": [ { "enableCluster": true, "enableShield": false, "enableWAF": false, "method": "GET", "path": "/status=200", "useFreshCache": false, "followRedirects": false, "tests": "", "delay": 0 } ], "srcVersion": 1 }}> ```js /// import { Logger } from "fastly:logger"; async function app (event) { let logger = new Logger("splunk"); logger.log(JSON.stringify({ method: event.request.method, url: event.request.url })); return new Response('OK'); } addEventListener("fetch", event => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/logger/configureConsole.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # configureConsole The **`configureConsole()`** function allows configuring the behaviour of the `console` global JS logger. ## Syntax ```js configureConsole(loggingOptions) ``` ### Parameters - `loggingOptions` _: object_ - - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ## Examples In this example, we disable prefixing for `console.log` and use `stderr` output for `console.error`: ```js import { configureConsole } from "fastly:logger"; configureConsole({ prefixing: false, stderr: true }); async function handleRequest(event) { console.log(JSON.stringify(event.request.headers)); const url = new URL(event.request.url); try { validate(url); } catch (e) { console.error(`Validation error: ${e}`); return new Response('Bad Request', { status: 400 }); } return new Response('OK'); } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/migration-guide/index.mdx ================================================ --- sidebar_position: 1 hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Migrating from v2 to v3` ## SimpleCache.delete renamed to SimpleCache.purge and requires purge options to be supplied as the second parameter We are renaming because "purge" is already a well-known and documented concept for removing content from Fastly's cache. The new addition of a second argument allows the caller to decide what scope to purge the content from, currently they can choose to purge from all of Fastly ("global") or from the POP that contains the currently executing instance ("pop"). We do not provide a default option right now, in the future we may provide a default option, if we discover a common pattern is being used. Here is an example of migrating an application using `SimpleCache.delete` to `SimpleCache.purge` with the same purging behaviour: ```diff /// import { SimpleCache } from 'fastly:cache'; addEventListener('fetch', event => event.respondWith(app(event))); async function app(event) { const url = new URL(event.request); const path = url.pathname; if (url.searchParams.has('delete')) { - SimpleCache.delete(path); + SimpleCache.purge(path, { scope: "global" }); return new Response(page, { status: 204 }); } let page = SimpleCache.getOrSet(path, async () => { return { value: await render(path), // Store the page in the cache for 1 minute. ttl: 60 } }); return new Response(page, { headers: { 'content-type': 'text/plain;charset=UTF-8' } }); } async function render(path) { // expensive/slow function which constructs and returns the contents for a given path await new Promise(resolve => setTimeout(resolve, 10_000)); return path; } ``` # `Migrating from v1 to v2` ## ObjectStore renamed to KVStore We have renamed the `ObjectStore` class to `KVStore`, and the module name from `fastly:object-store` to `fastly:kv-store`. You will need to update your code to use the new class name and module name. Below is the change that would need to be made for the imported module name: ```diff - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; ``` And this is the change that would need to be made for constructing an instance of the class: ```diff - const store = new ObjectStore('my-store'); + const store = new KVStore('my-store'); ``` Here is a full example of migrating an application from ObjectStore to KVStore: ```diff /// - import { ObjectStore } from 'fastly:object-store'; + import { KVStore } from 'fastly:kv-store'; async function app(event) { - const files = new ObjectStore('files'); + const files = new KVStore('files'); await files.put('hello', 'world') const entry = await files.get('hello') return new Response(await entry.text()) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/secret-store/SecretStore/SecretStore.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `SecretStore()` The **`SecretStore` constructor** lets you connect your Fastly Compute application to a Fastly Secret store. A secret store is a persistent, globally distributed store for secrets accessible to Fastly Compute services during request processing. >**Note**: Can only be used when processing requests, not during build-time initialization. ## Syntax ```js new SecretStore(name) ``` > **Note:** `SecretStore()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Parameters - `name` _: string_ - Define a Secret Store instance using the resource link name. ### Return value A new `SecretStore` object. ### Exceptions - `TypeError` - Thrown if no Secret Store exists with the provided name - Thrown if the provided name is longer than 255 in length - Thrown if the provided name is an empty string - Thrown if the provided name contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/secret-store/SecretStore/fromBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # fromBytes The **`fromBytes()`** function is used to create an in-memory secret from an array buffer. >**Note**: This API should be avoided when possible, by instead using [SecretStore.prototype.get](./prototype/get.mdx) to obtain secure secrets. ## Syntax ```js fromBytes(new Uint8Array([1, 2, 3])) ``` ### Parameters None. ### Return value Returns a `SecretStoreEntry`. ================================================ FILE: documentation/versioned_docs/version-3.41.2/secret-store/SecretStore/prototype/get.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStore.prototype.get ▸ **get**(): `string` Gets the value associated with the key `key` in the Secret store. ## Syntax ```js get(key) ``` ### Parameters - `key` _: string_ - The key to retrieve from within the Secret Store. ### Return value If the key does not exist in the Secret Store, this returns a `Promise` which resolves with `null`. If the key does exist in the Secret Store, this returns a `Promise` which resolves with an `SecretStoreEntry`. ## Description Send the given message, converted to a string, to this SecretStore instance's endpoint. The `get()` method requires its `this` value to be a [`SecretStore`](../SecretStore.mdx) object. If the `this` value does not inherit from `SecretStore.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ### Exceptions - `TypeError` - If the provided `key`: - Is an empty string - Is longer than 255 characters - Contains characters other than letters, numbers, dashes (-), underscores (_), and periods (.) ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/secret-store/SecretStoreEntry/prototype/plaintext.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.plaintext ▸ **plaintext**(): `string` Returns the plaintext contents of the SecretStoreEntry instance as String. ## Syntax ```js plaintext() ``` ### Parameters None. ### Return value A String ### Exceptions The `plaintext()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ## Examples In this example we connect to a Secret Store named `'secrets'` and retrieve a secret named `'cat-api-key'` use the value in a Request header. ```js /// import { SecretStore } from "fastly:secret-store"; async function app(event) { const secrets = new SecretStore('secrets') const catApiKey = await secrets.get('cat-api-key') return fetch('/api/cat', { headers: { 'cat-api-key': catApiKey.plaintext() } }) } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/secret-store/SecretStoreEntry/prototype/rawBytes.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # SecretStoreEntry.prototype.rawBytes ▸ **rawBytes**(): `Uint8Array` Returns the raw byte contents of the SecretStoreEntry instance as a Uint8Array. ## Syntax ```js rawBytes() ``` ### Parameters None. ### Return value A Uint8Array ### Exceptions The `rawBytes()` method requires its `this` value to be a `SecretStoreEntry` object. If the `this` value does not inherit from `SecretStoreEntry.prototype`, a [`TypeError`](../../../globals/TypeError/TypeError.mdx) is thrown. ================================================ FILE: documentation/versioned_docs/version-3.41.2/security/inspect.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # inspect The **`inspect()`** function inspects a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). ## Syntax ```js inspect(request, config); ``` ### Parameters - `request` _: Request_ - The Request to get a WAF determination for. - `config` _: object_ - `corp` _: string_ - Set a corp name for the configuration. - This parameter is currently required. - `workspace` _: string_ - Set a workspace name for the configuration. - This parameter is currently required. - `overrideClientIp` _: string_ - Specify an explicit client IP address to inspect. - By default, `inspect` will use the IP address that made the request to the running Compute service, but you may want to use a different IP when service chaining or if requests are proxied from outside of Fastly’s network. ### Return value Returns an `Object` with the `inspect` response, with the following fields: - `waf_response` _: number_ - Security status code. - `redirect_url` _: string | null_ - A redirect URL returned from Security. - `tags` _: string[]_ - Tags returned by Security. - `verdict` _: string_ - The outcome of inspecting a request with Security. It can be one of the following: - `"allow"` - Security indicated that this request is allowed. - `"block"` - Security indicated that this request should be blocked. - `"unauthorized"` - Security indicated that this service is not authorized to inspect a request. - Other verdicts may be returned but not currently documented. - `decision_ms` _: number_ - How long Security spent determining its verdict, in milliseconds. ## Examples ```js /// import { inspect } from "fastly:security"; async function app(event) { const res = inspect(event.request, { corp: "mycorp", workspace: "myws" }); switch (res.verdict) { case "allow": return await fetch(event.request); case "block": return new Response("Request Blocked", { status: 400 }); case "unauthorized": return new Response("Unauthorized", { status: 401 }); default: return new Response("idk", { status: 500 }); } } addEventListener("fetch", (event) => event.respondWith(app(event))); ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/shielding/Shield/Shield.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # `Shield()` Load information about the given shield. Returns an object representing the shield if it is active, or throws an exception if the string is malformed or the shield doesn’t exist. Shield names are defined on [this webpage](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations), in the “shield code” column. For example, the string “pdx-or-us” will look up our Portland, OR, USA shield site, while “paris-fr” will look up our Paris site. If you are using a major cloud provider for your primary origin site, consider looking at the “Recommended for” column, to find the Fastly POP most closely located to the given cloud provider. ## Syntax ```js new Shield(name) ``` > **Note:** `Shield()` can only be constructed with `new`. Attempting to call it without `new` throws a [`TypeError`](../../globals/TypeError/TypeError.mdx). ### Exceptions - `TypeError` - Thrown if no Shield exists with the provided name ## Examples In this example, we create a Shield instance for the Sydney, Australia shield POP. If the code is running on that shield POP, it fetches directly from origin. Otherwise, it routes the request through the shield using an encrypted connection. ```js /// import { Shield } from "fastly:shielding"; async function app(event) { const shield = new Shield('wsi-australia-au'); // If running on the shield POP, fetch from the origin directly if (shield.runningOn()) { return await fetch('https://http-me.fastly.com/anything', { backend: 'httpme' }); } // Otherwise, route the request through the shield using an encrypted connection return await fetch(event.request, { backend: shield.encryptedBackend() }); } addEventListener("fetch", (event) => event.respondWith(app(event))) ``` ================================================ FILE: documentation/versioned_docs/version-3.41.2/shielding/Shield/prototype/encryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.encryptedBackend ▸ **encryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an encrypted connection to the POP. For reference, this is almost always the backend that you want to use. Only use [`Shield::unencryptedBackend`](./unencryptedBackend.mdx) in situations in which you are 100% sure that all the data you will send and receive over the backend is already encrypted. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.41.2/shielding/Shield/prototype/runningOn.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.runningOn ▸ **runningOn**(): `boolean` Returns whether we are currently operating on the given shield. Technically, this may also return true in very isolated incidents in which Fastly is routing traffic from the target shield POP to the POP that this code is running on, but in these situations the results should be approximately identical. (For example, it may be the case that you are asking to shield to ‘pdx-or-us’. But, for load balancing, performance, or other reasons, Fastly is temporarily shifting shielding traffic from Portland to Seattle. In that case, this function may return true for hosts running on ‘bfi-wa-us’, our Seattle site, because effectively the shield has moved to that location. This should give you a slightly faster experience than the alternative, in which this function would return false, you would try to forward your traffic to the Portland site, and then that traffic would be caught and redirected back to Seattle.) ================================================ FILE: documentation/versioned_docs/version-3.41.2/shielding/Shield/prototype/unencryptedBackend.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Shield.prototype.unencryptedBackend ▸ **unencryptedBackend**(configuration?): `Backend` Returns a `Backend` representing an unencrypted connection to the POP. Generally speaking, we encourage users to use [`Shield::encryptedBackend`](./encryptedBackend.mdx) instead of this function. Data sent over this backend – the unencrypted version – will be sent over the open internet, with no protections. In most cases, this is not what you want. However, in some cases – such as when you want to ship large data blobs that you know are already encrypted — using these backends can prevent a double-encryption performance penalty. ## Parameters - `configuration` _: object_ _**optional**_ - `firstByteTimeout` _: number_ _**optional**_ - An optional first byte timeout (in milliseconds) to set on the returned backend. ================================================ FILE: documentation/versioned_docs/version-3.41.2/websocket/createWebsocketHandoff.mdx ================================================ --- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # createWebsocketHandoff The **`createWebsocketHandoff()`** function creates a Response instance which informs Fastly to pass the original Request through Websocket, to the declared backend. ## Syntax ```js createWebsocketHandoff(request, backend) ``` ### Parameters - `request` _: Request_ - The request to pass through Websocket. - `backend` _: string_ - The name of the backend that Websocket should send the request to. - The name has to be between 1 and 254 characters inclusive. - Throws a [`TypeError`](../globals/TypeError/TypeError.mdx) if the value is not valid. I.E. The value is null, undefined, an empty string or a string with more than 254 characters. ### Return value A Response instance is returned, which can then be used via `event.respondWith`. ## Examples In this example application requests to the path `/stream` and sent handled via Websocket. ```js import { createWebsocketHandoff } from "fastly:websocket"; async function handleRequest(event) { try { const url = new URL(event.request.url); if (url.pathname === '/stream') { return createWebsocketHandoff(event.request, 'websocket_backend'); } else { return new Response('oopsie, make a request to /stream for some websocket goodies', { status: 404 }); } } catch (error) { console.error({error}); return new Response(error.message, {status:500}) } } addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); ``` ================================================ FILE: documentation/versioned_sidebars/version-1.13.0-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versioned_sidebars/version-2.5.0-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versioned_sidebars/version-3.38.4-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versioned_sidebars/version-3.39.0-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versioned_sidebars/version-3.39.1-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versioned_sidebars/version-3.39.2-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versioned_sidebars/version-3.39.3-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versioned_sidebars/version-3.40.0-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versioned_sidebars/version-3.40.1-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versioned_sidebars/version-3.41.0-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versioned_sidebars/version-3.41.2-sidebars.json ================================================ { "defaultSidebar": [ { "type": "autogenerated", "dirName": "." } ] } ================================================ FILE: documentation/versions.json ================================================ [ "3.41.2", "3.41.0", "3.40.1", "3.40.0", "3.39.3", "3.39.2", "3.39.1", "3.39.0", "3.38.4", "2.5.0", "1.13.0" ] ================================================ FILE: eslint.config.mjs ================================================ // @ts-check import eslint from '@eslint/js'; import { defineConfig } from 'eslint/config'; import tseslint from 'typescript-eslint'; export default defineConfig([ { files: ['src/**/*.{ts,tsx,js}'], languageOptions: { parserOptions: { projectService: true, }, }, extends: [ eslint.configs.recommended, ...tseslint.configs.recommendedTypeChecked, ...tseslint.configs.stylisticTypeChecked, ], rules: { 'no-fallthrough': 'off', '@typescript-eslint/require-await': 'off', '@typescript-eslint/consistent-type-definitions': 'off', }, }, { ignores: [ 'ci/*', 'dist/*', 'documentation/*', 'integration-tests/*', 'runtime/*', 'tests/*', 'test-d/*', ] }, ]); ================================================ FILE: integration-tests/cli/build-config.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; const cli = await getBinPath({ name: 'js-compute' }); test('should build the fastly condition', async function (t) { const { execute, cleanup, writeFile, exists, path } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); await writeFile('./index.js', `import '#test';`); await writeFile('./test.js', `addEventListener('fetch', function(){})`); await writeFile( './package.json', `{ "type": "module", "imports": { "#test": { "fastly": "./test.js" } } }`, ); t.is(await exists('./app.wasm'), false); const { code, stdout, stderr } = await execute( process.execPath, `${cli} ${path}/index.js ${path}/app.wasm`, ); t.is(await exists('./app.wasm'), true); t.alike(stdout, []); t.alike(stderr, []); t.is(code, 0); }); ================================================ FILE: integration-tests/cli/custom-input-path.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; const cli = await getBinPath({ name: 'js-compute' }); test('should create wasm file and return zero exit code', async function (t) { const { execute, cleanup, writeFile, exists, path } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); await writeFile('./index.js', `addEventListener('fetch', function(){})`); t.is(await exists('./bin/main.wasm'), false); const { code, stdout, stderr } = await execute( process.execPath, `${cli} ${path}/index.js`, ); t.is(await exists('./bin/main.wasm'), true); t.alike(stdout, []); t.alike(stderr, []); t.is(code, 0); }); ================================================ FILE: integration-tests/cli/custom-output-path.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; const cli = await getBinPath({ name: 'js-compute' }); test('should create output directory, wasm file and return zero exit code', async function (t) { const { execute, cleanup, writeFile, exists, path } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); await writeFile('./index.js', `addEventListener('fetch', function(){})`); t.is(await exists('./my/cool/app.wasm'), false); const { code, stdout, stderr } = await execute( process.execPath, `${cli} ${path}/index.js ${path}/my/cool/app.wasm`, ); t.is(await exists('./my/cool/app.wasm'), true); t.alike(stdout, []); t.alike(stderr, []); t.is(code, 0); }); ================================================ FILE: integration-tests/cli/engine-wasm-path-is-not-a-file.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; import { ok } from 'node:assert'; const cli = await getBinPath({ name: 'js-compute' }); test('should return non-zero exit code', async function (t) { const { execute, cleanup, makeDir, writeFile, path } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); await makeDir('./engine.wasm'); await writeFile('./bin/index.js', `addEventListener('fetch', function(){})`); const { code, stdout, stderr } = await execute( process.execPath, `${cli} --engine-wasm ${path}/engine.wasm`, ); t.alike(stdout, []); ok( stderr .toString() .startsWith('Error: The `wasmEngine` path does not point to a file:'), ); ok(stderr.toString().endsWith('engine.wasm')); t.is(code, 1); }); ================================================ FILE: integration-tests/cli/env.test.js ================================================ import test from 'brittle'; import { EnvParser } from '../../dist/env.js'; test('EnvParser should parse single key-value pair', function (t) { const parser = new EnvParser(); parser.parse('NODE_ENV=production'); t.alike(parser.getEnv(), { NODE_ENV: 'production', }); }); test('EnvParser should parse multiple comma-separated values', function (t) { const parser = new EnvParser(); parser.parse('NODE_ENV=production,DEBUG=true,PORT=3000'); t.alike(parser.getEnv(), { NODE_ENV: 'production', DEBUG: 'true', PORT: '3000', }); }); test('EnvParser should merge multiple parse calls', function (t) { const parser = new EnvParser(); parser.parse('NODE_ENV=production'); parser.parse('DEBUG=true'); t.alike(parser.getEnv(), { NODE_ENV: 'production', DEBUG: 'true', }); }); test('EnvParser should inherit existing environment variables', function (t) { const parser = new EnvParser(); // Set up some test environment variables process.env.TEST_VAR1 = 'value1'; process.env.TEST_VAR2 = 'value2'; parser.parse('TEST_VAR1,TEST_VAR2'); t.alike(parser.getEnv(), { TEST_VAR1: 'value1', TEST_VAR2: 'value2', }); // Cleanup delete process.env.TEST_VAR1; delete process.env.TEST_VAR2; }); test('EnvParser should handle mixed inheritance and setting', function (t) { const parser = new EnvParser(); process.env.TEST_VAR = 'inherited'; parser.parse('TEST_VAR,NEW_VAR=set'); t.alike(parser.getEnv(), { TEST_VAR: 'inherited', NEW_VAR: 'set', }); // Cleanup delete process.env.TEST_VAR; }); test('EnvParser should handle values with spaces', function (t) { const parser = new EnvParser(); parser.parse('MESSAGE=Hello World'); t.alike(parser.getEnv(), { MESSAGE: 'Hello World', }); }); test('EnvParser should handle values with equals signs', function (t) { const parser = new EnvParser(); parser.parse('DATABASE_URL=postgres://user:pass@localhost:5432/db'); t.alike(parser.getEnv(), { DATABASE_URL: 'postgres://user:pass@localhost:5432/db', }); }); test('EnvParser should handle empty values', function (t) { const parser = new EnvParser(); parser.parse('EMPTY='); t.alike(parser.getEnv(), { EMPTY: '', }); }); test('EnvParser should handle whitespace', function (t) { const parser = new EnvParser(); parser.parse(' KEY = value with spaces '); t.alike(parser.getEnv(), { KEY: ' value with spaces', // Leading whitespace preserved, trailing removed }); // Test multiple values with whitespace parser.parse(' KEY2 = value2 , KEY3 = value3 '); t.alike(parser.getEnv(), { KEY: ' value with spaces', KEY2: ' value2', KEY3: ' value3', }); }); test('EnvParser should merge and override values', function (t) { const parser = new EnvParser(); parser.parse('KEY=first'); parser.parse('KEY=second'); t.alike(parser.getEnv(), { KEY: 'second', }); }); test('EnvParser should throw on empty key', function (t) { const parser = new EnvParser(); t.exception( () => parser.parse('=value'), 'Invalid environment variable format: =value\nMust be in format KEY=VALUE', ); }); test('EnvParser should handle empty constructor', function (t) { const parser = new EnvParser(); t.alike(parser.getEnv(), {}); }); test('EnvParser should handle multiple commas and whitespace', function (t) { const parser = new EnvParser(); parser.parse('KEY1=value1, KEY2=value2,,,KEY3=value3'); t.alike(parser.getEnv(), { KEY1: 'value1', KEY2: 'value2', KEY3: 'value3', }); }); test('EnvParser should handle values containing escaped characters', function (t) { const parser = new EnvParser(); // This is how Node.js argv will receive it after shell processing parser.parse('A=VERBATIM CONTENTS\\, GO HERE'); // Users will type: --env 'A=VERBATIM CONTENTS\, GO HERE' t.alike(parser.getEnv(), { A: 'VERBATIM CONTENTS, GO HERE', // Comma should be unescaped in final value }); }); ================================================ FILE: integration-tests/cli/input-path-is-not-a-file.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; import { ok } from 'node:assert'; const cli = await getBinPath({ name: 'js-compute' }); test('should return non-zero exit code', async function (t) { const { execute, cleanup, makeDir } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); await makeDir('./bin/index.js'); const { code, stdout, stderr } = await execute(process.execPath, cli); t.alike(stdout, []); ok( stderr .toString() .startsWith('Error: The `input` path does not point to a file:'), ); ok(stderr.toString().endsWith('index.js')); t.is(code, 1); }); ================================================ FILE: integration-tests/cli/invalid.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; import { strictEqual } from 'node:assert'; const cli = await getBinPath({ name: 'js-compute' }); test('should return non-zero exit code on syntax errors', async function (t) { const { execute, cleanup, writeFile } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); await writeFile('./bin/index.js', '\n\n\n"hello";@'); const { code, stdout, stderr } = await execute(process.execPath, cli); t.alike(stdout, []); // TODO: do not even try to fix the mess below if something breaks with it again. Just remove // cli-testing-library dependency entirely and check stderr directly. try { strictEqual( stderr.join('').toString().replace(/\r?\n/g, '').slice(1), ` [ERROR] Expected identifier but found end of file bin/index.js:4:9: 4 │ "hello";@ ╵ ^ Error: Build failed with 1 error: bin/index.js:4:9: ERROR: Expected identifier but found end of file`.replace( /\r?\n/g, '', ), ); } catch { strictEqual( stderr.join('').toString().replace(/\r?\n/g, '').slice(1), ` [ERROR] Expected identifier but found end of file bin/index.js:4:9: 4 │ "hello";@ ╵^ Error: Build failed with 1 error: bin/index.js:4:9: ERROR: Expected identifier but found end of file`.replace( /\r?\n/g, '', ), ); } t.is(code, 1); }); ================================================ FILE: integration-tests/cli/non-existent-engine-wasm-path.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; import { ok } from 'node:assert'; const cli = await getBinPath({ name: 'js-compute' }); test('should return non-zero exit code', async function (t) { const { execute, cleanup, writeFile, path } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); await writeFile('./bin/index.js', `addEventListener('fetch', function(){})`); const { code, stdout, stderr } = await execute( process.execPath, `${cli} --engine-wasm ${path}/engine.wasm`, ); t.alike(stdout, []); ok( stderr .toString() .startsWith( 'Error: The `wasmEngine` path points to a non-existent file:', ), ); ok(stderr.toString().endsWith('engine.wasm')); t.is(code, 1); }); ================================================ FILE: integration-tests/cli/non-existent-input-path.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; import { ok } from 'node:assert'; const cli = await getBinPath({ name: 'js-compute' }); test('should return non-zero exit code', async function (t) { const { execute, cleanup } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); const { code, stdout, stderr } = await execute(process.execPath, cli); t.alike(stdout, []); ok( stderr .toString() .startsWith('Error: The `input` path points to a non-existent file:'), ); ok(stderr.toString().endsWith('index.js')); t.is(code, 1); }); ================================================ FILE: integration-tests/cli/output-path-is-not-a-file.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; import { ok } from 'node:assert'; const cli = await getBinPath({ name: 'js-compute' }); test('should return non-zero exit code', async function (t) { const { execute, cleanup, makeDir, writeFile } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); await makeDir('./bin/main.wasm'); await writeFile('./bin/index.js', `addEventListener('fetch', function(){})`); const { code, stdout, stderr } = await execute(process.execPath, cli); t.alike(stdout, []); ok( stderr .toString() .startsWith('Error: The `output` path points to a directory:'), ); ok(stderr.toString().endsWith('main.wasm')); t.is(code, 1); }); ================================================ FILE: integration-tests/cli/valid.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; const cli = await getBinPath({ name: 'js-compute' }); test('should create wasm file and return zero exit code', async function (t) { const { execute, cleanup, writeFile, exists } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); await writeFile('./bin/index.js', `addEventListener('fetch', function(){})`); t.is(await exists('./bin/main.wasm'), false); const { code, stdout, stderr } = await execute(process.execPath, cli); t.is(await exists('./bin/main.wasm'), true); t.alike(stdout, []); t.alike(stderr, []); t.is(code, 0); }); ================================================ FILE: integration-tests/cli/version.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; const __dirname = dirname(fileURLToPath(import.meta.url)); const packageJson = readFileSync(join(__dirname, '../../package.json'), { encoding: 'utf-8', }); const version = JSON.parse(packageJson).version; const cli = await getBinPath({ name: 'js-compute' }); test('--version should return version number on stdout and zero exit code', async function (t) { const { execute, cleanup } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); const { code, stdout, stderr } = await execute( process.execPath, `${cli} --version`, ); t.is(code, 0); t.alike(stdout, [`js-compute-runtime-cli.js ${version}`]); t.alike(stderr, []); }); test('-V should return version number on stdout and zero exit code', async function (t) { const { execute, cleanup } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); const { code, stdout, stderr } = await execute(process.execPath, `${cli} -V`); t.is(code, 0); t.alike(stdout, [`js-compute-runtime-cli.js ${version}`]); t.alike(stderr, []); }); ================================================ FILE: integration-tests/cli/weval-bin.test.js ================================================ import test from 'brittle'; import { getBinPath } from 'get-bin-path'; import { prepareEnvironment } from '@jakechampion/cli-testing-library'; import { chmodSync } from 'node:fs'; const cli = await getBinPath({ name: 'js-compute' }); const isWindows = process.platform === 'win32'; test('should use --weval-bin when set and AOT is enabled', async function (t) { const { execute, cleanup, writeFile, exists, path } = await prepareEnvironment(); t.teardown(async function () { await cleanup(); }); await writeFile('./index.js', `addEventListener('fetch', function(){})`); await writeFile('./dummy.wasm', ''); const markerPath = `${path}/weval-bin-invoked`; const wrapperFileName = isWindows ? 'weval-wrapper.bat' : 'weval-wrapper.sh'; const wrapperPath = `${path}/${wrapperFileName}`; if (isWindows) { await writeFile( `./${wrapperFileName}`, `@echo off echo invoked > "${markerPath}" exit /b 1 `, ); } else { await writeFile( `./${wrapperFileName}`, `#!/bin/sh echo "invoked" > "${markerPath}" exit 1 `, ); chmodSync(wrapperPath, 0o755); } const { code } = await execute( process.execPath, `${cli} ${path}/index.js ${path}/out.wasm --enable-aot --engine-wasm=${path}/dummy.wasm --weval-bin=${wrapperPath}`, ); t.is(await exists('./weval-bin-invoked'), true); t.is(code, 1); }); ================================================ FILE: integration-tests/js-compute/build-one.sh ================================================ #!/usr/bin/env bash set -euo pipefail if [ "$#" -lt 1 ]; then echo "Usage: $0 " exit 1 fi test="$1" # NOTE: we run `js-compute-runtime` in the test directory, as there are some # assumptions about project path that are derived from the cwd of the executable # instead of the location of the js source. ( cd "$(dirname "${BASH_SOURCE[0]}")/fixtures/$test" npm i fastly compute build -i ) ================================================ FILE: integration-tests/js-compute/cleanupAll.js ================================================ #!/usr/bin/env node // Clean up any stale resources and services left behind by the integration tests import { $ as zx } from 'zx'; import { getPrefixes } from './env.js'; const { SERVICE_PREFIX, ACL_PREFIX, DICTIONARY_PREFIX, CONFIG_STORE_PREFIX, KV_STORE_PREFIX, SECRET_STORE_PREFIX, } = getPrefixes(); function existingList(stores, prefix) { return stores.filter( (store) => store.name?.startsWith(prefix) || store.Name?.startsWith(prefix), ); } const startTime = Date.now(); if (process.env.FASTLY_API_TOKEN === undefined) { try { process.env.FASTLY_API_TOKEN = String( await zx`fastly profile token --quiet`, ).trim(); } catch { console.error( 'No environment variable named FASTLY_API_TOKEN has been set and no default fastly profile exists.', ); console.error( 'In order to run the tests, either create a fastly profile using `fastly profile create` or export a fastly token under the name FASTLY_API_TOKEN', ); process.exit(1); } } const FASTLY_API_TOKEN = process.env.FASTLY_API_TOKEN; async function removeConfigStores(links, services) { console.log('Removing config stores...'); const stores = JSON.parse( await zx`fastly config-store list --quiet --json --token $FASTLY_API_TOKEN`, ); let dictionaries = existingList(stores, DICTIONARY_PREFIX); for (const dictionary of dictionaries) { console.log(`\tDeleting dictionary ${dictionary.name}`); try { await zx`fastly config-store delete --store-id=${dictionary.id} --token $FASTLY_API_TOKEN`; } catch {} } console.log('All dictionaries removed'); let configStores = existingList(stores, CONFIG_STORE_PREFIX); for (const store of configStores) { console.log(`\tDeleting config store ${store.name}`); try { await zx`fastly config-store delete --store-id=${store.id} --token $FASTLY_API_TOKEN`; } catch {} } console.log('All config stores removed'); } async function removeKVStores() { console.log('Removing KV stores...'); const stores = JSON.parse( await zx`fastly kv-store list --quiet --json --token $FASTLY_API_TOKEN`, ).Data; let kvStores = existingList(stores, KV_STORE_PREFIX); for (const store of kvStores) { console.log(`\tDeleting KV store ${store.Name}`); try { await zx`fastly kv-store delete --store-id=${store.StoreID} --quiet --all -y --token $FASTLY_API_TOKEN`; } catch {} } console.log('All KV stores removed'); } async function removeSecretStores(services) { console.log('Removing secret stores...'); const stores = JSON.parse( await zx`fastly secret-store list --quiet --json --token $FASTLY_API_TOKEN`, ); if (!stores) { return; } const secretStores = existingList(stores, SECRET_STORE_PREFIX); for (const store of secretStores) { console.log(`\tDeleting secret store ${store.name}`); try { await zx`fastly secret-store delete --store-id=${store.id} --token $FASTLY_API_TOKEN`; } catch {} } console.log('All secret stores removed'); } async function removeAcls(services) { console.log('Removing ACLs...'); const acls = existingList( JSON.parse( await zx`fastly compute acl list-acls --quiet --json --token $FASTLY_API_TOKEN`, ).data, ACL_PREFIX, ); for (const acl of acls) { console.log(`\tDeleting acl ${acl.name}`); try { await zx`fastly compute acl delete --acl-id=${acl.id} --token $FASTLY_API_TOKEN`; } catch {} } console.log('All ACLs removed'); } async function getServices() { console.log('Getting services...'); let services = JSON.parse( await zx`fastly service list --token $FASTLY_API_TOKEN --json`, ); services = services.filter(({ Name }) => Name.startsWith(SERVICE_PREFIX)); console.log('Services to delete:'); for (const service of services) { console.log('\t', service.Name); } return services; } async function removeServices(services) { console.log('Removing services...'); for (const service of services) { console.log(`\tDeleting service ${service.Name}`); await zx`fastly service delete --force --service-id=${service.ServiceID}`; } console.log('ALl services removed'); } async function removeLinks(services) { console.log('Removing links...'); for (const service of services) { const links = JSON.parse( await zx`fastly resource-link list --service-id=${service.ServiceID} --quiet --json --version latest --token $FASTLY_API_TOKEN`, ); for (const link of links) { console.log( `\tDeleting link between service ${service.Name} and resource ${link.name}`, ); await zx`fastly resource-link delete --version latest --autoclone --id=${link.id} --service-id=${link.service_id} --token $FASTLY_API_TOKEN`; await zx`fastly service-version activate --version latest --service-id=${link.service_id} --token $FASTLY_API_TOKEN`; } } console.log('All links removed'); } const services = await getServices(); await removeLinks(services); await removeConfigStores(services); await removeKVStores(); await removeSecretStores(services); await removeAcls(services); await removeServices(services); console.log( `Cleanup has finished! Took ${(Date.now() - startTime) / 1000} seconds to complete`, ); ================================================ FILE: integration-tests/js-compute/compare-downstream-response.js ================================================ import compareHeaders from './compare-headers.js'; /** * Function to compare a response from a server (Viceroy, Fastly Compute, etc...) * With a JSON Response Object in our config * @param {{ "status": number, "headers": [ [string, string] ], "body": string }} configResponse * @param {import('undici').Dispatcher.ResponseData} actualResponse */ function maybeUint8Array(body) { if (Array.isArray(body) && typeof body[0] === 'number') return new Uint8Array(body); if (typeof body === 'string') return new TextEncoder().encode(body); return body; } /** * @param {Uint8Array[]} buffers * @returns */ function concat(buffers) { const out = new Uint8Array(buffers.reduce((len, buf) => len + buf.length, 0)); let curPos = 0; for (const buf of buffers) { if (!(buf instanceof Uint8Array)) throw new Error('not a uint8 array'); out.set(buf, curPos); curPos += buf.length; } return out; } function bufferToString(actualBodyChunks) { try { return new TextDecoder().decode(concat(actualBodyChunks)); } catch { return concat(actualBodyChunks); } } function bufferEq(a, b) { for (let i = 0; i < a.byteLength; i++) { if (a[i] !== b[i]) return false; } return true; } export async function compareDownstreamResponse( configResponse, actualResponse, actualBodyChunks, ) { // Status if ( configResponse.status !== undefined && configResponse.status != actualResponse.statusCode ) { throw new Error( `[DownstreamResponse: Status mismatch] Expected: ${configResponse.status} - Got: ${actualResponse.statusCode}\n${actualBodyChunks.length ? `\n"${bufferToString(actualBodyChunks)}"` : ''}`, ); } // Headers if (configResponse.headers) { compareHeaders( configResponse.headers, actualResponse.headers, configResponse.headersExhaustive, ); } // Body if ( configResponse.body || configResponse.body_prefix || configResponse.body_suffix ) { if (configResponse.body_prefix) { const body_prefix = maybeUint8Array(configResponse.body_prefix); const actual_prefix = concat(actualBodyChunks).slice( 0, body_prefix.byteLength, ); if (body_prefix.byteLength !== actual_prefix.byteLength) { throw new Error( `[DownstreamResponse: Body Prefix length mismatch] Expected: ${body_prefix.byteLength} - Got ${actual_prefix.byteLength}: \n"${bufferToString(actualBodyChunks)}"`, ); } if (!bufferEq(actual_prefix, body_prefix)) { throw new Error( `[DownstreamResponse: Body Prefix mismatch] Expected: ${body_prefix} - Got ${actual_prefix}:\n"${bufferToString(actualBodyChunks)}"`, ); } } if (configResponse.body_suffix) { const body_suffix = maybeUint8Array(configResponse.body_suffix); const actual_suffix = concat(actualBodyChunks).slice( 0, body_suffix.byteLength, ); if (body_suffix.byteLength !== actual_suffix.byteLength) { throw new Error( `[DownstreamResponse: Body Suffix length mismatch] Expected: ${body_suffix.byteLength} - Got: ${actual_suffix.byteLength}: \n"${bufferToString(actualBodyChunks)}"`, ); } if (!bufferEq(actual_suffix, body_suffix)) { throw new Error( `[DownstreamResponse: Body Suffix mismatch] Expected: ${body_suffix} - Got ${actual_suffix}:\n"${bufferToString(actualBodyChunks)}"`, ); } } // Check if we need to stream the response and check the chunks, or the whole body configResponse.body = maybeUint8Array(configResponse.body); if (configResponse.body instanceof Array) { // Stream down the response let chunkNumber = 0; for (const chunk of actualBodyChunks) { const chunkString = chunk.toString('utf8'); // Check if the chunk is equal to what we expected if (configResponse.body[chunkNumber].includes(chunk.toString('utf8'))) { // Yay! We got a matching Chunk, let's see if this is the end of one of our expected chunks. If so, we need to increment our chunk number :) if ( configResponse.body[chunkNumber].endsWith(chunk.toString('utf8')) ) { chunkNumber++; } } else { throw new Error( `[DownstreamResponse: Body Chunk mismatch] Expected: ${configResponse.body[chunkNumber]} - Got: ${chunkString}`, ); } } if (chunkNumber !== configResponse.body.length) { throw new Error( `[DownstreamResponse: Body Chunk mismatch] Expected: ${configResponse.body} - Got: (Incomplete stream, Number of chunks returned: ${chunkNumber})`, ); } } else if (configResponse.body !== undefined) { // Get the text, and check if it matches the test const downstreamBodyText = new TextDecoder().decode( concat(actualBodyChunks), ); const eq = typeof configResponse.body === 'string' ? downstreamBodyText === configResponse.body : bufferEq(configResponse.body, concat(actualBodyChunks)); if (!eq) { throw new Error( `[DownstreamResponse: Body mismatch] Expected: ${configResponse.body} - Got: ${downstreamBodyText}`, ); } } } } ================================================ FILE: integration-tests/js-compute/compare-headers.js ================================================ /** * * @param {[ * [string, string | string[]] * ] | Record} configHeaders * @param {Headers | { * [string]: string * }} wasmModuleHeaders * @returns */ const compareHeaders = (configHeaders, wasmModuleHeaders, exhaustive) => { if (!configHeaders) { return; } // convert an array of entries into an object of arrays for easier asserting if (Array.isArray(configHeaders)) { const combinedHeaders = Object.create(null); for (const [key, val] of configHeaders) { if (!Object.hasOwnProperty.call(combinedHeaders, key)) { combinedHeaders[key] = val; } else { if (Array.isArray(combinedHeaders[key])) { if (Array.isArray(val)) { combinedHeaders[key] = combinedHeaders[key].concat(val); } else { combinedHeaders[key].push(val); } } else { combinedHeaders[key] = [ combinedHeaders[key], ...(Array.isArray(val) ? val : [val]), ]; } } } configHeaders = combinedHeaders; } if (exhaustive) { const configHeaderNames = Object.keys(configHeaders); const wasmHeaderNames = Object.keys(wasmModuleHeaders); if (configHeaderNames.length !== wasmHeaderNames.length) { throw new Error( `[Header names exhaustive check failed]: Expected ${configHeaderNames.length} header names ${configHeaderNames.join(', ')}, got ${wasmHeaderNames.length} header names ${wasmHeaderNames.join(', ')}`, ); } } for (let [configHeaderKey, configHeaderValue] of Object.entries( configHeaders, )) { let wasmModuleHeaderValue = wasmModuleHeaders[configHeaderKey.toLowerCase()]; if (Array.isArray(configHeaderValue) && configHeaderValue.length === 1) { configHeaderValue = configHeaderValue[0]; } if (Array.isArray(configHeaderValue)) { if (!Array.isArray(wasmModuleHeaderValue)) { throw new Error( `[Header Value mismatch] Expected multiple headers for '${configHeaderKey}', but ony got one.`, ); } if (configHeaderValue.length !== wasmModuleHeaderValue.length) { throw new Error( `[Header Value mismatch] Expected ${configHeaderValue.length} headers for '${configHeaderKey}', but got ${wasmModuleHeaderValue.length}.`, ); } for (const [idx, configValue] of configHeaderValue.entries()) { if (wasmModuleHeaderValue[idx] !== configValue) { throw new Error( `[Header Value mismatch] Expected '${configValue}' for header item ${idx} of '${configHeaderKey}', but got '${wasmModuleHeaderValue[idx]}'.`, ); } } } else if ( configHeaderValue !== true && wasmModuleHeaderValue !== configHeaderValue ) { throw new Error( `[Header Value mismatch] Expected: '${configHeaderKey}: ${configHeaderValue}' (${configHeaderValue.length}), got '${configHeaderKey}: ${wasmModuleHeaderValue}' (${wasmModuleHeaderValue?.length})`, ); } } }; export default compareHeaders; ================================================ FILE: integration-tests/js-compute/env.js ================================================ export const GLOBAL_PREFIX = 'js_integration_test_'; function applyGlobalPrefix(map) { for (const key in map) { map[key] = GLOBAL_PREFIX + map[key]; } return map; } export function getEnv(serviceName) { return applyGlobalPrefix({ DICTIONARY_NAME: `aZ2__2${serviceName ? '__' + serviceName.replace(/-/g, '_') : ''}`, CONFIG_STORE_NAME: `config${serviceName ? '__' + serviceName.replace(/-/g, '_') : ''}`, KV_STORE_NAME: `kv-store${serviceName ? '--' + serviceName : ''}`, SECRET_STORE_NAME: `secret-store${serviceName ? '--' + serviceName : ''}`, ACL_NAME: `acl${serviceName ? '__' + serviceName.replace(/-/g, '_') : ''}`, }); } export function getPrefixes() { return applyGlobalPrefix({ SERVICE_PREFIX: `app-`, DICTIONARY_PREFIX: `aZ2__2`, CONFIG_STORE_PREFIX: `config`, KV_STORE_PREFIX: `kv-store`, SECRET_STORE_PREFIX: `secret-store`, ACL_PREFIX: `acl`, }); } ================================================ FILE: integration-tests/js-compute/fixtures/app/.eslintrc.cjs ================================================ module.exports = { env: { es2021: true, }, extends: 'eslint:recommended', overrides: [], parserOptions: { ecmaVersion: 'latest', sourceType: 'module', }, rules: {}, }; ================================================ FILE: integration-tests/js-compute/fixtures/app/fastly.toml.in ================================================ # This file describes a Fastly Compute package. To learn more visit: # https://developer.fastly.com/reference/fastly-toml/ authors = ["jchampion@fastly.com"] description = "" language = "other" manifest_version = 2 name = "js-test-app" service_id = "" [scripts] build = "node ../../../../dist/cli/js-compute-runtime-cli.js --env FASTLY_DEBUG_LOGGING,ACL_NAME,CONFIG_STORE_NAME,DICTIONARY_NAME,KV_STORE_NAME,SECRET_STORE_NAME,LOCAL_TEST,TEST=\"foo\" --enable-experimental-high-resolution-time-methods src/index.js" [local_server] [local_server.backends] [local_server.backends.TheOrigin] url = "https://compute-sdk-test-backend.edgecompute.app" override_host = "compute-sdk-test-backend.edgecompute.app" [local_server.backends.TheOrigin2] url = "https://compute-sdk-test-backend.edgecompute.app" override_host = "compute-sdk-test-backend.edgecompute.app" [local_server.backends.httpme] url = "https://http-me.fastly.dev" override_host = "http-me.fastly.dev" [local_server.config_stores] [local_server.config_stores.CONFIG_STORE_NAME] format = "inline-toml" [local_server.config_stores.CONFIG_STORE_NAME.contents] "twitter" = "https://twitter.com/fastly" [local_server.config_stores."DICTIONARY_NAME"] format = "inline-toml" [local_server.config_stores."DICTIONARY_NAME".contents] "twitter" = "https://twitter.com/fastly" [local_server.geolocation] format = "inline-toml" [local_server.geolocation.addresses] [local_server.geolocation.addresses."2.216.196.179"] as_name = "sky uk limited" as_number = 5607 area_code = 0 city = "bircotes" conn_speed = "broadband" conn_type = "wifi" continent = "EU" country_code = "GB" country_code3 = "GBR" country_name = "united kingdom" gmt_offset = 0 latitude = 53.42 longitude = -1.05 metro_code = 826039 postal_code = "dn11 8af" proxy_description = "?" proxy_type = "?" region = "NTT" utc_offset = 0 [local_server.geolocation.addresses."2607:f0d0:1002:51::4"] as_name = "softlayer technologies inc." as_number = 36351 area_code = 214 city = "dallas" conn_speed = "broadband" conn_type = "wired" continent = "NA" country_code = "US" country_code3 = "USA" country_name = "united states" gmt_offset = -600 latitude = 32.94 longitude = -96.84 metro_code = 623 postal_code = "75244" proxy_description = "?" proxy_type = "hosting" region = "TX" utc_offset = -600 [local_server.kv_stores] [[local_server.kv_stores.KV_STORE_NAME]] key = "placeholder" data = 'placholder' [local_server.secret_stores] [[local_server.secret_stores.SECRET_STORE_NAME]] key = "first" data = "This is also some secret data" [[local_server.secret_stores.SECRET_STORE_NAME]] key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" data = "This is some secret data" [local_server.device_detection] format = "inline-toml" [local_server.device_detection.user_agents] [local_server.device_detection.user_agents."Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 FBAN/FBIOS;FBAV/8.0.0.28.18;FBBV/1665515;FBDV/iPhone4,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/7.0.4;FBSS/2; FBCR/Telekom.de;FBID/phone;FBLC/de_DE;FBOP/5"] user_agent = {} os = {} device = {name = "iPhone", brand = "Apple", model = "iPhone4,1", hwtype = "Mobile Phone", is_ereader = false, is_gameconsole = false, is_mediaplayer = false, is_mobile = true, is_smarttv = false, is_tablet = false, is_tvplayer = false, is_desktop = false, is_touchscreen = true } [local_server.device_detection.user_agents."ghosts-app/1.0.2.1 (ASUSTeK COMPUTER INC.; X550CC; Windows 8 (X86); en)"] user_agent = {} os = {} device = {name = "Asus TeK", brand = "Asus", model = "TeK", is_desktop = false } [local_server.device_detection.user_agents."Googlebot/2.1 (+http://www.google.com/bot.html)"] user_agent = {} os = {} device = {name = "Googlebot", brand = "Google", model = "bot", is_desktop = false, is_bot = true } [setup] [setup.backends] [setup.backends.httpme] address = "http-me.fastly.dev" port = 443 [setup.backends.TheOrigin] address = "compute-sdk-test-backend.edgecompute.app" port = 443 [setup.backends.TheOrigin2] address = "compute-sdk-test-backend.edgecompute.app" port = 443 ================================================ FILE: integration-tests/js-compute/fixtures/app/message.txt ================================================ hello includeBytes ================================================ FILE: integration-tests/js-compute/fixtures/app/src/assertions.js ================================================ // Testing/Assertion functions // export async function sleep(milliseconds) { return new Promise((resolve) => { setTimeout(resolve, milliseconds); }); } // TODO: Implement ReadableStream getIterator() and [@@asyncIterator]() methods export async function streamToString(stream) { const decoder = new TextDecoder(); let string = ''; let reader = stream.getReader(); // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await reader.read(); if (done) { return string; } string += decoder.decode(value); } } export function iteratableToStream(iterable) { return new ReadableStream({ async pull(controller) { for await (const value of iterable) { controller.enqueue(value); } controller.close(); }, }); } export function pass(message = '') { return new Response(message); } function prettyPrintSymbol(a) { if (typeof a === 'symbol') { return String(a); } return a; } export function assert(actual, expected, code) { if (!deepEqual(actual, expected)) { throw new Error( `Expected \`${code}\` to equal \`${JSON.stringify(prettyPrintSymbol(expected))}\` - Found \`${JSON.stringify(prettyPrintSymbol(actual))}\``, ); } } export { assert as strictEqual }; export function ok(truthy, code) { if (!truthy) { throw new Error( `Expected ${code ? code + ' ' : ''}to be truthy - Found \`${JSON.stringify(prettyPrintSymbol(truthy))}\``, ); } } export async function assertResolves(func) { try { await func(); } catch (error) { throw new Error( `Expected \`${func.toString()}\` to resolve - Found it rejected: ${error.name}: ${error.message}`, ); } } export async function assertRejects(func, errorClass, errorMessage) { try { await func(); } catch (error) { if (errorClass) { if (error instanceof errorClass === false) { throw new Error( `Expected \`${func.toString()}\` to reject instance of \`${errorClass.name}\` - Found instance of \`${error.name}\``, ); } } if (errorMessage) { if (error.message !== errorMessage) { throw new Error( `Expected \`${func.toString()}\` to reject error message of \`${errorMessage}\` - Found \`${error.message}\``, ); } } return; } throw new Error( `Expected \`${func.toString()}\` to reject - Found it did not reject`, ); } export function assertThrows(func, errorClass, errorMessage) { try { func(); } catch (error) { if (errorClass) { if (error instanceof errorClass === false) { throw new Error( `Expected \`${func.toString()}\` to throw instance of \`${errorClass.name}\` - Found instance of \`${error.name}\`: ${error.message}\n${error.stack}`, ); } } if (errorMessage) { if (error.message !== errorMessage) { throw new Error( `Expected \`${func.toString()}\` to throw error message of \`${errorMessage}\` - Found \`${error.message}\``, ); } } return; } throw new Error( `Expected \`${func.toString()}\` to throw - Found it did not throw`, ); } export function assertDoesNotThrow(func) { try { func(); } catch (error) { throw new Error( `Expected \`${func.toString()}\` to not throw - Found it did throw: ${error.name}: ${error.message}`, ); } } export function deepStrictEqual(a, b) { if (!deepEqual(a, b)) { throw new Error(`Expected ${a} to equal ${b}`); } } export function deepEqual(a, b) { var aKeys; var bKeys; var typeA; var typeB; var key; var i; typeA = typeof a; typeB = typeof b; if (a === null || typeA !== 'object') { if (b === null || typeB !== 'object') { return a === b; } return false; } // Case: `a` is of type 'object' if (b === null || typeB !== 'object') { return false; } if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) { return false; } if (a instanceof Date) { return a.getTime() === b.getTime(); } if (a instanceof RegExp) { return a.source === b.source && a.flags === b.flags; } if (a instanceof Error) { if (a.message !== b.message || a.name !== b.name) { return false; } } aKeys = Object.keys(a); bKeys = Object.keys(b); if (aKeys.length !== bKeys.length) { return false; } aKeys.sort(); bKeys.sort(); // Cheap key test: for (i = 0; i < aKeys.length; i++) { if (aKeys[i] !== bKeys[i]) { return false; } } // Possibly expensive deep equality test for each corresponding key: for (i = 0; i < aKeys.length; i++) { key = aKeys[i]; if (!deepEqual(a[key], b[key])) { return false; } } return typeA === typeB; } ================================================ FILE: integration-tests/js-compute/fixtures/app/src/async-select.js ================================================ import { routes } from './routes'; routes.set('/async-select/hello', () => { let requestsData = [ { url: 'https://compute-sdk-test-backend.edgecompute.app/async_select_1', backend: 'TheOrigin', header: 'fooname', }, { url: 'https://compute-sdk-test-backend.edgecompute.app/async_select_2', backend: 'TheOrigin2', header: 'barname', }, ]; let pending = requestsData.map((data) => { let request = new Request(data.url); return fetch(request, { backend: data.backend }); }); return processUpstreamRequests(pending, requestsData); }); async function processUpstreamRequests(requests, requestsData) { // Create our response headers we will be sending downstream let responseHeaders = new Headers(); // Loop through our requests for await (let response of select(requests)) { // Check which response we got, so we know which header to // copy over to our response headers let { header } = requestsData.find((data) => data.url == response.url); // Set the appropriate header on our response let headerValue = response.headers.get(header); if (headerValue == null) { throw new Error( 'No header value on the response from the request with url ' + response.url + ' and with the header name: ' + header, ); } responseHeaders.set(header, headerValue); } // Send our response downstream return new Response('pong', { headers: responseHeaders, }); } async function* select(promises) { promises = promises.map((promise) => { promise.finally(() => { promises.splice(promises.indexOf(promise), 1); }); return promise; }); while (promises.length) { yield await Promise.any(promises); } } ================================================ FILE: integration-tests/js-compute/fixtures/app/src/btoa.js ================================================ import { assert, assertThrows } from './assertions.js'; import { routes } from './routes'; routes.set('/btoa', () => { // btoa { var everything = ''; for (var i = 0; i < 256; i++) { everything += String.fromCharCode(i); } assert( btoa(everything), 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==', ); assert(btoa(42), btoa('42')); assert(btoa(null), btoa('null')); assert(btoa({ x: 1 }), btoa('[object Object]')); assertThrows(() => btoa(), TypeError); assertThrows(() => btoa('🐱')); assert(btoa(''), '', `btoa("")`); assert(btoa('ab'), 'YWI=', `btoa("ab")`); assert(btoa('abc'), 'YWJj', `btoa("abc")`); assert(btoa('abcd'), 'YWJjZA==', `btoa("abcd")`); assert(btoa('abcde'), 'YWJjZGU=', `btoa("abcde")`); assert(btoa('ÿÿÀ'), '///A', `btoa("ÿÿÀ")`); assert(btoa('\0a'), 'AGE=', `btoa("\\0a")`); assert(btoa('a\0b'), 'YQBi', `btoa("a\\0b")`); assert(btoa(undefined), 'dW5kZWZpbmVk', `btoa(undefined)`); assert(btoa(null), 'bnVsbA==', `btoa(null)`); assert(btoa(7), 'Nw==', `btoa(7)`); assert(btoa(12), 'MTI=', `btoa(12)`); assert(btoa(1.5), 'MS41', `btoa(1.5)`); assert(btoa(true), 'dHJ1ZQ==', `btoa(true)`); assert(btoa(false), 'ZmFsc2U=', `btoa(false)`); assert(btoa(NaN), 'TmFO', `btoa(NaN)`); assert(btoa(Infinity), 'SW5maW5pdHk=', `btoa(Infinity)`); assert(btoa(-Infinity), 'LUluZmluaXR5', `btoa(-Infinity)`); assert(btoa(0), 'MA==', `btoa(0)`); assert(btoa(-0), 'MA==', `btoa(-0)`); assert(btoa('\0'), 'AA==', `btoa("\\0")`); assert(btoa('\x01'), 'AQ==', `btoa("\\x01")`); assert(btoa('\x02'), 'Ag==', `btoa("\\x02")`); assert(btoa('\x03'), 'Aw==', `btoa("\\x03")`); assert(btoa('\x04'), 'BA==', `btoa("\\x04")`); assert(btoa('\x05'), 'BQ==', `btoa("\\x05")`); assert(btoa('\x06'), 'Bg==', `btoa("\\x06")`); assert(btoa('\x07'), 'Bw==', `btoa("\\x07")`); assert(btoa('\b'), 'CA==', `btoa("\\b")`); assert(btoa('\t'), 'CQ==', `btoa("\\t")`); assert(btoa('\n'), 'Cg==', `btoa("\\n")`); assert(btoa('\v'), 'Cw==', `btoa("\\v")`); assert(btoa('\f'), 'DA==', `btoa("\\f")`); assert(btoa('\r'), 'DQ==', `btoa("\\r")`); assert(btoa('\x0e'), 'Dg==', `btoa("\\x0e")`); assert(btoa('\x0f'), 'Dw==', `btoa("\\x0f")`); assert(btoa('\x10'), 'EA==', `btoa("\\x10")`); assert(btoa('\x11'), 'EQ==', `btoa("\\x11")`); assert(btoa('\x12'), 'Eg==', `btoa("\\x12")`); assert(btoa('\x13'), 'Ew==', `btoa("\\x13")`); assert(btoa('\x14'), 'FA==', `btoa("\\x14")`); assert(btoa('\x15'), 'FQ==', `btoa("\\x15")`); assert(btoa('\x16'), 'Fg==', `btoa("\\x16")`); assert(btoa('\x17'), 'Fw==', `btoa("\\x17")`); assert(btoa('\x18'), 'GA==', `btoa("\\x18")`); assert(btoa('\x19'), 'GQ==', `btoa("\\x19")`); assert(btoa('\x1a'), 'Gg==', `btoa("\\x1a")`); assert(btoa('\x1b'), 'Gw==', `btoa("\\x1b")`); assert(btoa('\x1c'), 'HA==', `btoa("\\x1c")`); assert(btoa('\x1d'), 'HQ==', `btoa("\\x1d")`); assert(btoa('\x1e'), 'Hg==', `btoa("\\x1e")`); assert(btoa('\x1f'), 'Hw==', `btoa("\\x1f")`); assert(btoa(' '), 'IA==', `btoa(" ")`); assert(btoa('!'), 'IQ==', `btoa("!")`); assert(btoa('#'), 'Iw==', `btoa("#")`); assert(btoa('$'), 'JA==', `btoa("$")`); assert(btoa('%'), 'JQ==', `btoa("%")`); assert(btoa('&'), 'Jg==', `btoa("&")`); assert(btoa("'"), 'Jw==', `btoa("'")`); assert(btoa('('), 'KA==', `btoa("(")`); assert(btoa(')'), 'KQ==', `btoa(")")`); assert(btoa('*'), 'Kg==', `btoa("*")`); assert(btoa('+'), 'Kw==', `btoa("+")`); assert(btoa(','), 'LA==', `btoa(",")`); assert(btoa('-'), 'LQ==', `btoa("-")`); assert(btoa('.'), 'Lg==', `btoa(".")`); assert(btoa('/'), 'Lw==', `btoa("/")`); assert(btoa('0'), 'MA==', `btoa("0")`); assert(btoa('1'), 'MQ==', `btoa("1")`); assert(btoa('2'), 'Mg==', `btoa("2")`); assert(btoa('3'), 'Mw==', `btoa("3")`); assert(btoa('4'), 'NA==', `btoa("4")`); assert(btoa('5'), 'NQ==', `btoa("5")`); assert(btoa('6'), 'Ng==', `btoa("6")`); assert(btoa('7'), 'Nw==', `btoa("7")`); assert(btoa('8'), 'OA==', `btoa("8")`); assert(btoa('9'), 'OQ==', `btoa("9")`); assert(btoa(':'), 'Og==', `btoa(":")`); assert(btoa(';'), 'Ow==', `btoa(";")`); assert(btoa('<'), 'PA==', `btoa("<")`); assert(btoa('='), 'PQ==', `btoa("=")`); assert(btoa('>'), 'Pg==', `btoa(">")`); assert(btoa('?'), 'Pw==', `btoa("?")`); assert(btoa('@'), 'QA==', `btoa("@")`); assert(btoa('A'), 'QQ==', `btoa("A")`); assert(btoa('B'), 'Qg==', `btoa("B")`); assert(btoa('C'), 'Qw==', `btoa("C")`); assert(btoa('D'), 'RA==', `btoa("D")`); assert(btoa('E'), 'RQ==', `btoa("E")`); assert(btoa('F'), 'Rg==', `btoa("F")`); assert(btoa('G'), 'Rw==', `btoa("G")`); assert(btoa('H'), 'SA==', `btoa("H")`); assert(btoa('I'), 'SQ==', `btoa("I")`); assert(btoa('J'), 'Sg==', `btoa("J")`); assert(btoa('K'), 'Sw==', `btoa("K")`); assert(btoa('L'), 'TA==', `btoa("L")`); assert(btoa('M'), 'TQ==', `btoa("M")`); assert(btoa('N'), 'Tg==', `btoa("N")`); assert(btoa('O'), 'Tw==', `btoa("O")`); assert(btoa('P'), 'UA==', `btoa("P")`); assert(btoa('Q'), 'UQ==', `btoa("Q")`); assert(btoa('R'), 'Ug==', `btoa("R")`); assert(btoa('S'), 'Uw==', `btoa("S")`); assert(btoa('T'), 'VA==', `btoa("T")`); assert(btoa('U'), 'VQ==', `btoa("U")`); assert(btoa('V'), 'Vg==', `btoa("V")`); assert(btoa('W'), 'Vw==', `btoa("W")`); assert(btoa('X'), 'WA==', `btoa("X")`); assert(btoa('Y'), 'WQ==', `btoa("Y")`); assert(btoa('Z'), 'Wg==', `btoa("Z")`); assert(btoa('['), 'Ww==', `btoa("[")`); assert(btoa('\\'), 'XA==', `btoa("\\\\")`); assert(btoa(']'), 'XQ==', `btoa("]")`); assert(btoa('^'), 'Xg==', `btoa("^")`); assert(btoa('_'), 'Xw==', `btoa("_")`); assert(btoa('a'), 'YQ==', `btoa("a")`); assert(btoa('b'), 'Yg==', `btoa("b")`); assert(btoa('c'), 'Yw==', `btoa("c")`); assert(btoa('d'), 'ZA==', `btoa("d")`); assert(btoa('e'), 'ZQ==', `btoa("e")`); assert(btoa('f'), 'Zg==', `btoa("f")`); assert(btoa('g'), 'Zw==', `btoa("g")`); assert(btoa('h'), 'aA==', `btoa("h")`); assert(btoa('i'), 'aQ==', `btoa("i")`); assert(btoa('j'), 'ag==', `btoa("j")`); assert(btoa('k'), 'aw==', `btoa("k")`); assert(btoa('l'), 'bA==', `btoa("l")`); assert(btoa('m'), 'bQ==', `btoa("m")`); assert(btoa('n'), 'bg==', `btoa("n")`); assert(btoa('o'), 'bw==', `btoa("o")`); assert(btoa('p'), 'cA==', `btoa("p")`); assert(btoa('q'), 'cQ==', `btoa("q")`); assert(btoa('r'), 'cg==', `btoa("r")`); assert(btoa('s'), 'cw==', `btoa("s")`); assert(btoa('t'), 'dA==', `btoa("t")`); assert(btoa('u'), 'dQ==', `btoa("u")`); assert(btoa('v'), 'dg==', `btoa("v")`); assert(btoa('w'), 'dw==', `btoa("w")`); assert(btoa('x'), 'eA==', `btoa("x")`); assert(btoa('y'), 'eQ==', `btoa("y")`); assert(btoa('z'), 'eg==', `btoa("z")`); assert(btoa('{'), 'ew==', `btoa("{")`); assert(btoa('|'), 'fA==', `btoa("|")`); assert(btoa('}'), 'fQ==', `btoa("}")`); assert(btoa('~'), 'fg==', `btoa("~")`); assert(btoa(''), 'fw==', `btoa("")`); assert(btoa('€'), 'gA==', `btoa("€")`); assert(btoa(''), 'gQ==', `btoa("")`); assert(btoa('‚'), 'gg==', `btoa("‚")`); assert(btoa('ƒ'), 'gw==', `btoa("ƒ")`); assert(btoa('„'), 'hA==', `btoa("„")`); // eslint-disable-next-line no-irregular-whitespace assert(btoa('…'), 'hQ==', `btoa("…")`); assert(btoa('†'), 'hg==', `btoa("†")`); assert(btoa('‡'), 'hw==', `btoa("‡")`); assert(btoa('ˆ'), 'iA==', `btoa("ˆ")`); assert(btoa('‰'), 'iQ==', `btoa("‰")`); assert(btoa('Š'), 'ig==', `btoa("Š")`); assert(btoa('‹'), 'iw==', `btoa("‹")`); assert(btoa('Œ'), 'jA==', `btoa("Œ")`); assert(btoa(''), 'jQ==', `btoa("")`); assert(btoa('Ž'), 'jg==', `btoa("Ž")`); assert(btoa(''), 'jw==', `btoa("")`); assert(btoa(''), 'kA==', `btoa("")`); assert(btoa('‘'), 'kQ==', `btoa("‘")`); assert(btoa('’'), 'kg==', `btoa("’")`); assert(btoa('“'), 'kw==', `btoa("“")`); assert(btoa('”'), 'lA==', `btoa("”")`); assert(btoa('•'), 'lQ==', `btoa("•")`); assert(btoa('–'), 'lg==', `btoa("–")`); assert(btoa('—'), 'lw==', `btoa("—")`); assert(btoa('˜'), 'mA==', `btoa("˜")`); assert(btoa('™'), 'mQ==', `btoa("™")`); assert(btoa('š'), 'mg==', `btoa("š")`); assert(btoa('›'), 'mw==', `btoa("›")`); assert(btoa('œ'), 'nA==', `btoa("œ")`); assert(btoa(''), 'nQ==', `btoa("")`); assert(btoa('ž'), 'ng==', `btoa("ž")`); assert(btoa('Ÿ'), 'nw==', `btoa("Ÿ")`); // eslint-disable-next-line no-irregular-whitespace assert(btoa(' '), 'oA==', `btoa(" ")`); assert(btoa('¡'), 'oQ==', `btoa("¡")`); assert(btoa('¢'), 'og==', `btoa("¢")`); assert(btoa('£'), 'ow==', `btoa("£")`); assert(btoa('¤'), 'pA==', `btoa("¤")`); assert(btoa('¥'), 'pQ==', `btoa("¥")`); assert(btoa('¦'), 'pg==', `btoa("¦")`); assert(btoa('§'), 'pw==', `btoa("§")`); assert(btoa('¨'), 'qA==', `btoa("¨")`); assert(btoa('©'), 'qQ==', `btoa("©")`); assert(btoa('ª'), 'qg==', `btoa("ª")`); assert(btoa('«'), 'qw==', `btoa("«")`); assert(btoa('¬'), 'rA==', `btoa("¬")`); assert(btoa('­'), 'rQ==', `btoa("­")`); assert(btoa('®'), 'rg==', `btoa("®")`); assert(btoa('¯'), 'rw==', `btoa("¯")`); assert(btoa('°'), 'sA==', `btoa("°")`); assert(btoa('±'), 'sQ==', `btoa("±")`); assert(btoa('²'), 'sg==', `btoa("²")`); assert(btoa('³'), 'sw==', `btoa("³")`); assert(btoa('´'), 'tA==', `btoa("´")`); assert(btoa('µ'), 'tQ==', `btoa("µ")`); assert(btoa('¶'), 'tg==', `btoa("¶")`); assert(btoa('·'), 'tw==', `btoa("·")`); assert(btoa('¸'), 'uA==', `btoa("¸")`); assert(btoa('¹'), 'uQ==', `btoa("¹")`); assert(btoa('º'), 'ug==', `btoa("º")`); assert(btoa('»'), 'uw==', `btoa("»")`); assert(btoa('¼'), 'vA==', `btoa("¼")`); assert(btoa('½'), 'vQ==', `btoa("½")`); assert(btoa('¾'), 'vg==', `btoa("¾")`); assert(btoa('¿'), 'vw==', `btoa("¿")`); assert(btoa('À'), 'wA==', `btoa("À")`); assert(btoa('Á'), 'wQ==', `btoa("Á")`); assert(btoa('Â'), 'wg==', `btoa("Â")`); assert(btoa('Ã'), 'ww==', `btoa("Ã")`); assert(btoa('Ä'), 'xA==', `btoa("Ä")`); assert(btoa('Å'), 'xQ==', `btoa("Å")`); assert(btoa('Æ'), 'xg==', `btoa("Æ")`); assert(btoa('Ç'), 'xw==', `btoa("Ç")`); assert(btoa('È'), 'yA==', `btoa("È")`); assert(btoa('É'), 'yQ==', `btoa("É")`); assert(btoa('Ê'), 'yg==', `btoa("Ê")`); assert(btoa('Ë'), 'yw==', `btoa("Ë")`); assert(btoa('Ì'), 'zA==', `btoa("Ì")`); assert(btoa('Í'), 'zQ==', `btoa("Í")`); assert(btoa('Î'), 'zg==', `btoa("Î")`); assert(btoa('Ï'), 'zw==', `btoa("Ï")`); assert(btoa('Ð'), '0A==', `btoa("Ð")`); assert(btoa('Ñ'), '0Q==', `btoa("Ñ")`); assert(btoa('Ò'), '0g==', `btoa("Ò")`); assert(btoa('Ó'), '0w==', `btoa("Ó")`); assert(btoa('Ô'), '1A==', `btoa("Ô")`); assert(btoa('Õ'), '1Q==', `btoa("Õ")`); assert(btoa('Ö'), '1g==', `btoa("Ö")`); assert(btoa('×'), '1w==', `btoa("×")`); assert(btoa('Ø'), '2A==', `btoa("Ø")`); assert(btoa('Ù'), '2Q==', `btoa("Ù")`); assert(btoa('Ú'), '2g==', `btoa("Ú")`); assert(btoa('Û'), '2w==', `btoa("Û")`); assert(btoa('Ü'), '3A==', `btoa("Ü")`); assert(btoa('Ý'), '3Q==', `btoa("Ý")`); assert(btoa('Þ'), '3g==', `btoa("Þ")`); assert(btoa('ß'), '3w==', `btoa("ß")`); assert(btoa('à'), '4A==', `btoa("à")`); assert(btoa('á'), '4Q==', `btoa("á")`); assert(btoa('â'), '4g==', `btoa("â")`); assert(btoa('ã'), '4w==', `btoa("ã")`); assert(btoa('ä'), '5A==', `btoa("ä")`); assert(btoa('å'), '5Q==', `btoa("å")`); assert(btoa('æ'), '5g==', `btoa("æ")`); assert(btoa('ç'), '5w==', `btoa("ç")`); assert(btoa('è'), '6A==', `btoa("è")`); assert(btoa('é'), '6Q==', `btoa("é")`); assert(btoa('ê'), '6g==', `btoa("ê")`); assert(btoa('ë'), '6w==', `btoa("ë")`); assert(btoa('ì'), '7A==', `btoa("ì")`); assert(btoa('í'), '7Q==', `btoa("í")`); assert(btoa('î'), '7g==', `btoa("î")`); assert(btoa('ï'), '7w==', `btoa("ï")`); assert(btoa('ð'), '8A==', `btoa("ð")`); assert(btoa('ñ'), '8Q==', `btoa("ñ")`); assert(btoa('ò'), '8g==', `btoa("ò")`); assert(btoa('ó'), '8w==', `btoa("ó")`); assert(btoa('ô'), '9A==', `btoa("ô")`); assert(btoa('õ'), '9Q==', `btoa("õ")`); assert(btoa('ö'), '9g==', `btoa("ö")`); assert(btoa('÷'), '9w==', `btoa("÷")`); assert(btoa('ø'), '+A==', `btoa("ø")`); assert(btoa('ù'), '+Q==', `btoa("ù")`); assert(btoa('ú'), '+g==', `btoa("ú")`); assert(btoa('û'), '+w==', `btoa("û")`); assert(btoa('ü'), '/A==', `btoa("ü")`); assert(btoa('ý'), '/Q==', `btoa("ý")`); assert(btoa('þ'), '/g==', `btoa("þ")`); assert(btoa('ÿ'), '/w==', `btoa("ÿ")`); } // atob { assert(atob(''), '', `atob("")`); assert(atob('abcd'), 'i·\x1D'); assert(atob(' abcd'), 'i·\x1D'); assert(atob('abcd '), 'i·\x1D'); assertThrows(() => atob(' abcd===')); assertThrows(() => atob('abcd=== ')); assertThrows(() => atob('abcd ===')); assertThrows(() => atob('a')); assert(atob('ab'), 'i'); assert(atob('abc'), 'i·'); assertThrows(() => atob('abcde')); assertThrows(() => atob('𐀀')); assertThrows(() => atob('=')); assertThrows(() => atob('==')); assertThrows(() => atob('===')); assertThrows(() => atob('====')); assertThrows(() => atob('=====')); assertThrows(() => atob('a=')); assertThrows(() => atob('a==')); assertThrows(() => atob('a===')); assertThrows(() => atob('a====')); assertThrows(() => atob('a=====')); assertThrows(() => atob('ab=')); assert(atob('ab=='), 'i'); assertThrows(() => atob('ab===')); assertThrows(() => atob('ab====')); assertThrows(() => atob('ab=====')); assert(atob('abc='), 'i·'); assertThrows(() => atob('abc==')); assertThrows(() => atob('abc===')); assertThrows(() => atob('abc====')); assertThrows(() => atob('abc=====')); assertThrows(() => atob('abcd=')); assertThrows(() => atob('abcd==')); assertThrows(() => atob('abcd===')); assertThrows(() => atob('abcd====')); assertThrows(() => atob('abcd=====')); assertThrows(() => atob('abcde=')); assertThrows(() => atob('abcde==')); assertThrows(() => atob('abcde===')); assertThrows(() => atob('abcde====')); assertThrows(() => atob('abcde=====')); assertThrows(() => atob('=a')); assertThrows(() => atob('=a=')); assertThrows(() => atob('a=b')); assertThrows(() => atob('a=b=')); assertThrows(() => atob('ab=c')); assertThrows(() => atob('ab=c=')); assertThrows(() => atob('abc=d')); assertThrows(() => atob('abc=d=')); assertThrows(() => atob('ab\u000Bcd')); assertThrows(() => atob('ab\u3000cd')); assertThrows(() => atob('ab\u3001cd')); assert(atob('ab\tcd'), 'i·\x1D'); assert(atob('ab\ncd'), 'i·\x1D'); assert(atob('ab\fcd'), 'i·\x1D'); assert(atob('ab\rcd'), 'i·\x1D'); assert(atob('ab cd'), 'i·\x1D'); assertThrows(() => atob('ab\u00a0cd')); assert(atob('ab\t\n\f\r cd'), 'i·\x1D'); assert(atob(' \t\n\f\r ab\t\n\f\r cd\t\n\f\r '), 'i·\x1D'); assert(atob('ab\t\n\f\r =\t\n\f\r =\t\n\f\r '), 'i'); assertThrows(() => atob('A')); assert(atob('/A'), 'ü'); assert(atob('//A'), 'ÿð'); assert(atob('///A'), 'ÿÿÀ'); assertThrows(() => atob('////A')); assertThrows(() => atob('/')); assert(atob('A/'), '\x03'); assert(atob('AA/'), '\x00\x0F'); assertThrows(() => atob('AAAA/')); assert(atob('AAA/'), '\x00\x00?'); assertThrows(() => atob('\u0000nonsense')); assertThrows(() => atob('abcd\u0000nonsense')); assert(atob('YQ'), 'a'); assert(atob('YR'), 'a'); assertThrows(() => atob('~~')); assertThrows(() => atob('..')); assertThrows(() => atob('--')); assertThrows(() => atob('__')); } }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/byob.js ================================================ import { routes } from './routes'; routes.set('/byob', () => { // eslint-disable-next-line no-undef const stream = new ReadableStream({ type: 'bytes', autoAllocateChunkSize: 1024, async pull(controller) { const view = controller.byobRequest.view; view[0] = 104; view[1] = 101; view[2] = 121; view[3] = 51; controller.byobRequest.respond(4); controller.close(); }, }); return new Response(stream); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/byte-repeater.js ================================================ /* eslint-env serviceworker */ import { CacheOverride } from 'fastly:cache-override'; import { routes } from './routes'; routes.set('/byte-repeater', () => { let headers = new Headers(); headers.set('AssemblyScriptHeader', 'AssemblyScriptValue'); let streamController; let stream = new ReadableStream({ start: (controller) => { streamController = controller; }, }); let response = new Response(stream, { headers, }); // Make a request upstream let upstreamRequest = new Request( 'https://compute-sdk-test-backend.edgecompute.app/byte_repeater', ); upstreamRequest.setCacheOverride(new CacheOverride('pass')); fetch(upstreamRequest, { backend: 'TheOrigin', }).then(async (upstreamResponse) => { let body = upstreamResponse.body; let streamReader = body.getReader(); // eslint-disable-next-line no-constant-condition while (true) { let chunk = await streamReader.read(); // Check if we are done if (chunk.done) { break; } if (chunk.value.byteLength == 0) { continue; } // Otherwise get the byte and repeat them let upstreamBytes = chunk.value; let downstreamBytes = new Uint8Array(upstreamBytes.length * 2); for (let i = 0; i < upstreamBytes.length; i++) { let downstreamIndex = i * 2; downstreamBytes[downstreamIndex] = upstreamBytes[i]; downstreamBytes[downstreamIndex + 1] = upstreamBytes[i]; } streamController.enqueue(downstreamBytes); } streamController.close(); }); // Send downstream (back to the client) return response; }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/cache-core.js ================================================ /// /* eslint-env serviceworker */ import { assert, assertDoesNotThrow, assertThrows, sleep, streamToString, assertResolves, } from './assertions.js'; import { routes } from './routes.js'; import { CoreCache, CacheEntry, CacheState, TransactionCacheEntry, } from 'fastly:cache'; import { FastlyBody } from 'fastly:body'; function iteratableToStream(iterable) { return new ReadableStream({ async pull(controller) { for await (const value of iterable) { controller.enqueue(value); } controller.close(); }, }); } let createdLion = false; function ensureLion() { if (createdLion) return; const writer = CoreCache.insert('lion', { maxAge: 600_000, }); writer.append('raar'); writer.close(); createdLion = true; } // FastlyBody { routes.set('/FastlyBody/interface', () => { let actual = Reflect.ownKeys(FastlyBody); let expected = ['prototype', 'length', 'name']; assert(actual, expected, `Reflect.ownKeys(FastlyBody)`); // Check the prototype descriptors are correct { actual = Reflect.getOwnPropertyDescriptor(FastlyBody, 'prototype'); expected = { value: FastlyBody.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody, 'prototype')`, ); } // Check the constructor function's defined parameter length is correct { actual = Reflect.getOwnPropertyDescriptor(FastlyBody, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody, 'length')`, ); } // Check the constructor function's name is correct { actual = Reflect.getOwnPropertyDescriptor(FastlyBody, 'name'); expected = { value: 'FastlyBody', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody, 'name')`, ); } // Check the prototype has the correct keys { actual = Reflect.ownKeys(FastlyBody.prototype); expected = [ 'constructor', 'concat', 'read', 'append', 'prepend', 'close', 'abandon', Symbol.toStringTag, ]; assert(actual, expected, `Reflect.ownKeys(FastlyBody.prototype)`); } // Check the constructor on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: FastlyBody.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, 'constructor')`, ); assert( typeof FastlyBody.prototype.constructor, 'function', `typeof FastlyBody.prototype.constructor`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.constructor, 'name', ); expected = { value: 'FastlyBody', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.constructor, 'name')`, ); } // Check the Symbol.toStringTag on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype, Symbol.toStringTag, ); expected = { writable: false, enumerable: false, configurable: true, value: 'FastlyBody', }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, [Symbol.toStringTag])`, ); assert( typeof FastlyBody.prototype[Symbol.toStringTag], 'string', `typeof FastlyBody.prototype[Symbol.toStringTag]`, ); } // Check the concat method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, 'concat'); expected = { writable: true, enumerable: true, configurable: true, value: FastlyBody.prototype.concat, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, 'concat')`, ); assert( typeof FastlyBody.prototype.concat, 'function', `typeof FastlyBody.prototype.concat`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.concat, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.concat, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.concat, 'name', ); expected = { value: 'concat', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.concat, 'name')`, ); } // Check the read method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, 'read'); expected = { writable: true, enumerable: true, configurable: true, value: FastlyBody.prototype.read, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, 'read')`, ); assert( typeof FastlyBody.prototype.read, 'function', `typeof FastlyBody.prototype.read`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.read, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.read, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.read, 'name', ); expected = { value: 'read', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.read, 'name')`, ); } // Check the append method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, 'append'); expected = { writable: true, enumerable: true, configurable: true, value: FastlyBody.prototype.append, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, 'append')`, ); assert( typeof FastlyBody.prototype.append, 'function', `typeof FastlyBody.prototype.append`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.append, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.append, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.append, 'name', ); expected = { value: 'append', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.append, 'name')`, ); } // Check the prepend method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype, 'prepend', ); expected = { writable: true, enumerable: true, configurable: true, value: FastlyBody.prototype.prepend, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, 'prepend')`, ); assert( typeof FastlyBody.prototype.prepend, 'function', `typeof FastlyBody.prototype.prepend`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.prepend, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.prepend, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.prepend, 'name', ); expected = { value: 'prepend', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.prepend, 'name')`, ); } // Check the close method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, 'close'); expected = { writable: true, enumerable: true, configurable: true, value: FastlyBody.prototype.close, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype, 'close')`, ); assert( typeof FastlyBody.prototype.close, 'function', `typeof FastlyBody.prototype.close`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.close, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.close, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( FastlyBody.prototype.close, 'name', ); expected = { value: 'close', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(FastlyBody.prototype.close, 'name')`, ); } }); // constructor { routes.set('/FastlyBody/constructor/called-as-regular-function', () => { assertThrows(() => { FastlyBody(); }, TypeError); }); routes.set('/FastlyBody/constructor/called-as-constructor', () => { assertDoesNotThrow(() => new FastlyBody()); }); } // append(data: BodyInit): void; { routes.set('/FastlyBody/append/called-as-constructor', () => { assertThrows(() => { new FastlyBody.append('1'); }, TypeError); }); routes.set('/FastlyBody/append/data-parameter-not-supplied', () => { assertThrows( () => { const body = new FastlyBody(); body.append(); }, TypeError, `append: At least 1 argument required, but only 0 passed`, ); }); routes.set('/FastlyBody/append/data-parameter-wrong-type', () => { assertThrows(() => { const body = new FastlyBody(); body.append(Symbol()); }); }); // - ReadableStream routes.set( '/FastlyBody/append/data-parameter-readablestream-guest-backed', () => { // TODO: update this when streams are supported assertThrows( () => { const stream = iteratableToStream([]); const body = new FastlyBody(); body.append(stream); }, TypeError, `Content-provided streams are not yet supported for appending onto a FastlyBody`, ); }, ); routes.set( '/FastlyBody/append/data-parameter-readablestream-host-backed', async () => { const res = await fetch( 'https://compute-sdk-test-backend.edgecompute.app/', { backend: 'TheOrigin', }, ); const body = new FastlyBody(); let result = body.append(res.body); assert(result, undefined, `body.append(res.body)`); }, ); // - URLSearchParams routes.set('/FastlyBody/append/data-parameter-URLSearchParams', () => { const items = [ new URLSearchParams(), new URLSearchParams({ a: 'b', c: 'd' }), ]; const body = new FastlyBody(); for (const searchParams of items) { let result = body.append(searchParams); assert(result, undefined, `await body.append(searchParams)`); } }); // - USV strings routes.set('/FastlyBody/append/data-parameter-strings', () => { const strings = [ // empty '', // lone surrogate '\uD800', // surrogate pair '𠈓', String('carrot'), ]; const body = new FastlyBody(); for (const string of strings) { let result = body.append(string); assert(result, undefined, `body.append(string)`); } }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/FastlyBody/append/data-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol(); const value = { toString() { throw sentinel; }, }; const body = new FastlyBody(); body.append(value); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { const body = new FastlyBody(); body.append(Symbol()); }, TypeError, `can't convert symbol to string`, ); }, ); // - buffer source routes.set('/FastlyBody/append/data-parameter-buffer', () => { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; const body = new FastlyBody(); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = body.append(typedArray.buffer); assert(result, undefined, `body.append(typedArray.buffer)`); } }); routes.set('/FastlyBody/append/data-parameter-arraybuffer', () => { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; const body = new FastlyBody(); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = body.append(typedArray.buffer); assert(result, undefined, `body.append(typedArray.buffer)`); } }); routes.set('/FastlyBody/append/data-parameter-typed-arrays', () => { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; const body = new FastlyBody(); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = body.append(typedArray); assert(result, undefined, `body.append(typedArray)`); } }); routes.set('/FastlyBody/append/data-parameter-dataview', () => { const typedArrayConstructors = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array, ]; const body = new FastlyBody(); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); const view = new DataView(typedArray.buffer); let result = body.append(view); assert(result, undefined, `body.append(typedArray)`); } }); } // prepend(data: BodyInit): void; { routes.set('/FastlyBody/prepend/called-as-constructor', () => { assertThrows(() => { new FastlyBody.prepend('1'); }, TypeError); }); routes.set('/FastlyBody/prepend/data-parameter-not-supplied', () => { assertThrows( () => { const body = new FastlyBody(); body.prepend(); }, TypeError, `prepend: At least 1 argument required, but only 0 passed`, ); }); routes.set('/FastlyBody/prepend/data-parameter-wrong-type', () => { assertThrows(() => { const body = new FastlyBody(); body.prepend(Symbol()); }); }); // - ReadableStream routes.set( '/FastlyBody/prepend/data-parameter-readablestream-guest-backed', () => { // TODO: update this when streams are supported assertThrows( () => { const stream = iteratableToStream([]); const body = new FastlyBody(); body.prepend(stream); }, TypeError, `Content-provided streams are not yet supported for prepending onto a FastlyBody`, ); }, ); routes.set( '/FastlyBody/prepend/data-parameter-readablestream-host-backed', async () => { const res = await fetch( 'https://compute-sdk-test-backend.edgecompute.app/', { backend: 'TheOrigin', }, ); const body = new FastlyBody(); let result = body.prepend(res.body); assert(result, undefined, `body.prepend(res.body)`); }, ); routes.set( '/FastlyBody/prepend/data-parameter-readablestream-locked', () => { const stream = iteratableToStream([]); // getReader() causes the stream to become locked stream.getReader(); const body = new FastlyBody(); assertThrows( () => { body.prepend(stream); }, TypeError, `Can't use a ReadableStream that's locked or has ever been read from or canceled`, ); }, ); // - URLSearchParams routes.set('/FastlyBody/prepend/data-parameter-URLSearchParams', () => { const items = [ new URLSearchParams(), new URLSearchParams({ a: 'b', c: 'd' }), ]; const body = new FastlyBody(); for (const searchParams of items) { let result = body.prepend(searchParams); assert(result, undefined, `await body.prepend(searchParams)`); } }); // - USV strings routes.set('/FastlyBody/prepend/data-parameter-strings', () => { const strings = [ // empty '', // lone surrogate '\uD800', // surrogate pair '𠈓', String('carrot'), ]; const body = new FastlyBody(); for (const string of strings) { let result = body.prepend(string); assert(result, undefined, `body.prepend(string)`); } }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/FastlyBody/prepend/data-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol(); const value = { toString() { throw sentinel; }, }; const body = new FastlyBody(); body.prepend(value); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { const body = new FastlyBody(); body.prepend(Symbol()); }, TypeError, `can't convert symbol to string`, ); }, ); // - buffer source routes.set('/FastlyBody/prepend/data-parameter-buffer', () => { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; const body = new FastlyBody(); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = body.prepend(typedArray.buffer); assert(result, undefined, `body.prepend(typedArray.buffer)`); } }); routes.set('/FastlyBody/prepend/data-parameter-arraybuffer', () => { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; const body = new FastlyBody(); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = body.prepend(typedArray.buffer); assert(result, undefined, `body.prepend(typedArray.buffer)`); } }); routes.set('/FastlyBody/prepend/data-parameter-typed-arrays', () => { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; const body = new FastlyBody(); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = body.prepend(typedArray); assert(result, undefined, `body.prepend(typedArray)`); } }); routes.set('/FastlyBody/prepend/data-parameter-dataview', () => { const typedArrayConstructors = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array, ]; const body = new FastlyBody(); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); const view = new DataView(typedArray.buffer); let result = body.prepend(view); assert(result, undefined, `body.prepend(typedArray)`); } }); } // concat(dest: FastlyBody): void; { routes.set('/FastlyBody/concat/called-as-constructor', () => { assertThrows(() => { new FastlyBody.concat(new FastlyBody()); }, TypeError); }); routes.set('/FastlyBody/concat/dest-parameter-not-supplied', () => { assertThrows( () => { const body = new FastlyBody(); body.concat(); }, TypeError, `concat: At least 1 argument required, but only 0 passed`, ); }); routes.set('/FastlyBody/concat/dest-parameter-wrong-type', () => { assertThrows(() => { const body = new FastlyBody(); body.concat('hello'); }); }); routes.set('/FastlyBody/concat/concat-same-fastlybody-twice', () => { assertThrows(() => { const body = new FastlyBody(); const body2 = new FastlyBody(); body.concat(body2); body.concat(body2); }); }); routes.set('/FastlyBody/concat/happy-path', () => { assertDoesNotThrow(() => { const body = new FastlyBody(); body.concat(new FastlyBody()); }); }); } // read(chunkSize: number): ArrayBuffer; { routes.set('/FastlyBody/read/called-as-constructor', () => { assertThrows(() => { new FastlyBody.read(1); }, TypeError); }); routes.set('/FastlyBody/read/chunkSize-parameter-not-supplied', () => { assertThrows( () => { const body = new FastlyBody(); body.read(); }, TypeError, `read: At least 1 argument required, but only 0 passed`, ); }); routes.set('/FastlyBody/read/chunkSize-parameter-wrong-type', () => { assertThrows(() => { const body = new FastlyBody(); body.read(Symbol()); }); }); // negative routes.set('/FastlyBody/read/chunkSize-parameter-negative', () => { assertThrows(() => { const body = new FastlyBody(); body.append('hello world'); body.read(-1); }); }); // infinity routes.set('/FastlyBody/read/chunkSize-parameter-infinity', () => { assertThrows(() => { const body = new FastlyBody(); body.append('hello world'); body.read(Infinity); }); }); // NaN routes.set('/FastlyBody/read/chunkSize-parameter-NaN', () => { assertThrows(() => { const body = new FastlyBody(); body.append('hello world'); body.read(NaN); }); }); routes.set('/FastlyBody/read/happy-path', () => { const body = new FastlyBody(); body.append('world'); body.prepend('hello '); const body2 = new FastlyBody(); body2.append('!'); body.concat(body2); const decoder = new TextDecoder(); let result = decoder.decode(body.read(1)); assert(result, 'h', `body.read(1)`); result = decoder.decode(body.read(1)); assert(result, 'e', `body.read(1)`); }); } // close(): void; { routes.set('/FastlyBody/close/called-as-constructor', () => { assertThrows(() => { new CoreCache.lookup('1'); }, TypeError); }); routes.set('/FastlyBody/close/called-once', () => { assertThrows( () => { CoreCache.lookup(); }, TypeError, `CoreCache.lookup: At least 1 argument required, but only 0 passed`, ); }); routes.set('/FastlyBody/close/called-twice', () => { assertThrows(() => { CoreCache.lookup('cat', { headers: '' }); }); }); } } // CoreCache { routes.set('/core-cache/interface', () => { let actual = Reflect.ownKeys(CoreCache); let expected = [ 'prototype', 'lookup', 'insert', 'transactionLookup', 'length', 'name', ]; assert(actual, expected, `Reflect.ownKeys(CoreCache)`); // Check the prototype descriptors are correct { actual = Reflect.getOwnPropertyDescriptor(CoreCache, 'prototype'); expected = { value: CoreCache.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache, 'prototype')`, ); } // Check the constructor function's defined parameter length is correct { actual = Reflect.getOwnPropertyDescriptor(CoreCache, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache, 'length')`, ); } // Check the constructor function's name is correct { actual = Reflect.getOwnPropertyDescriptor(CoreCache, 'name'); expected = { value: 'CoreCache', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache, 'name')`, ); } // Check the prototype has the correct keys { actual = Reflect.ownKeys(CoreCache.prototype); expected = ['constructor', Symbol.toStringTag]; assert(actual, expected, `Reflect.ownKeys(CoreCache.prototype)`); } // Check the constructor on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( CoreCache.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: CoreCache.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache.prototype, 'constructor')`, ); assert( typeof CoreCache.prototype.constructor, 'function', `typeof CoreCache.prototype.constructor`, ); actual = Reflect.getOwnPropertyDescriptor( CoreCache.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CoreCache.prototype.constructor, 'name', ); expected = { value: 'CoreCache', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache.prototype.constructor, 'name')`, ); } // Check the Symbol.toStringTag on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( CoreCache.prototype, Symbol.toStringTag, ); expected = { writable: false, enumerable: false, configurable: true, value: 'CoreCache', }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache.prototype, [Symbol.toStringTag])`, ); assert( typeof CoreCache.prototype[Symbol.toStringTag], 'string', `typeof CoreCache.prototype[Symbol.toStringTag]`, ); } // Check the lookup static method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(CoreCache, 'lookup'); expected = { writable: true, enumerable: true, configurable: true, value: CoreCache.lookup, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache, 'lookup')`, ); assert(typeof CoreCache.lookup, 'function', `typeof CoreCache.lookup`); actual = Reflect.getOwnPropertyDescriptor(CoreCache.lookup, 'length'); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache.lookup, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(CoreCache.lookup, 'name'); expected = { value: 'lookup', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache.lookup, 'name')`, ); } // Check the insert static method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(CoreCache, 'insert'); expected = { writable: true, enumerable: true, configurable: true, value: CoreCache.insert, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache, 'insert')`, ); assert(typeof CoreCache.insert, 'function', `typeof CoreCache.insert`); actual = Reflect.getOwnPropertyDescriptor(CoreCache.insert, 'length'); expected = { value: 2, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache.insert, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(CoreCache.insert, 'name'); expected = { value: 'insert', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache.insert, 'name')`, ); } // Check the transactionLookup static method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(CoreCache, 'transactionLookup'); expected = { writable: true, enumerable: true, configurable: true, value: CoreCache.transactionLookup, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache, 'transactionLookup')`, ); assert( typeof CoreCache.transactionLookup, 'function', `typeof CoreCache.transactionLookup`, ); actual = Reflect.getOwnPropertyDescriptor( CoreCache.transactionLookup, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache.transactionLookup, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CoreCache.transactionLookup, 'name', ); expected = { value: 'transactionLookup', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CoreCache.transactionLookup, 'name')`, ); } }); // CoreCache constructor { routes.set('/core-cache/constructor/called-as-regular-function', () => { assertThrows(() => { CoreCache(); }, TypeError); }); routes.set('/core-cache/constructor/throws', () => { assertThrows(() => new CoreCache(), TypeError); }); } // CoreCache lookup static method // static lookup(key: string): CoreCacheEntry | null; { routes.set('/core-cache/lookup/called-as-constructor', () => { assertThrows(() => { new CoreCache.lookup('1'); }, TypeError); }); // https://tc39.es/ecma262/#sec-tostring routes.set('/core-cache/lookup/key-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const key = { toString() { throw sentinel; }, }; CoreCache.lookup(key); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { CoreCache.lookup(Symbol()); }, TypeError, `can't convert symbol to string`, ); }); routes.set('/core-cache/lookup/key-parameter-not-supplied', () => { assertThrows( () => { CoreCache.lookup(); }, TypeError, `CoreCache.lookup: At least 1 argument required, but only 0 passed`, ); }); routes.set('/core-cache/lookup/key-parameter-empty-string', () => { assertThrows( () => { CoreCache.lookup(''); }, Error, `CoreCache.lookup: key can not be an empty string`, ); }); routes.set('/core-cache/lookup/key-parameter-8135-character-string', () => { assertDoesNotThrow(() => { const key = 'a'.repeat(8135); CoreCache.lookup(key); }); }); routes.set('/core-cache/lookup/key-parameter-8136-character-string', () => { assertThrows( () => { const key = 'a'.repeat(8136); CoreCache.lookup(key); }, Error, `CoreCache.lookup: key is too long, the maximum allowed length is 8135.`, ); }); routes.set('/core-cache/lookup/key-does-not-exist-returns-null', () => { let result = CoreCache.lookup(Math.random()); assert(result, null, `CoreCache.lookup(Math.random()) === null`); }); routes.set('/core-cache/lookup/key-exists', () => { let key = 'c'.repeat(8135); let writer = CoreCache.insert(key, { maxAge: 1000, }); writer.append('meow'); writer.close(); let result = CoreCache.lookup(key); assert( result instanceof CacheEntry, true, `CoreCache.lookup('cat') instanceof CacheEntry`, ); }); routes.set('/core-cache/lookup/options-parameter-none', () => { ensureLion(); let entry; assertDoesNotThrow(() => { entry = CoreCache.lookup('lion'); }); assert( entry instanceof CacheEntry, true, `CoreCache.lookup('lion', {headers:...}) instanceof CacheEntry`, ); }); routes.set('/core-cache/lookup/options-parameter-wrong-type', () => { ensureLion(); assertThrows(() => { CoreCache.lookup('lion', ''); }); }); routes.set( '/core-cache/lookup/options-parameter-headers-field-wrong-type', () => { ensureLion(); assertThrows(() => { CoreCache.lookup('lion', { headers: '' }); }); }, ); routes.set( '/core-cache/lookup/options-parameter-headers-field-undefined', () => { ensureLion(); let entry; assertDoesNotThrow(() => { entry = CoreCache.lookup('lion', { headers: undefined }); }); assert( entry instanceof CacheEntry, true, `CoreCache.lookup('lion', {headers:...}) instanceof CacheEntry`, ); }, ); routes.set( '/core-cache/lookup/options-parameter-headers-field-valid-sequence', () => { ensureLion(); let entry; assertDoesNotThrow(() => { entry = CoreCache.lookup('lion', { headers: [ ['user-agent', 'Aki 1.0'], ['Accept-Encoding', 'br'], ], }); }); assert( entry instanceof CacheEntry, true, `CoreCache.lookup('lion', {headers:...}) instanceof CacheEntry`, ); }, ); routes.set( '/core-cache/lookup/options-parameter-headers-field-valid-record', () => { ensureLion(); let entry; assertDoesNotThrow(() => { entry = CoreCache.lookup('lion', { headers: { 'user-agent': 'Aki 1.0', 'Accept-Encoding': 'br', }, }); }); assert( entry instanceof CacheEntry, true, `CoreCache.lookup('lion', {headers:...}) instanceof CacheEntry`, ); }, ); routes.set( '/core-cache/lookup/options-parameter-headers-field-valid-Headers-instance', () => { ensureLion(); let entry; assertDoesNotThrow(() => { entry = CoreCache.lookup('lion', { headers: new Headers({ 'user-agent': 'Aki 1.0', 'Accept-Encoding': 'br', }), }); }); assert( entry instanceof CacheEntry, true, `CoreCache.lookup('lion', {headers:...}) instanceof CacheEntry`, ); }, ); } // static insert(key: string, options: InsertOptions): FastlyBody; { routes.set('/core-cache/insert/called-as-constructor', () => { assertThrows(() => { new CoreCache.insert('1', { maxAge: 1 }); }, TypeError); }); // https://tc39.es/ecma262/#sec-tostring routes.set('/core-cache/insert/key-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const key = { toString() { throw sentinel; }, }; CoreCache.insert(key, { maxAge: 1 }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { CoreCache.insert(Symbol(), { maxAge: 1 }); }, TypeError, `can't convert symbol to string`, ); }); routes.set('/core-cache/insert/key-parameter-not-supplied', () => { assertThrows( () => { CoreCache.insert(); }, TypeError, `CoreCache.insert: At least 2 arguments required, but only 0 passed`, ); }); routes.set('/core-cache/insert/key-parameter-empty-string', () => { assertThrows( () => { CoreCache.insert('', { maxAge: 1 }); }, Error, `CoreCache.insert: key can not be an empty string`, ); }); routes.set('/core-cache/insert/key-parameter-8135-character-string', () => { assertDoesNotThrow(() => { const key = 'a'.repeat(8135); CoreCache.insert(key, { maxAge: 1 }); }); }); routes.set('/core-cache/insert/key-parameter-8136-character-string', () => { assertThrows( () => { const key = 'a'.repeat(8136); CoreCache.insert(key, { maxAge: 1 }); }, Error, `CoreCache.insert: key is too long, the maximum allowed length is 8135.`, ); }); routes.set('/core-cache/insert/options-parameter-wrong-type', () => { assertThrows(() => { CoreCache.insert('cat', ''); }); }); routes.set( '/core-cache/insert/options-parameter-headers-field-wrong-type', () => { assertThrows(() => { CoreCache.insert('cat', { headers: '', maxAge: 1 }); }); }, ); routes.set( '/core-cache/insert/options-parameter-headers-field-undefined', () => { let body; assertDoesNotThrow(() => { body = CoreCache.insert('cat', { headers: undefined, maxAge: 1 }); }); assert( body instanceof FastlyBody, true, `CoreCache.insert('cat', {headers:undefined}) instanceof FastlyBody`, ); }, ); routes.set( '/core-cache/insert/options-parameter-headers-field-valid-sequence', () => { let body; assertDoesNotThrow(() => { body = CoreCache.insert('cat', { headers: [ ['user-agent', 'Aki 1.0'], ['Accept-Encoding', 'br'], ], maxAge: 1, }); }); assert( body instanceof FastlyBody, true, `CoreCache.insert('cat', {headers:undefined}) instanceof FastlyBody`, ); }, ); routes.set( '/core-cache/insert/options-parameter-headers-field-valid-record', () => { let body; assertDoesNotThrow(() => { body = CoreCache.insert('cat', { headers: { 'user-agent': 'Aki 1.0', 'Accept-Encoding': 'br', }, maxAge: 1, }); }); assert( body instanceof FastlyBody, true, `CoreCache.insert('cat', {headers:undefined}) instanceof FastlyBody`, ); }, ); routes.set( '/core-cache/insert/options-parameter-headers-field-valid-Headers-instance', () => { let body; assertDoesNotThrow(() => { body = CoreCache.insert('cat', { headers: new Headers({ 'user-agent': 'Aki 1.0', 'Accept-Encoding': 'br', }), maxAge: 1, }); }); assert( body instanceof FastlyBody, true, `CoreCache.insert('cat', {headers:undefined}) instanceof FastlyBody`, ); }, ); routes.set( '/core-cache/insert/options-parameter-maxAge-field-valid-record', () => { let body; assertDoesNotThrow(() => { body = CoreCache.insert('cat', { maxAge: 1 }); }); assert( body instanceof FastlyBody, true, `CoreCache.insert('cat', {maxAge: 1}) instanceof FastlyBody`, ); }, ); routes.set('/core-cache/insert/options-parameter-maxAge-field-NaN', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: NaN, }); }); }); routes.set( '/core-cache/insert/options-parameter-maxAge-field-postitive-infinity', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-maxAge-field-negative-infinity', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-maxAge-field-negative-number', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: -1, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-maxAge-field-too-large', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 2e13, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-initialAge-field-valid-record', () => { let body; assertDoesNotThrow(() => { body = CoreCache.insert('cat', { maxAge: 1, initialAge: 1 }); }); assert( body instanceof FastlyBody, true, `CoreCache.insert('cat', {maxAge: 1,initialAge: 1}) instanceof FastlyBody`, ); }, ); routes.set( '/core-cache/insert/options-parameter-initialAge-field-NaN', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, initialAge: NaN, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-initialAge-field-postitive-infinity', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, initialAge: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-initialAge-field-negative-infinity', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, initialAge: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-initialAge-field-negative-number', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, initialAge: -1, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-initialAge-field-too-large', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, initialAge: 2e13, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-staleWhileRevalidate-field-valid-record', () => { let body; assertDoesNotThrow(() => { body = CoreCache.insert('cat', { maxAge: 1, staleWhileRevalidate: 1, }); }); assert( body instanceof FastlyBody, true, `CoreCache.insert('cat', {maxAge: 1,staleWhileRevalidate: 1}) instanceof FastlyBody`, ); }, ); routes.set( '/core-cache/insert/options-parameter-staleWhileRevalidate-field-NaN', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, staleWhileRevalidate: NaN, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-staleWhileRevalidate-field-postitive-infinity', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, staleWhileRevalidate: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-staleWhileRevalidate-field-negative-infinity', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, staleWhileRevalidate: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-staleWhileRevalidate-field-negative-number', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, staleWhileRevalidate: -1, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-staleWhileRevalidate-field-too-large', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, staleWhileRevalidate: 2e13, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-length-field-valid-record', () => { let body; assertDoesNotThrow(() => { body = CoreCache.insert('cat', { maxAge: 1, length: 1 }); }); assert( body instanceof FastlyBody, true, `CoreCache.insert('cat', {maxAge: 1,length: 1}) instanceof FastlyBody`, ); }, ); routes.set('/core-cache/insert/options-parameter-length-field-NaN', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, length: NaN, }); }); }); routes.set( '/core-cache/insert/options-parameter-length-field-postitive-infinity', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, length: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-length-field-negative-infinity', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, length: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/core-cache/insert/options-parameter-length-field-negative-number', () => { assertThrows(() => { CoreCache.insert('cat', { maxAge: 1, length: -1, }); }); }, ); routes.set('/core-cache/insert/options-parameter-sensitive-field', () => { assertDoesNotThrow(() => { CoreCache.insert('cat', { maxAge: 1, sensitive: true, }); }); }); routes.set('/core-cache/insert/options-parameter-vary-field', () => { assertDoesNotThrow(() => { CoreCache.insert('cat', { maxAge: 1, vary: ['animal', 'mineral', 'vegetable'], }); }); }); routes.set( '/core-cache/insert/options-parameter-userMetadata-field/arraybuffer/empty', async () => { await assertResolves(async () => { let key = '/core-cache/insert/options-parameter-userMetadata-field/arraybuffer/empty' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, userMetadata: new ArrayBuffer(0), }); writer.append('hello'); writer.close(); }); }, ); routes.set( '/core-cache/insert/options-parameter-userMetadata-field/arraybuffer/not-empty', async () => { await assertResolves(async () => { let key = '/core-cache/insert/options-parameter-userMetadata-field/arraybuffer/not-empty' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, userMetadata: Uint8Array.from([104, 101, 108, 108, 111]).buffer, }); writer.append('hello'); writer.close(); }); }, ); routes.set( '/core-cache/insert/options-parameter-userMetadata-field/URLSearchParams', async () => { await assertResolves(async () => { let key = '/core-cache/insert/options-parameter-userMetadata-field/URLSearchParams' + Math.random(); let userMetadata = new URLSearchParams(); userMetadata.set('hello', 'world'); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, userMetadata, }); writer.append('hello'); writer.close(); }); }, ); routes.set( '/core-cache/insert/options-parameter-userMetadata-field/string', async () => { await assertResolves(async () => { let key = '/core-cache/insert/options-parameter-userMetadata-field/string' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, userMetadata: 'hello', }); writer.append('hello'); writer.close(); }); }, ); // surrogateKeys?: Array,-- empty string? -- toString which throws -- wrong types? } //static transactionLookup(key: string, options?: LookupOptions): CacheEntry | null; { routes.set('/core-cache/transactionLookup/called-as-constructor', () => { assertThrows(() => { new CoreCache.transactionLookup('1'); }, TypeError); }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/core-cache/transactionLookup/key-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const key = { toString() { throw sentinel; }, }; CoreCache.transactionLookup(key); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { CoreCache.transactionLookup(Symbol()); }, TypeError, `can't convert symbol to string`, ); }, ); routes.set( '/core-cache/transactionLookup/key-parameter-not-supplied', () => { assertThrows( () => { CoreCache.transactionLookup(); }, TypeError, `CoreCache.transactionLookup: At least 1 argument required, but only 0 passed`, ); }, ); routes.set( '/core-cache/transactionLookup/key-parameter-empty-string', () => { assertThrows( () => { CoreCache.transactionLookup(''); }, Error, `CoreCache.transactionLookup: key can not be an empty string`, ); }, ); routes.set( '/core-cache/transactionLookup/key-parameter-8135-character-string', () => { assertDoesNotThrow(() => { const key = 'a'.repeat(8135); CoreCache.transactionLookup(key); }); }, ); routes.set( '/core-cache/transactionLookup/key-parameter-8136-character-string', () => { assertThrows( () => { const key = 'a'.repeat(8136); CoreCache.transactionLookup(key); }, Error, `CoreCache.transactionLookup: key is too long, the maximum allowed length is 8135.`, ); }, ); routes.set('/core-cache/transactionLookup/key-does-not-exist', () => { let result = CoreCache.transactionLookup(Math.random()); assert( result instanceof CacheEntry, true, `CoreCache.transactionLookup(Math.random()) instanceof CacheEntry`, ); }); routes.set('/core-cache/transactionLookup/key-exists', () => { let writer = CoreCache.insert('cat', { maxAge: 10_000, }); writer.append('meow'); writer.close(); let result = CoreCache.transactionLookup('cat'); assert( result instanceof CacheEntry, true, `CoreCache.transactionLookup('cat') instanceof CacheEntry`, ); }); routes.set( '/core-cache/transactionLookup/options-parameter-wrong-type', () => { assertThrows(() => { CoreCache.transactionLookup('cat', ''); }); }, ); routes.set( '/core-cache/transactionLookup/options-parameter-headers-field-wrong-type', () => { assertThrows(() => { CoreCache.transactionLookup('cat', { headers: '' }); }); }, ); routes.set( '/core-cache/transactionLookup/options-parameter-headers-field-undefined', () => { let entry; assertDoesNotThrow(() => { entry = CoreCache.transactionLookup('cat', { headers: undefined }); }); assert( entry instanceof CacheEntry, true, `CoreCache.transactionLookup('cat', {headers:...}) instanceof CacheEntry`, ); }, ); routes.set( '/core-cache/transactionLookup/options-parameter-headers-field-valid-sequence', () => { let entry; assertDoesNotThrow(() => { entry = CoreCache.transactionLookup('cat', { headers: [ ['user-agent', 'Aki 1.0'], ['Accept-Encoding', 'br'], ], }); }); assert( entry instanceof CacheEntry, true, `CoreCache.transactionLookup('cat', {headers:...}) instanceof CacheEntry`, ); }, ); routes.set( '/core-cache/transactionLookup/options-parameter-headers-field-valid-record', () => { let entry; assertDoesNotThrow(() => { entry = CoreCache.transactionLookup('cat', { headers: { 'user-agent': 'Aki 1.0', 'Accept-Encoding': 'br', }, }); }); assert( entry instanceof CacheEntry, true, `CoreCache.transactionLookup('cat', {headers:...}) instanceof CacheEntry`, ); }, ); routes.set( '/core-cache/transactionLookup/options-parameter-headers-field-valid-Headers-instance', () => { let entry; assertDoesNotThrow(() => { entry = CoreCache.transactionLookup('cat', { headers: new Headers({ 'user-agent': 'Aki 1.0', 'Accept-Encoding': 'br', }), }); }); assert( entry instanceof CacheEntry, true, `CoreCache.transactionLookup('cat', {headers:...}) instanceof CacheEntry`, ); }, ); } } // CacheEntry { routes.set('/cache-entry/interface', () => { let actual = Reflect.ownKeys(CacheEntry); let expected = ['prototype', 'length', 'name']; assert(actual, expected, `Reflect.ownKeys(CacheEntry)`); // Check the prototype descriptors are correct { actual = Reflect.getOwnPropertyDescriptor(CacheEntry, 'prototype'); expected = { value: CacheEntry.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry, 'prototype')`, ); } // Check the constructor function's defined parameter length is correct { actual = Reflect.getOwnPropertyDescriptor(CacheEntry, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry, 'length')`, ); } // Check the constructor function's name is correct { actual = Reflect.getOwnPropertyDescriptor(CacheEntry, 'name'); expected = { value: 'CacheEntry', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry, 'name')`, ); } // Check the prototype has the correct keys { actual = Reflect.ownKeys(CacheEntry.prototype); expected = [ 'constructor', 'close', 'state', 'userMetadata', 'body', 'length', 'maxAge', 'staleWhileRevalidate', 'age', 'hits', Symbol.toStringTag, ]; assert(actual, expected, `Reflect.ownKeys(CacheEntry.prototype)`); } // Check the constructor on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: CacheEntry.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'constructor')`, ); assert( typeof CacheEntry.prototype.constructor, 'function', `typeof CacheEntry.prototype.constructor`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.constructor, 'name', ); expected = { value: 'CacheEntry', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.constructor, 'name')`, ); } // Check the Symbol.toStringTag on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype, Symbol.toStringTag, ); expected = { writable: false, enumerable: false, configurable: true, value: 'CacheEntry', }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, [Symbol.toStringTag])`, ); assert( typeof CacheEntry.prototype[Symbol.toStringTag], 'string', `typeof CacheEntry.prototype[Symbol.toStringTag]`, ); } // Check the close method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'close'); expected = { writable: true, enumerable: true, configurable: true, value: CacheEntry.prototype.close, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'close')`, ); assert( typeof CacheEntry.prototype.close, 'function', `typeof CacheEntry.prototype.close`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.close, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.close, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.close, 'name', ); expected = { value: 'close', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.close, 'name')`, ); } // Check the state method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'state'); expected = { writable: true, enumerable: true, configurable: true, value: CacheEntry.prototype.state, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'state')`, ); assert( typeof CacheEntry.prototype.state, 'function', `typeof CacheEntry.prototype.state`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.state, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.state, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.state, 'name', ); expected = { value: 'state', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.state, 'name')`, ); } // Check the userMetadata method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype, 'userMetadata', ); expected = { writable: true, enumerable: true, configurable: true, value: CacheEntry.prototype.userMetadata, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'userMetadata')`, ); assert( typeof CacheEntry.prototype.userMetadata, 'function', `typeof CacheEntry.prototype.userMetadata`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.userMetadata, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.userMetadata, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.userMetadata, 'name', ); expected = { value: 'userMetadata', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.userMetadata, 'name')`, ); } // Check the body method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'body'); expected = { writable: true, enumerable: true, configurable: true, value: CacheEntry.prototype.body, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'body')`, ); assert( typeof CacheEntry.prototype.body, 'function', `typeof CacheEntry.prototype.body`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.body, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.body, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.body, 'name', ); expected = { value: 'body', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.body, 'name')`, ); } // Check the length method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'length'); expected = { writable: true, enumerable: true, configurable: true, value: CacheEntry.prototype.length, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'length')`, ); assert( typeof CacheEntry.prototype.length, 'function', `typeof CacheEntry.prototype.length`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.length, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.length, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.length, 'name', ); expected = { value: 'length', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.length, 'name')`, ); } // Check the maxAge method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'maxAge'); expected = { writable: true, enumerable: true, configurable: true, value: CacheEntry.prototype.maxAge, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'maxAge')`, ); assert( typeof CacheEntry.prototype.maxAge, 'function', `typeof CacheEntry.prototype.maxAge`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.maxAge, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.maxAge, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.maxAge, 'name', ); expected = { value: 'maxAge', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.maxAge, 'name')`, ); } // Check the staleWhileRevalidate method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype, 'staleWhileRevalidate', ); expected = { writable: true, enumerable: true, configurable: true, value: CacheEntry.prototype.staleWhileRevalidate, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'staleWhileRevalidate')`, ); assert( typeof CacheEntry.prototype.staleWhileRevalidate, 'function', `typeof CacheEntry.prototype.staleWhileRevalidate`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.staleWhileRevalidate, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.staleWhileRevalidate, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.staleWhileRevalidate, 'name', ); expected = { value: 'staleWhileRevalidate', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.staleWhileRevalidate, 'name')`, ); } // Check the age method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'age'); expected = { writable: true, enumerable: true, configurable: true, value: CacheEntry.prototype.age, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'age')`, ); assert( typeof CacheEntry.prototype.age, 'function', `typeof CacheEntry.prototype.age`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.age, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.age, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.age, 'name', ); expected = { value: 'age', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.age, 'name')`, ); } // Check the hits method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'hits'); expected = { writable: true, enumerable: true, configurable: true, value: CacheEntry.prototype.hits, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype, 'hits')`, ); assert( typeof CacheEntry.prototype.hits, 'function', `typeof CacheEntry.prototype.hits`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.hits, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.hits, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( CacheEntry.prototype.hits, 'name', ); expected = { value: 'hits', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(CacheEntry.prototype.hits, 'name')`, ); } }); // CacheEntry constructor { routes.set('/cache-entry/constructor/called-as-regular-function', () => { assertThrows(() => { CacheEntry(); }, TypeError); }); routes.set('/cache-entry/constructor/throws', () => { assertThrows(() => new CacheEntry(), TypeError); }); } // close(): void; { routes.set('/cache-entry/close/called-as-constructor', () => { assertThrows(() => { new CacheEntry.prototype.close(); }, TypeError); }); routes.set('/cache-entry/close/called-unbound', () => { assertThrows(() => { CacheEntry.prototype.close.call(undefined); }, Error); }); routes.set('/cache-entry/close/called-on-instance', () => { let key = '/cache-entry/close/called-on-instance' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).close(); assert(result, undefined, `CoreCache.lookup(key).close()`); }); } // state(): CacheState; { routes.set('/cache-entry/state/called-as-constructor', () => { assertThrows(() => { new CacheEntry.prototype.state(); }, TypeError); }); routes.set('/cache-entry/state/called-unbound', () => { assertThrows(() => { CacheEntry.prototype.state.call(undefined); }, Error); }); routes.set('/cache-entry/state/called-on-instance', () => { let key = '/cache-entry/state/called-on-instance' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let entry = CoreCache.lookup(key); let result = entry.state(); assert( result instanceof CacheState, true, `CoreCache.lookup(key).state() instanceof CacheState`, ); }); } // userMetadata(): ArrayBuffer; { routes.set('/cache-entry/userMetadata/called-as-constructor', () => { assertThrows(() => { new CacheEntry.prototype.userMetadata(); }, TypeError); }); routes.set('/cache-entry/userMetadata/called-unbound', () => { assertThrows(() => { CacheEntry.prototype.userMetadata.call(undefined); }, Error); }); routes.set('/cache-entry/userMetadata/called-on-instance', () => { let key = '/cache-entry/userMetadata/called-on-instance' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).userMetadata(); assert( result instanceof ArrayBuffer, true, `CoreCache.lookup(key).userMetadata() instanceof ArrayBuffer`, ); assert( result.byteLength, 0, `CoreCache.lookup(key).userMetadata().byteLength`, ); }); routes.set('/cache-entry/userMetadata/basic', () => { let key = '/cache-entry/userMetadata/basic' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, userMetadata: 'hello world', }); writer.append('hello'); writer.close(); let entry = CoreCache.lookup(key); assert( entry instanceof CacheEntry, true, 'CoreCache.lookup(key) instanceof CacheEntry', ); let metadata = entry.userMetadata(); assert( metadata instanceof ArrayBuffer, true, `CoreCache.lookup(key).userMetadata() instanceof ArrayBuffer`, ); assert( metadata.byteLength, 11, `CoreCache.lookup(key).userMetadata().byteLength`, ); let result = new TextDecoder().decode(metadata); assert( result, 'hello world', `new TextDecoder().decode(CoreCache.lookup(key).userMetadata()) === 'hello world'`, ); }); } // body(options?: CacheBodyOptions): ReadableStream; { routes.set('/cache-entry/body/called-as-constructor', () => { assertThrows(() => { new CacheEntry.prototype.body(); }, TypeError); }); routes.set('/cache-entry/body/called-unbound', () => { assertThrows(() => { CacheEntry.prototype.body.call(undefined); }, Error); }); routes.set('/cache-entry/body/called-on-instance', async () => { let key = '/cache-entry/body/called-on-instance' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).body(); assert( result instanceof ReadableStream, true, `CoreCache.lookup(key).body() instanceof ReadableStream`, ); result = await streamToString(result); assert( result, 'hello', `await streamToString(CoreCache.lookup(key).body())`, ); }); routes.set('/cache-entry/body/options-start-negative', async () => { let key = '/cache-entry/body/options-start-negative' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); assertThrows(() => { CoreCache.lookup(key).body({ start: -1 }); }); }); routes.set('/cache-entry/body/options-start-NaN', async () => { let key = '/cache-entry/body/options-start-NaN' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); assertThrows(() => { CoreCache.lookup(key).body({ start: NaN }); }); }); routes.set('/cache-entry/body/options-start-Infinity', async () => { let key = '/cache-entry/body/options-start-Infinity' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); assertThrows(() => { CoreCache.lookup(key).body({ start: Infinity }); }); }); routes.set('/cache-entry/body/options-start-valid', async () => { let key = '/cache-entry/body/options-start-valid' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).body({ start: 1 }); assert( result instanceof ReadableStream, true, `CoreCache.lookup(key).body() instanceof ReadableStream`, ); result = await streamToString(result); assert( result, 'ello', `await streamToString(CoreCache.lookup(key).body())`, ); }); routes.set('/cache-entry/body/options-start-longer-than-body', async () => { let key = '/cache-entry/body/options-start-longer-than-body' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).body({ start: 1000 }); assert( result instanceof ReadableStream, true, `CoreCache.lookup(key).body() instanceof ReadableStream`, ); result = await streamToString(result); assert( result, 'hello', `await streamToString(CoreCache.lookup(key).body())`, ); }); routes.set('/cache-entry/body/options-end-negative', async () => { let key = '/cache-entry/body/options-end-negative' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); assertThrows(() => { CoreCache.lookup(key).body({ end: -1 }); }); }); routes.set('/cache-entry/body/options-end-NaN', async () => { let key = '/cache-entry/body/options-end-NaN' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); assertThrows(() => { CoreCache.lookup(key).body({ end: NaN }); }); }); routes.set('/cache-entry/body/options-end-Infinity', async () => { let key = '/cache-entry/body/options-end-Infinity' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); assertThrows(() => { CoreCache.lookup(key).body({ end: Infinity }); }); }); routes.set('/cache-entry/body/options-end-valid', async () => { let key = '/cache-entry/body/options-end-valid' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).body({ start: 1, end: 1 }); assert( result instanceof ReadableStream, true, `CoreCache.lookup(key).body() instanceof ReadableStream`, ); result = await streamToString(result); console.log({ result }); assert(result, 'e', `await streamToString(CoreCache.lookup(key).body())`); }); routes.set('/cache-entry/body/options-end-zero', async () => { let key = '/cache-entry/body/options-end-zero' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).body({ start: 1, end: 0 }); assert( result instanceof ReadableStream, true, `CoreCache.lookup(key).body() instanceof ReadableStream`, ); result = await streamToString(result); console.log({ result }); assert( result, 'hello', `await streamToString(CoreCache.lookup(key).body())`, ); }); } // length(): number; { routes.set('/cache-entry/length/called-as-constructor', () => { assertThrows(() => { new CacheEntry.prototype.length(); }, TypeError); }); routes.set('/cache-entry/length/called-unbound', () => { assertThrows(() => { CacheEntry.prototype.length.call(undefined); }, Error); }); routes.set('/cache-entry/length/called-on-instance', () => { let key = '/cache-entry/length/called-on-instance' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).length(); assert(result, 5, `CoreCache.lookup(key).length()`); }); // TODO pass in an entry with unknown length and then call length and check it is null? /// The size in bytes of the cached item, if known. /// /// The length of the cached item may be unknown if the item is currently being streamed into /// the cache without a fixed length. } // maxAge(): number; { routes.set('/cache-entry/maxAge/called-as-constructor', () => { assertThrows(() => { new CacheEntry.prototype.maxAge(); }, TypeError); }); routes.set('/cache-entry/maxAge/called-unbound', () => { assertThrows(() => { CacheEntry.prototype.maxAge.call(undefined); }, Error); }); routes.set('/cache-entry/maxAge/called-on-instance', async () => { let key = '/cache-entry/maxAge/called-on-instance' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).maxAge(); assert(result, 60_000, `CoreCache.lookup(key).maxAge()`); }); } // staleWhileRevalidate(): number; { routes.set( '/cache-entry/staleWhileRevalidate/called-as-constructor', () => { assertThrows(() => { new CacheEntry.prototype.staleWhileRevalidate(); }, TypeError); }, ); routes.set('/cache-entry/staleWhileRevalidate/called-unbound', () => { assertThrows(() => { CacheEntry.prototype.staleWhileRevalidate.call(undefined); }, Error); }); routes.set( '/cache-entry/staleWhileRevalidate/called-on-instance', async () => { let key = '/cache-entry/staleWhileRevalidate/called-on-instance' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).staleWhileRevalidate(); assert( typeof result, 'number', `typeof CoreCache.lookup(key).staleWhileRevalidate()`, ); assert( result >= 0, true, `CoreCache.lookup(key).staleWhileRevalidate() >= 0`, ); }, ); } // age(): number; { routes.set('/cache-entry/age/called-as-constructor', () => { assertThrows(() => { new CacheEntry.prototype.age(); }, TypeError); }); routes.set('/cache-entry/age/called-unbound', () => { assertThrows(() => { CacheEntry.prototype.age.call(undefined); }, Error); }); routes.set('/cache-entry/age/called-on-instance', async () => { let key = '/cache-entry/age/called-on-instance' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).age(); assert(typeof result, 'number', `typeof CoreCache.lookup(key).age()`); assert(result >= 0, true, `CoreCache.lookup(key).age() >= 0`); await sleep(1000); result = CoreCache.lookup(key).age(); assert( result >= 1_000, true, `CoreCache.lookup(key).age() >= 1_000 (${result})`, ); }); } // hits(): number; { routes.set('/cache-entry/hits/called-as-constructor', () => { assertThrows(() => { new CacheEntry.prototype.hits(); }, TypeError); }); routes.set('/cache-entry/hits/called-unbound', () => { assertThrows(() => { CacheEntry.prototype.hits.call(undefined); }, Error); }); routes.set('/cache-entry/hits/called-on-instance', () => { let key = '/cache-entry/hits/called-on-instance' + Math.random(); let writer = CoreCache.insert(key, { maxAge: 60 * 1000, }); writer.append('hello'); writer.close(); let result = CoreCache.lookup(key).hits(); assert(result, 1, `CoreCache.lookup(key).hits()`); result = CoreCache.lookup(key).hits(); assert(result, 2, `CoreCache.lookup(key).hits()`); }); } } // TransactionCacheEntry { routes.set('/transaction-cache-entry/interface', () => { let actual = Reflect.ownKeys(TransactionCacheEntry); let expected = ['prototype', 'length', 'name']; assert(actual, expected, `Reflect.ownKeys(TransactionCacheEntry)`); // Check the prototype descriptors are correct { actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry, 'prototype', ); expected = { value: TransactionCacheEntry.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry, 'prototype')`, ); } // Check the constructor function's defined parameter length is correct { actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry, 'length')`, ); } // Check the constructor function's name is correct { actual = Reflect.getOwnPropertyDescriptor(TransactionCacheEntry, 'name'); expected = { value: 'TransactionCacheEntry', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry, 'name')`, ); } // Check the prototype has the correct keys { actual = Reflect.ownKeys(TransactionCacheEntry.prototype); expected = [ 'constructor', 'insert', 'insertAndStreamBack', 'update', 'cancel', Symbol.toStringTag, ]; assert( actual, expected, `Reflect.ownKeys(TransactionCacheEntry.prototype)`, ); } // Check the constructor on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: TransactionCacheEntry.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype, 'constructor')`, ); assert( typeof TransactionCacheEntry.prototype.constructor, 'function', `typeof TransactionCacheEntry.prototype.constructor`, ); actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype.constructor, 'name', ); expected = { value: 'TransactionCacheEntry', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype.constructor, 'name')`, ); } // Check the Symbol.toStringTag on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype, Symbol.toStringTag, ); expected = { writable: false, enumerable: false, configurable: true, value: 'TransactionCacheEntry', }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype, [Symbol.toStringTag])`, ); assert( typeof TransactionCacheEntry.prototype[Symbol.toStringTag], 'string', `typeof TransactionCacheEntry.prototype[Symbol.toStringTag]`, ); } // Check the insert method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype, 'insert', ); expected = { writable: true, enumerable: true, configurable: true, value: TransactionCacheEntry.prototype.insert, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype, 'insert')`, ); assert( typeof TransactionCacheEntry.prototype.insert, 'function', `typeof TransactionCacheEntry.prototype.insert`, ); actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype.insert, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype.insert, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype.insert, 'name', ); expected = { value: 'insert', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype.insert, 'name')`, ); } // Check the insertAndStreamBack method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype, 'insertAndStreamBack', ); expected = { writable: true, enumerable: true, configurable: true, value: TransactionCacheEntry.prototype.insertAndStreamBack, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype, 'insertAndStreamBack')`, ); assert( typeof TransactionCacheEntry.prototype.insertAndStreamBack, 'function', `typeof TransactionCacheEntry.prototype.insertAndStreamBack`, ); actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype.insertAndStreamBack, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype.insertAndStreamBack, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype.insertAndStreamBack, 'name', ); expected = { value: 'insertAndStreamBack', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype.insertAndStreamBack, 'name')`, ); } // Check the update method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype, 'update', ); expected = { writable: true, enumerable: true, configurable: true, value: TransactionCacheEntry.prototype.update, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype, 'update')`, ); assert( typeof TransactionCacheEntry.prototype.update, 'function', `typeof TransactionCacheEntry.prototype.update`, ); actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype.update, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype.update, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype.update, 'name', ); expected = { value: 'update', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype.update, 'name')`, ); } // Check the cancel method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype, 'cancel', ); expected = { writable: true, enumerable: true, configurable: true, value: TransactionCacheEntry.prototype.cancel, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype, 'cancel')`, ); assert( typeof TransactionCacheEntry.prototype.cancel, 'function', `typeof TransactionCacheEntry.prototype.cancel`, ); actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype.cancel, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype.cancel, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( TransactionCacheEntry.prototype.cancel, 'name', ); expected = { value: 'cancel', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(TransactionCacheEntry.prototype.cancel, 'name')`, ); } }); // insert(options: TransactionInsertOptions): FastlyBody; { routes.set('/transaction-cache-entry/insert/called-as-constructor', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); new entry.insert({ maxAge: 1 }); }, TypeError); }); routes.set( '/transaction-cache-entry/insert/entry-parameter-not-supplied', () => { let entry = CoreCache.transactionLookup('1'); assert( entry instanceof TransactionCacheEntry, true, 'entry instanceof TransactionCacheEntry', ); assertThrows( () => { entry.insert(); }, TypeError, `insert: At least 1 argument required, but only 0 passed`, ); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-maxAge-field-valid-record', () => { let body; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup('1'); body = entry.insert({ maxAge: 1 }); }); assert( body instanceof FastlyBody, true, `entry.insert({maxAge: 1}) instanceof FastlyBody`, ); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-maxAge-field-NaN', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-maxAge-field-postitive-infinity', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-maxAge-field-negative-infinity', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-maxAge-field-negative-number', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: -1, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-maxAge-field-too-large', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 2e13, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-initialAge-field-valid-record', () => { let body; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup('1'); body = entry.insert({ maxAge: 1, initialAge: 1 }); }); assert( body instanceof FastlyBody, true, `entry.insert({maxAge: 1,initialAge: 1}) instanceof FastlyBody`, ); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-initialAge-field-NaN', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, initialAge: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-initialAge-field-postitive-infinity', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, initialAge: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-initialAge-field-negative-infinity', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, initialAge: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-initialAge-field-negative-number', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, initialAge: -1, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-initialAge-field-too-large', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, initialAge: 2e13, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-valid-record', () => { let body; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup('1'); body = entry.insert({ maxAge: 1, staleWhileRevalidate: 1 }); }); assert( body instanceof FastlyBody, true, `entry.insert({maxAge: 1,staleWhileRevalidate: 1}) instanceof FastlyBody`, ); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-NaN', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, staleWhileRevalidate: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-postitive-infinity', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, staleWhileRevalidate: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-negative-infinity', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, staleWhileRevalidate: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-negative-number', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, staleWhileRevalidate: -1, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-too-large', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, staleWhileRevalidate: 2e13, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-length-field-valid-record', () => { let body; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup('1'); body = entry.insert({ maxAge: 1, length: 1 }); }); assert( body instanceof FastlyBody, true, `entry.insert({maxAge: 1,length: 1}) instanceof FastlyBody`, ); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-length-field-NaN', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, length: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-length-field-postitive-infinity', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, length: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-length-field-negative-infinity', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, length: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-length-field-negative-number', () => { assertThrows(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, length: -1, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-sensitive-field', () => { assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, sensitive: true, }); }); }, ); routes.set( '/transaction-cache-entry/insert/options-parameter-vary-field', () => { assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup('1'); entry.insert({ maxAge: 1, vary: ['animal', 'mineral', 'vegetable'], }); }); }, ); } // insertAndStreamBack(options: TransactionInsertOptions): [FastlyBody, CacheEntry]; { routes.set( '/transaction-cache-entry/insertAndStreamBack/called-as-constructor', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); new entry.insertAndStreamBack({ maxAge: 1 }); }, TypeError); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/entry-parameter-not-supplied', (event) => { const path = new URL(event.request.url).pathname; assertThrows( () => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack(); }, TypeError, `insertAndStreamBack: At least 1 argument required, but only 0 passed`, ); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-valid-record', (event) => { const path = new URL(event.request.url).pathname; let writer; let reader; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup(path); [writer, reader] = entry.insertAndStreamBack({ maxAge: 1 }); }); assert( writer instanceof FastlyBody, true, `writer instanceof FastlyBody`, ); assert( reader instanceof CacheEntry, true, `writer instanceof CacheEntry`, ); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-NaN', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-postitive-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-negative-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-negative-number', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: -1, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-too-large', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 2e13, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-valid-record', (event) => { const path = new URL(event.request.url).pathname; let writer; let reader; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup(path); [writer, reader] = entry.insertAndStreamBack({ maxAge: 1, initialAge: 1, }); }); assert( writer instanceof FastlyBody, true, `writer instanceof FastlyBody`, ); assert( reader instanceof CacheEntry, true, `writer instanceof CacheEntry`, ); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-NaN', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, initialAge: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-postitive-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, initialAge: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-negative-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, initialAge: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-negative-number', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, initialAge: -1, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-too-large', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, initialAge: 2e13, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-valid-record', (event) => { const path = new URL(event.request.url).pathname; let writer, reader; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup(path); [writer, reader] = entry.insertAndStreamBack({ maxAge: 1, staleWhileRevalidate: 1, }); }); assert( writer instanceof FastlyBody, true, `writer instanceof FastlyBody`, ); assert( reader instanceof CacheEntry, true, `writer instanceof CacheEntry`, ); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-NaN', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, staleWhileRevalidate: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-postitive-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, staleWhileRevalidate: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-negative-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, staleWhileRevalidate: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-negative-number', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, staleWhileRevalidate: -1, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-too-large', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, staleWhileRevalidate: 2e13, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-length-field-valid-record', (event) => { const path = new URL(event.request.url).pathname; let writer, reader; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup(path); [writer, reader] = entry.insertAndStreamBack({ maxAge: 1, length: 1, }); }); assert( writer instanceof FastlyBody, true, `writer instanceof FastlyBody`, ); assert( reader instanceof CacheEntry, true, `writer instanceof CacheEntry`, ); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-length-field-NaN', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, length: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-length-field-postitive-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, length: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-length-field-negative-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, length: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-length-field-negative-number', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, length: -1, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-sensitive-field', (event) => { const path = new URL(event.request.url).pathname; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, sensitive: true, }); }); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/write-to-writer-and-read-from-reader', async (event) => { const path = new URL(event.request.url).pathname; let entry = CoreCache.transactionLookup(path); let [writer, reader] = entry.insertAndStreamBack({ maxAge: 60 * 1000, sensitive: true, }); writer.append('hello'); writer.close(); const actual = await new Response(reader.body()).text(); assert(actual, 'hello', `actual === "hello"`); }, ); routes.set( '/transaction-cache-entry/insertAndStreamBack/options-parameter-vary-field', (event) => { const path = new URL(event.request.url).pathname; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup(path); entry.insertAndStreamBack({ maxAge: 1, vary: ['animal', 'mineral', 'vegetable'], }); }); }, ); } // update(options: TransactionInsertOptions): void; { routes.set( '/transaction-cache-entry/update/called-as-constructor', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); new entry.update({ maxAge: 1 }); }, TypeError); }, ); routes.set( '/transaction-cache-entry/update/entry-parameter-not-supplied', (event) => { const path = new URL(event.request.url).pathname; assertThrows( () => { let entry = CoreCache.transactionLookup(path); entry.update(); }, TypeError, `update: At least 1 argument required, but only 0 passed`, ); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-maxAge-field-valid-record', (event) => { const path = new URL(event.request.url).pathname; assertDoesNotThrow(() => { let writer = CoreCache.insert(path, { maxAge: 0, staleWhileRevalidate: 60 * 1000, }); writer.append('meow'); writer.close(); let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1 }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-maxAge-field-NaN', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-maxAge-field-postitive-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-maxAge-field-negative-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-maxAge-field-negative-number', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: -1, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-maxAge-field-too-large', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 2e13, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-initialAge-field-valid-record', (event) => { const path = new URL(event.request.url).pathname; assertDoesNotThrow(() => { let writer = CoreCache.insert(path, { maxAge: 0, staleWhileRevalidate: 60 * 1000, }); writer.append('meow'); writer.close(); let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, initialAge: 1 }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-initialAge-field-NaN', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, initialAge: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-initialAge-field-postitive-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, initialAge: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-initialAge-field-negative-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, initialAge: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-initialAge-field-negative-number', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, initialAge: -1, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-initialAge-field-too-large', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, initialAge: 2e13, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-valid-record', (event) => { const path = new URL(event.request.url).pathname; assertDoesNotThrow(() => { let writer = CoreCache.insert(path, { maxAge: 0, staleWhileRevalidate: 60 * 1000, }); writer.append('meow'); writer.close(); let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, staleWhileRevalidate: 1 }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-NaN', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, staleWhileRevalidate: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-postitive-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, staleWhileRevalidate: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-negative-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, staleWhileRevalidate: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-negative-number', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, staleWhileRevalidate: -1, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-too-large', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, staleWhileRevalidate: 2e13, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-length-field-valid-record', (event) => { const path = new URL(event.request.url).pathname; assertDoesNotThrow(() => { let writer = CoreCache.insert(path, { maxAge: 0, staleWhileRevalidate: 60 * 1000, }); writer.append('meow'); writer.close(); let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, length: 1 }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-length-field-NaN', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, length: NaN, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-length-field-postitive-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, length: Number.POSITIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-length-field-negative-infinity', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, length: Number.NEGATIVE_INFINITY, }); }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-length-field-negative-number', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1, length: -1, }); }); }, ); routes.set( '/transaction-cache-entry/update/write-to-writer-and-read-from-reader', async (event) => { const path = new URL(event.request.url).pathname; let entry = CoreCache.transactionLookup(path); let writer = entry.insert({ maxAge: 1, staleWhileRevalidate: 60 * 1000, }); writer.append('meow'); writer.close(); entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 60 * 1000, }); await sleep(1000); entry = CoreCache.transactionLookup(path); assert(entry.maxAge(), 60 * 1000, `entry2.maxAge() === 60 * 1000`); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-vary-field', async (event) => { const path = new URL(event.request.url).pathname; let entry = CoreCache.transactionLookup(path); let writer = entry.insert({ maxAge: 1, staleWhileRevalidate: 60 * 1000, vary: ['animal', 'mineral', 'vegetable'], }); writer.append('meow'); writer.close(); await sleep(1000); entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1000, vary: ['animal'], }); }, ); routes.set( '/transaction-cache-entry/update/options-parameter-userMetadata-field', async (event) => { const path = new URL(event.request.url).pathname; let entry = CoreCache.transactionLookup(path); let writer = entry.insert({ maxAge: 1, staleWhileRevalidate: 60 * 1000, }); writer.append('meow'); writer.close(); await sleep(1000); entry = CoreCache.transactionLookup(path); entry.update({ maxAge: 1000, userMetadata: 'hello', }); }, ); // TODO: tests for options parameter fields // surrogateKeys?: Array,-- empty string? -- toString which throws -- wrong types? } // cancel(): void; { routes.set( '/transaction-cache-entry/cancel/called-as-constructor', (event) => { const path = new URL(event.request.url).pathname; assertThrows(() => { let entry = CoreCache.transactionLookup(path); new entry.cancel(); }, TypeError); }, ); routes.set('/transaction-cache-entry/cancel/called-once', (event) => { const path = new URL(event.request.url).pathname; assertDoesNotThrow(() => { let entry = CoreCache.transactionLookup(path); entry.cancel(); }); }); routes.set( '/transaction-cache-entry/cancel/makes-entry-cancelled', (event) => { const path = new URL(event.request.url).pathname; let entry; assertDoesNotThrow(() => { entry = CoreCache.transactionLookup(path); entry.cancel(); }); assertThrows(() => { entry.insert({ maxAge: 1 }); }); }, ); routes.set( '/transaction-cache-entry/cancel/called-twice-throws', (event) => { const path = new URL(event.request.url).pathname; let entry; assertDoesNotThrow(() => { entry = CoreCache.transactionLookup(path); entry.cancel(); }); assertThrows(() => { entry.cancel(); }); }, ); } } { routes.set( '/core-cache/transaction-lookup-transaction-insert-vary-works', async () => { const key = `/core-cache/vary-works-${Date.now()}`; const animal = 'animal'; let entry = CoreCache.transactionLookup(key, { headers: { [animal]: 'cat', }, }); assert(entry.state().found(), false, `entry.state().found() === false`); let writer = entry.insert({ maxAge: 60_000 * 60, vary: [animal], headers: { [animal]: 'cat', }, }); writer.append('cat'); writer.close(); entry.close(); await sleep(1_000); entry = CoreCache.transactionLookup(key, { headers: { [animal]: 'cat', }, }); assert(entry.state().found(), true, `entry.state().found() === true`); assert( await streamToString(entry.body()), 'cat', `await streamToString(CoreCache.lookup(key).body())`, ); entry.close(); entry = CoreCache.transactionLookup(key, { headers: { [animal]: 'dog', }, }); assert(entry.state().found(), false, `entry.state().found() == false`); writer = entry.insert({ maxAge: 60_000 * 60, vary: [animal], headers: { [animal]: 'dog', }, }); writer.append('dog'); writer.close(); entry.close(); await sleep(1_000); entry = CoreCache.transactionLookup(key, { headers: { [animal]: 'dog', }, }); assert(entry.state().found(), true, `entry.state().found() === true`); assert( await streamToString(entry.body()), 'dog', `await streamToString(CoreCache.lookup(key).body())`, ); entry.close(); }, ); routes.set('/core-cache/lookup-insert-vary-works', async () => { const key = `/core-cache/vary-works-${Date.now()}`; const animal = 'animal'; let entry = CoreCache.lookup(key, { headers: { [animal]: 'cat', }, }); assert(entry, null, `entry == null`); let writer = CoreCache.insert(key, { maxAge: 60_000 * 60, vary: [animal], headers: { [animal]: 'cat', }, }); writer.append('cat'); writer.close(); await sleep(1_000); entry = CoreCache.lookup(key, { headers: { [animal]: 'cat', }, }); assert(entry.state().found(), true, `entry.state().found() === true`); assert( await streamToString(entry.body()), 'cat', `await streamToString(CoreCache.lookup(key).body())`, ); entry.close(); entry = CoreCache.lookup(key, { headers: { [animal]: 'dog', }, }); assert(entry, null, `entry == null`); writer = CoreCache.insert(key, { maxAge: 60_000 * 60, vary: [animal], headers: { [animal]: 'dog', }, }); writer.append('dog'); writer.close(); await sleep(1_000); entry = CoreCache.lookup(key, { headers: { [animal]: 'dog', }, }); assert(entry.state().found(), true, `entry.state().found() === true`); assert( await streamToString(entry.body()), 'dog', `await streamToString(CoreCache.lookup(key).body())`, ); }); } ================================================ FILE: integration-tests/js-compute/fixtures/app/src/cache-override.js ================================================ import { CacheOverride } from 'fastly:cache-override'; import { assert, assertThrows, assertDoesNotThrow } from './assertions.js'; import { isRunningLocally, routes } from './routes.js'; // CacheOverride constructor { routes.set( '/cache-override/constructor/called-as-regular-function', async () => { assertThrows( () => { CacheOverride(); }, TypeError, `calling a builtin CacheOverride constructor without new is forbidden`, ); }, ); routes.set('/cache-override/constructor/empty-parameter', async () => { assertThrows( () => { new CacheOverride(); }, TypeError, `CacheOverride constructor: At least 1 argument required, but only 0 passed`, ); }); routes.set('/cache-override/constructor/invalid-mode', async () => { // empty string not allowed assertThrows( () => { new CacheOverride(''); }, TypeError, `CacheOverride constructor: 'mode' has to be "none", "pass", or "override", but got ""`, ); assertThrows( () => { new CacheOverride('be nice to the cache'); }, TypeError, `CacheOverride constructor: 'mode' has to be "none", "pass", or "override", but got "be nice to the cache"`, ); }); routes.set('/cache-override/constructor/valid-mode', async () => { assertDoesNotThrow(() => { new CacheOverride('none'); }); assertDoesNotThrow(() => { new CacheOverride('pass'); }); assertDoesNotThrow(() => { new CacheOverride('override', {}); }); assertDoesNotThrow(() => { new CacheOverride({}); }); }); } // Using CacheOverride { routes.set('/cache-override/fetch/mode-none', async () => { if (isRunningLocally()) return; { const response = await fetch( 'https://http-me.fastly.dev/now?status=200', { backend: 'httpme', cacheOverride: new CacheOverride('none'), }, ); assert( response.headers.has('x-cache'), true, `CacheOveride('none'); response.headers.has('x-cache') === true`, ); } { const response = await fetch( 'https://http-me.fastly.dev/now?status=200', { backend: 'httpme', cacheOverride: 'none', }, ); assert( response.headers.has('x-cache'), true, `CacheOveride('none'); response.headers.has('x-cache') === true`, ); } }); routes.set('/cache-override/fetch/mode-pass', async () => { if (isRunningLocally()) return; { const response = await fetch( 'https://http-me.fastly.dev/now?status=200', { backend: 'httpme', cacheOverride: new CacheOverride('pass'), }, ); assert( response.headers.has('x-cache'), false, `CacheOveride('pass'); response.headers.has('x-cache') === false`, ); } { const response = await fetch( 'https://http-me.fastly.dev/now?status=200', { backend: 'httpme', cacheOverride: 'pass', }, ); assert( response.headers.has('x-cache'), false, `CacheOveride('pass'); response.headers.has('x-cache') === false`, ); } }); routes.set('/cache-override/fetch/null-304-body', async (event) => { const resp = await fetch( new Request('https://http-me.fastly.dev/body=foo?status=304', { method: 'POST', backend: 'httpme', cacheOverride: new CacheOverride({ async afterSend(resp) { resp.ttl = 1000000000; }, }), }), ); assert( resp.body, null, '304s should never have bodies even when processed through the caching code', ); }); } ================================================ FILE: integration-tests/js-compute/fixtures/app/src/cache-simple.js ================================================ /// /* eslint-env serviceworker */ import { assert, assertDoesNotThrow, assertThrows, assertRejects, iteratableToStream, streamToString, assertResolves, } from './assertions.js'; import { SimpleCache, SimpleCacheEntry } from 'fastly:cache'; import { routes, isRunningLocally } from './routes.js'; routes.set('/simple-cache/interface', () => { let actual = Reflect.ownKeys(SimpleCache); let expected = [ 'prototype', 'purge', 'get', 'getOrSet', 'set', 'length', 'name', ]; assert(actual, expected, `Reflect.ownKeys(SimpleCache)`); // Check the prototype descriptors are correct { actual = Reflect.getOwnPropertyDescriptor(SimpleCache, 'prototype'); expected = { value: SimpleCache.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache, 'prototype')`, ); } // Check the constructor function's defined parameter length is correct { actual = Reflect.getOwnPropertyDescriptor(SimpleCache, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache, 'length')`, ); } // Check the constructor function's name is correct { actual = Reflect.getOwnPropertyDescriptor(SimpleCache, 'name'); expected = { value: 'SimpleCache', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache, 'name')`, ); } // Check the prototype has the correct keys { actual = Reflect.ownKeys(SimpleCache.prototype); expected = ['constructor', Symbol.toStringTag]; assert(actual, expected, `Reflect.ownKeys(SimpleCache.prototype)`); } // Check the constructor on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( SimpleCache.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: SimpleCache.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.prototype, 'constructor')`, ); assert( typeof SimpleCache.prototype.constructor, 'function', `typeof SimpleCache.prototype.constructor`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCache.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCache.prototype.constructor, 'name', ); expected = { value: 'SimpleCache', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.prototype.constructor, 'name')`, ); } // Check the Symbol.toStringTag on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( SimpleCache.prototype, Symbol.toStringTag, ); expected = { writable: false, enumerable: false, configurable: true, value: 'SimpleCache', }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.prototype, [Symbol.toStringTag])`, ); assert( typeof SimpleCache.prototype[Symbol.toStringTag], 'string', `typeof SimpleCache.prototype[Symbol.toStringTag]`, ); } // Check the get static method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(SimpleCache, 'get'); expected = { writable: true, enumerable: true, configurable: true, value: SimpleCache.get, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache, 'get')`, ); assert(typeof SimpleCache.get, 'function', `typeof SimpleCache.get`); actual = Reflect.getOwnPropertyDescriptor(SimpleCache.get, 'length'); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.get, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(SimpleCache.get, 'name'); expected = { value: 'get', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.get, 'name')`, ); } // Check the set static method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(SimpleCache, 'set'); expected = { writable: true, enumerable: true, configurable: true, value: SimpleCache.set, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache, 'set')`, ); assert(typeof SimpleCache.set, 'function', `typeof SimpleCache.set`); actual = Reflect.getOwnPropertyDescriptor(SimpleCache.set, 'length'); expected = { value: 3, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.set, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(SimpleCache.set, 'name'); expected = { value: 'set', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.set, 'name')`, ); } // Check the purge static method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(SimpleCache, 'purge'); expected = { writable: true, enumerable: true, configurable: true, value: SimpleCache.purge, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache, 'purge')`, ); assert(typeof SimpleCache.purge, 'function', `typeof SimpleCache.purge`); actual = Reflect.getOwnPropertyDescriptor(SimpleCache.purge, 'length'); expected = { value: 2, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.purge, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(SimpleCache.purge, 'name'); expected = { value: 'purge', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.purge, 'name')`, ); } // Check the getOrSet static method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(SimpleCache, 'getOrSet'); expected = { writable: true, enumerable: true, configurable: true, value: SimpleCache.getOrSet, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache, 'getOrSet')`, ); assert( typeof SimpleCache.getOrSet, 'function', `typeof SimpleCache.getOrSet`, ); actual = Reflect.getOwnPropertyDescriptor(SimpleCache.getOrSet, 'length'); expected = { value: 2, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.getOrSet, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(SimpleCache.getOrSet, 'name'); expected = { value: 'getOrSet', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCache.getOrSet, 'name')`, ); } }); // SimpleCache constructor { routes.set('/simple-store/constructor/called-as-regular-function', () => { assertThrows(() => { SimpleCache(); }, TypeError); }); routes.set('/simple-cache/constructor/throws', () => { assertThrows(() => new SimpleCache(), TypeError); }); } // SimpleCache purge static method // static purge(key: string, options: PurgeOptions): undefined; { routes.set('/simple-cache/purge/called-as-constructor', () => { if (!isRunningLocally()) { assertThrows(() => { new SimpleCache.purge('1', { scope: 'global' }); }, TypeError); } }); // Ensure we correctly coerce the parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set('/simple-cache/purge/key-parameter-calls-7.1.17-ToString', () => { if (!isRunningLocally()) { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const key = { toString() { throw sentinel; }, }; SimpleCache.purge(key, { scope: 'global' }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { SimpleCache.purge(Symbol(), { scope: 'global' }); }, TypeError, `can't convert symbol to string`, ); } }); routes.set('/simple-cache/purge/key-parameter-not-supplied', () => { if (!isRunningLocally()) { assertThrows( () => { SimpleCache.purge(); }, TypeError, `SimpleCache.purge: At least 2 arguments required, but only 0 passed`, ); } }); routes.set('/simple-cache/purge/key-parameter-empty-string', () => { if (!isRunningLocally()) { assertThrows( () => { SimpleCache.purge('', { scope: 'global' }); }, Error, `SimpleCache.purge: key can not be an empty string`, ); } }); routes.set('/simple-cache/purge/key-parameter-8135-character-string', () => { if (!isRunningLocally()) { assertDoesNotThrow(() => { const key = 'a'.repeat(8135); SimpleCache.purge(key, { scope: 'global' }); }); } }); routes.set('/simple-cache/purge/key-parameter-8136-character-string', () => { if (!isRunningLocally()) { assertThrows( () => { const key = 'a'.repeat(8136); SimpleCache.purge(key, { scope: 'global' }); }, Error, `SimpleCache.purge: key is too long, the maximum allowed length is 8135.`, ); } }); routes.set('/simple-cache/purge/options-parameter', () => { if (!isRunningLocally()) { assertThrows( () => { const key = 'a'; SimpleCache.purge(key, 'hello'); }, Error, `SimpleCache.purge: options parameter is not an object.`, ); assertThrows( () => { const key = 'a'; SimpleCache.purge(key, { scope: Symbol() }); }, Error, `can't convert symbol to string`, ); assertThrows( () => { const key = 'a'; SimpleCache.purge(key, { scope: '' }); }, Error, `SimpleCache.purge: scope field of options parameter must be either 'pop', or 'global'.`, ); assertDoesNotThrow(() => { const key = 'a'; SimpleCache.purge(key, { scope: 'pop' }); }); assertDoesNotThrow(() => { const key = 'a'; SimpleCache.purge(key, { scope: 'global' }); }); } }); routes.set('/simple-cache/purge/returns-undefined', () => { if (!isRunningLocally()) { assert( SimpleCache.purge('meow', { scope: 'global' }), undefined, "SimpleCache.purge('meow', {scope'global'})", ); } }); } // SimpleCache set static method // static set(key: string, value: BodyInit, ttl: number): undefined; { routes.set('/simple-cache/set/called-as-constructor', () => { if (!isRunningLocally()) { assertThrows(() => { new SimpleCache.set('1', 'meow', 1); }, TypeError); } }); // Ensure we correctly coerce the key parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set('/simple-cache/set/key-parameter-calls-7.1.17-ToString', () => { if (!isRunningLocally()) { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const key = { toString() { throw sentinel; }, }; SimpleCache.set(key, 'meow', 1); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { SimpleCache.set(Symbol(), 'meow', 1); }, TypeError, `can't convert symbol to string`, ); } }); // Ensure we correctly coerce the tll parameter to a number as according to // https://tc39.es/ecma262/#sec-tonumber routes.set('/simple-cache/set/tll-parameter-7.1.4-ToNumber', () => { if (!isRunningLocally()) { let sentinel; let requestedType; const test = () => { sentinel = Symbol('sentinel'); const ttl = { [Symbol.toPrimitive](type) { requestedType = type; throw sentinel; }, }; SimpleCache.set('1', 'meow', ttl); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); assert(requestedType, 'number', 'requestedType === "number"'); } assertThrows( () => SimpleCache.set('1', 'meow', Symbol()), TypeError, `can't convert symbol to number`, ); } }); routes.set('/simple-cache/set/no-parameters-supplied', () => { if (!isRunningLocally()) { assertThrows( () => { SimpleCache.set(); }, TypeError, `SimpleCache.set: At least 3 arguments required, but only 0 passed`, ); } }); routes.set('/simple-cache/set/key-parameter-empty-string', () => { if (!isRunningLocally()) { assertThrows( () => { SimpleCache.set('', 'meow', 1); }, Error, `SimpleCache.set: key can not be an empty string`, ); } }); routes.set('/simple-cache/set/key-parameter-8135-character-string', () => { if (!isRunningLocally()) { assertDoesNotThrow(() => { const key = 'a'.repeat(8135); SimpleCache.set(key, 'meow', 1); }); } }); routes.set('/simple-cache/set/key-parameter-8136-character-string', () => { if (!isRunningLocally()) { assertThrows( () => { const key = 'a'.repeat(8136); SimpleCache.set(key, 'meow', 1); }, Error, `SimpleCache.set: key is too long, the maximum allowed length is 8135.`, ); } }); routes.set('/simple-cache/set/ttl-parameter-negative-number', () => { if (!isRunningLocally()) { assertThrows( () => { SimpleCache.set('cat', 'meow', -1); }, Error, `SimpleCache.set: TTL parameter is an invalid value, only positive numbers can be used for TTL values.`, ); } }); routes.set('/simple-cache/set/ttl-parameter-NaN', () => { if (!isRunningLocally()) { assertThrows( () => { SimpleCache.set('cat', 'meow', NaN); }, Error, `SimpleCache.set: TTL parameter is an invalid value, only positive numbers can be used for TTL values.`, ); } }); routes.set('/simple-cache/set/ttl-parameter-Infinity', () => { if (!isRunningLocally()) { assertThrows( () => { SimpleCache.set('cat', 'meow', Number.POSITIVE_INFINITY); }, Error, `SimpleCache.set: TTL parameter is an invalid value, only positive numbers can be used for TTL values.`, ); assertThrows( () => { SimpleCache.set('cat', 'meow', Number.NEGATIVE_INFINITY); }, Error, `SimpleCache.set: TTL parameter is an invalid value, only positive numbers can be used for TTL values.`, ); } }); routes.set('/simple-cache/set/value-parameter-as-undefined', () => { if (!isRunningLocally()) { assert( SimpleCache.set('meow', undefined, 1), undefined, 'SimpleCache.set("meow", undefined, 1) === undefined', ); } }); // - ReadableStream routes.set( '/simple-cache/set/value-parameter-readablestream-missing-length-parameter', () => { if (!isRunningLocally()) { // TODO: remove this when streams are supported assertThrows( () => { const stream = iteratableToStream([]); SimpleCache.set('meow', stream, 1); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); routes.set( '/simple-cache/set/value-parameter-readablestream-negative-length-parameter', () => { if (!isRunningLocally()) { // TODO: remove this when streams are supported assertThrows( () => { const stream = iteratableToStream([]); SimpleCache.set('meow', stream, 1, -1); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); routes.set( '/simple-cache/set/value-parameter-readablestream-nan-length-parameter', () => { if (!isRunningLocally()) { // TODO: remove this when streams are supported assertThrows( () => { const stream = iteratableToStream([]); SimpleCache.set('meow', stream, 1, NaN); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); routes.set( '/simple-cache/set/value-parameter-readablestream-negative-infinity-length-parameter', () => { if (!isRunningLocally()) { // TODO: remove this when streams are supported assertThrows( () => { const stream = iteratableToStream([]); SimpleCache.set('meow', stream, 1, Number.NEGATIVE_INFINITY); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); routes.set( '/simple-cache/set/value-parameter-readablestream-positive-infinity-length-parameter', () => { if (!isRunningLocally()) { // TODO: remove this when streams are supported assertThrows( () => { const stream = iteratableToStream([]); SimpleCache.set('meow', stream, 1, Number.POSITIVE_INFINITY); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); // Ensure we correctly coerce the tll parameter to a number as according to // https://tc39.es/ecma262/#sec-tonumber routes.set('/simple-cache/set/length-parameter-7.1.4-ToNumber', async () => { if (!isRunningLocally()) { const res = await fetch( 'https://compute-sdk-test-backend.edgecompute.app/', { backend: 'TheOrigin', }, ); let sentinel; let requestedType; const test = () => { sentinel = Symbol('sentinel'); const length = { [Symbol.toPrimitive](type) { requestedType = type; throw sentinel; }, }; SimpleCache.set('1', res.body, 1, length); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); assert(requestedType, 'number', 'requestedType === "number"'); } assertThrows( () => SimpleCache.set('1', res.body, 1, Symbol()), TypeError, `can't convert symbol to number`, ); } }); routes.set('/simple-cache/set/value-parameter-readablestream-empty', () => { if (!isRunningLocally()) { // TODO: remove this when streams are supported assertThrows( () => { const stream = iteratableToStream([]); SimpleCache.set('meow', stream, 1, 0); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }); routes.set('/simple-cache/set/value-parameter-readablestream-locked', () => { if (!isRunningLocally()) { const stream = iteratableToStream([]); // getReader() causes the stream to become locked stream.getReader(); assertThrows( () => { SimpleCache.set('meow', stream, 1, 0); }, TypeError, `Can't use a ReadableStream that's locked or has ever been read from or canceled`, ); } }); routes.set('/simple-cache/set/value-parameter-readablestream', async () => { if (!isRunningLocally()) { const res = await fetch( 'https://compute-sdk-test-backend.edgecompute.app/', { backend: 'TheOrigin', }, ); let result = SimpleCache.set( 'readablestream', res.body, 100, res.headers.get('content-length'), ); assert( result, undefined, `SimpleCache.set('readablestream', res.body, 100)`, ); } }); // - URLSearchParams routes.set('/simple-cache/set/value-parameter-URLSearchParams', () => { if (!isRunningLocally()) { const items = [ new URLSearchParams(), new URLSearchParams({ a: 'b', c: 'd' }), ]; for (const searchParams of items) { let result = SimpleCache.set('meow', searchParams, 1); assert( result, undefined, `SimpleCache.set("meow", searchParams, 1) === undefiend`, ); } } }); // - USV strings routes.set('/simple-cache/set/value-parameter-strings', () => { if (!isRunningLocally()) { const strings = [ // empty '', // lone surrogate '\uD800', // surrogate pair '𠈓', String('carrot'), ]; for (const string of strings) { let result = SimpleCache.set('meow', string, 1); assert( result, undefined, `SimpleCache.set("meow", string, 1) === undefined`, ); } } }); // https://tc39.es/ecma262/#sec-tostring routes.set('/simple-cache/set/value-parameter-calls-7.1.17-ToString', () => { if (!isRunningLocally()) { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const value = { toString() { throw sentinel; }, }; SimpleCache.set('meow', value, 1); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { SimpleCache.set('meow', Symbol(), 1); }, TypeError, `can't convert symbol to string`, ); } }); // - buffer source routes.set('/simple-cache/set/value-parameter-buffer', () => { if (!isRunningLocally()) { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = SimpleCache.set('meow', typedArray.buffer, 1); assert( result, undefined, `SimpleCache.set("meow", typedArray.buffer, 1) === undefined`, ); } } }); routes.set('/simple-cache/set/value-parameter-arraybuffer', () => { if (!isRunningLocally()) { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = SimpleCache.set('meow', typedArray.buffer, 1); assert( result, undefined, `SimpleCache.set("meow", typedArray.buffer, 1) === undefined`, ); } } }); routes.set('/simple-cache/set/value-parameter-typed-arrays', () => { if (!isRunningLocally()) { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = SimpleCache.set('meow', typedArray, 1); assert( result, undefined, `SimpleCache.set("meow", typedArray, 1) === undefined`, ); } } }); routes.set('/simple-cache/set/value-parameter-dataview', () => { if (!isRunningLocally()) { const typedArrayConstructors = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array, ]; for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); const view = new DataView(typedArray.buffer); let result = SimpleCache.set('meow', view, 1); assert( result, undefined, `SimpleCache.set("meow", view, 1) === undefined`, ); } } }); routes.set('/simple-cache/set/returns-undefined', () => { if (!isRunningLocally()) { assert( SimpleCache.set('1', 'meow', 1), undefined, "SimpleCache.set('1', 'meow', 1) === undefined", ); } }); } // SimpleCache get static method // static get(key: string): SimpleCacheEntry | null; { routes.set('/simple-cache/get/called-as-constructor', () => { if (!isRunningLocally()) { assertThrows(() => { new SimpleCache.get('1'); }, TypeError); } }); // https://tc39.es/ecma262/#sec-tostring routes.set('/simple-cache/get/key-parameter-calls-7.1.17-ToString', () => { if (!isRunningLocally()) { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const key = { toString() { throw sentinel; }, }; SimpleCache.get(key); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { SimpleCache.get(Symbol()); }, TypeError, `can't convert symbol to string`, ); } }); routes.set('/simple-cache/get/key-parameter-not-supplied', () => { if (!isRunningLocally()) { assertThrows( () => { SimpleCache.get(); }, TypeError, `SimpleCache.get: At least 1 argument required, but only 0 passed`, ); } }); routes.set('/simple-cache/get/key-parameter-empty-string', () => { if (!isRunningLocally()) { assertThrows( () => { SimpleCache.get(''); }, Error, `SimpleCache.get: key can not be an empty string`, ); } }); routes.set('/simple-cache/get/key-parameter-8135-character-string', () => { if (!isRunningLocally()) { assertDoesNotThrow(() => { const key = 'a'.repeat(8135); SimpleCache.get(key); }); } }); routes.set('/simple-cache/get/key-parameter-8136-character-string', () => { if (!isRunningLocally()) { assertThrows( () => { const key = 'a'.repeat(8136); SimpleCache.get(key); }, Error, `SimpleCache.get: key is too long, the maximum allowed length is 8135.`, ); } }); routes.set('/simple-cache/get/key-does-not-exist-returns-null', () => { if (!isRunningLocally()) { let result = SimpleCache.get(Math.random()); assert(result, null, `SimpleCache.get(Math.random()) === null`); } }); routes.set('/simple-cache/get/key-exists', () => { if (!isRunningLocally()) { SimpleCache.set('cat', 'meow', 100); let result = SimpleCache.get('cat'); assert( result instanceof SimpleCacheEntry, true, `SimpleCache.get('cat') instanceof SimpleCacheEntry`, ); } }); } // SimpleCacheEntry { routes.set('/simple-cache-entry/interface', async () => { return simpleCacheEntryInterfaceTests(); }); routes.set('/simple-cache-entry/text/valid', async () => { if (!isRunningLocally()) { let key = `entry-text-valid`; SimpleCache.set(key, 'hello', 100); let entry = SimpleCache.get(key); let result = entry.text(); assert( result instanceof Promise, true, `entry.text() instanceof Promise`, ); result = await result; assert(result, 'hello', `await entry.text()`); } }); routes.set('/simple-cache-entry/json/valid', async () => { if (!isRunningLocally()) { let key = `entry-json-valid`; const obj = { a: 1, b: 2, c: 3 }; SimpleCache.set(key, JSON.stringify(obj), 100); let entry = SimpleCache.get(key); let result = entry.json(); assert( result instanceof Promise, true, `entry.json() instanceof Promise`, ); result = await result; assert(result, obj, `await entry.json()`); } }); routes.set('/simple-cache-entry/json/invalid', async () => { if (!isRunningLocally()) { let key = `entry-json-invalid`; SimpleCache.set(key, "132abc;['-=9", 100); let entry = SimpleCache.get(key); await assertRejects( () => entry.json(), SyntaxError, `JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 4 of the JSON data`, ); } }); routes.set('/simple-cache-entry/arrayBuffer/valid', async () => { if (!isRunningLocally()) { let key = `entry-arraybuffer-valid`; SimpleCache.set(key, new Int8Array([0, 1, 2, 3]), 100); let entry = SimpleCache.get(key); let result = entry.arrayBuffer(); assert( result instanceof Promise, true, `entry.arrayBuffer() instanceof Promise`, ); result = await result; assert( result instanceof ArrayBuffer, true, `(await entry.arrayBuffer()) instanceof ArrayBuffer`, ); } }); routes.set('/simple-cache-entry/body', async () => { if (!isRunningLocally()) { let key = `entry-body`; SimpleCache.set(key, 'body body body', 100); let entry = SimpleCache.get(key); let result = entry.body; assert( result instanceof ReadableStream, true, `entry.body instanceof ReadableStream`, ); let text = await streamToString(result); assert(text, 'body body body', `entry.body contents as string`); } }); routes.set('/simple-cache-entry/bodyUsed', async () => { if (!isRunningLocally()) { let key = `entry-bodyUsed`; SimpleCache.set(key, 'body body body', 100); let entry = SimpleCache.get(key); assert(entry.bodyUsed, false, `entry.bodyUsed`); await entry.text(); assert(entry.bodyUsed, true, `entry.bodyUsed`); } }); routes.set('/simple-cache-entry/readablestream', async () => { if (!isRunningLocally()) { const res = await fetch( 'https://compute-sdk-test-backend.edgecompute.app/', { backend: 'TheOrigin', }, ); let key = `readablestream`; SimpleCache.set(key, res.body, 100, res.headers.get('content-length')); let entry = SimpleCache.get(key); assert( await entry.text(), 'Compute SDK Test Backend', `await entry.text()`, ); } }); } async function simpleCacheEntryInterfaceTests() { let actual = Reflect.ownKeys(SimpleCacheEntry); let expected = ['prototype', 'length', 'name']; assert(actual, expected, `Reflect.ownKeys(SimpleCacheEntry)`); actual = Reflect.getOwnPropertyDescriptor(SimpleCacheEntry, 'prototype'); expected = { value: SimpleCacheEntry.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry, 'prototype')`, ); actual = Reflect.getOwnPropertyDescriptor(SimpleCacheEntry, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(SimpleCacheEntry, 'name'); expected = { value: 'SimpleCacheEntry', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry, 'name')`, ); actual = Reflect.ownKeys(SimpleCacheEntry.prototype); expected = [ 'constructor', 'body', 'bodyUsed', 'arrayBuffer', 'json', 'text', Symbol.toStringTag, ]; assert(actual, expected, `Reflect.ownKeys(SimpleCacheEntry.prototype)`); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: SimpleCacheEntry.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'constructor')`, ); actual = Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'text'); expected = { writable: true, enumerable: true, configurable: true, value: SimpleCacheEntry.prototype.text, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'text')`, ); actual = Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'json'); expected = { writable: true, enumerable: true, configurable: true, value: SimpleCacheEntry.prototype.json, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'json')`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype, 'arrayBuffer', ); expected = { writable: true, enumerable: true, configurable: true, value: SimpleCacheEntry.prototype.arrayBuffer, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'arrayBuffer')`, ); actual = Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'body'); assert( actual.enumerable, true, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'body').enumerable`, ); assert( actual.configurable, true, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'body').configurable`, ); assert( 'set' in actual, true, `'set' in Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'body')`, ); assert( actual.set, undefined, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'body').set`, ); assert( typeof actual.get, 'function', `typeof Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'body').get`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype, 'bodyUsed', ); assert( actual.enumerable, true, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'bodyUsed').enumerable`, ); assert( actual.configurable, true, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'bodyUsed').configurable`, ); assert( 'set' in actual, true, `'set' in Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'bodyUsed')`, ); assert( actual.set, undefined, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'bodyUsed').set`, ); assert( typeof actual.get, 'function', `typeof Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype, 'bodyUsed').get`, ); assert( typeof SimpleCacheEntry.prototype.constructor, 'function', `typeof SimpleCacheEntry.prototype.constructor`, ); assert( typeof SimpleCacheEntry.prototype.text, 'function', `typeof SimpleCacheEntry.prototype.text`, ); assert( typeof SimpleCacheEntry.prototype.json, 'function', `typeof SimpleCacheEntry.prototype.json`, ); assert( typeof SimpleCacheEntry.prototype.arrayBuffer, 'function', `typeof SimpleCacheEntry.prototype.arrayBuffer`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype.constructor, 'name', ); expected = { value: 'SimpleCacheEntry', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype.constructor, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype.text, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype.text, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype.text, 'name', ); expected = { value: 'text', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype.text, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype.json, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype.json, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype.json, 'name', ); expected = { value: 'json', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype.json, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype.arrayBuffer, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype.arrayBuffer, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( SimpleCacheEntry.prototype.arrayBuffer, 'name', ); expected = { value: 'arrayBuffer', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(SimpleCacheEntry.prototype.arrayBuffer, 'name')`, ); } // SimpleCache getOrSet static method // static getOrSet(key: string, set: () => Promise<{value: BodyInit, ttl: number}>): Promise; // static getOrSet(key: string, set: () => Promise<{value: ReadableStream, ttl: number, length: number}>): Promise; { routes.set('/simple-cache/getOrSet/rejection-rejects-outer', async () => { if (!isRunningLocally()) { let key = String(Math.random()); SimpleCache.get(key); assertRejects( () => SimpleCache.getOrSet(key, async () => { throw RangeError('inner rejection'); }), RangeError, 'inner rejection', ); } }); routes.set('/simple-cache/getOrSet/called-as-constructor', () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/called-as-constructor'; assertThrows(() => { new SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl: 10, }; }); }, TypeError); } }); routes.set('/simple-cache/getOrSet/no-parameters-supplied', async () => { if (!isRunningLocally()) { await assertRejects( async () => { await SimpleCache.getOrSet(); }, TypeError, `SimpleCache.getOrSet: At least 2 arguments required, but only 0 passed`, ); } }); // Ensure we correctly coerce the key parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set( '/simple-cache/getOrSet/key-parameter-calls-7.1.17-ToString', async () => { if (!isRunningLocally()) { let sentinel = { sentinel: 'sentinel' }; const test = async () => { const key = { toString() { throw sentinel; }, }; await SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl: 10, }; }); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } await assertRejects( async () => { await SimpleCache.getOrSet(Symbol(), async () => { return { value: 'meow', ttl: 10, }; }); }, TypeError, `can't convert symbol to string`, ); } }, ); // TODO: second parameter not a function routes.set('/simple-cache/getOrSet/key-parameter-empty-string', async () => { if (!isRunningLocally()) { await assertRejects( async () => { await SimpleCache.getOrSet('', async () => { return { value: 'meow', ttl: 10, }; }); }, Error, `SimpleCache.getOrSet: key can not be an empty string`, ); } }); routes.set( '/simple-cache/getOrSet/key-parameter-8135-character-string', async () => { if (!isRunningLocally()) { await assertDoesNotThrow(async () => { const key = 'a'.repeat(8135); await SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl: 10, }; }); }); } }, ); routes.set( '/simple-cache/getOrSet/key-parameter-8136-character-string', async () => { if (!isRunningLocally()) { await assertRejects( async () => { const key = 'a'.repeat(8136); await SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl: 10, }; }); }, Error, `SimpleCache.getOrSet: key is too long, the maximum allowed length is 8135.`, ); } }, ); // Ensure we correctly coerce the ttl field to a number as according to // https://tc39.es/ecma262/#sec-tonumber routes.set('/simple-cache/getOrSet/ttl-field-7.1.4-ToNumber', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/ttl-field-7.1.4-ToNumber'; let sentinel = { sentinel: 'sentinel' }; let requestedType; const test = async () => { const ttl = { [Symbol.toPrimitive](type) { requestedType = type; throw sentinel; }, }; await SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl, }; }); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); assert(requestedType, 'number', 'requestedType === "number"'); } await assertRejects( () => SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl: Symbol(), }; }), TypeError, `can't convert symbol to number`, ); } }); routes.set('/simple-cache/getOrSet/ttl-field-negative-number', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/ttl-field-negative-number'; await assertRejects( async () => { await SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl: -1, }; }); }, Error, `SimpleCache.getOrSet: TTL field is an invalid value, only positive numbers can be used for TTL values.`, ); } }); routes.set('/simple-cache/getOrSet/ttl-field-NaN', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/ttl-field-NaN'; await assertRejects( async () => { await SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl: NaN, }; }); }, Error, `SimpleCache.getOrSet: TTL field is an invalid value, only positive numbers can be used for TTL values.`, ); } }); routes.set('/simple-cache/getOrSet/ttl-field-Infinity', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/ttl-field-Infinity'; await assertRejects( async () => { await SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl: Number.POSITIVE_INFINITY, }; }); }, Error, `SimpleCache.getOrSet: TTL field is an invalid value, only positive numbers can be used for TTL values.`, ); await assertRejects( async () => { await SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl: Number.NEGATIVE_INFINITY, }; }); }, Error, `SimpleCache.getOrSet: TTL field is an invalid value, only positive numbers can be used for TTL values.`, ); } }); routes.set('/simple-cache/getOrSet/value-field-as-undefined', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-as-undefined'; await assertResolves(async () => { await SimpleCache.getOrSet(key, async () => { return { value: undefined, ttl: 1 }; }); }); } }); // - ReadableStream routes.set( '/simple-cache/getOrSet/value-field-readablestream-missing-length-field', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-readablestream-missing-length-field'; // TODO: remove this when streams are supported await assertRejects( async () => { const stream = iteratableToStream([]); await SimpleCache.getOrSet(key, async () => { return { value: stream, ttl: 1 }; }); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); routes.set( '/simple-cache/getOrSet/value-field-readablestream-negative-length-field', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-readablestream-negative-length-field'; // TODO: remove this when streams are supported await assertRejects( async () => { const stream = iteratableToStream([]); await SimpleCache.getOrSet(key, async () => { return { value: stream, ttl: 1, length: -1 }; }); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); routes.set( '/simple-cache/getOrSet/value-field-readablestream-nan-length-field', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-readablestream-nan-length-field'; // TODO: remove this when streams are supported await assertRejects( async () => { const stream = iteratableToStream([]); await SimpleCache.getOrSet(key, async () => { return { value: stream, ttl: 1, length: NaN }; }); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); routes.set( '/simple-cache/getOrSet/value-field-readablestream-negative-infinity-length-field', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-readablestream-negative-infinity-length-field'; // TODO: remove this when streams are supported await assertRejects( async () => { const stream = iteratableToStream([]); await SimpleCache.getOrSet(key, async () => { return { value: stream, ttl: 1, length: Number.NEGATIVE_INFINITY, }; }); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); routes.set( '/simple-cache/getOrSet/value-field-readablestream-positive-infinity-length-field', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-readablestream-positive-infinity-length-field'; // TODO: remove this when streams are supported await assertRejects( async () => { const stream = iteratableToStream([]); await SimpleCache.getOrSet(key, async () => { return { value: stream, ttl: 1, length: Number.POSITIVE_INFINITY, }; }); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); // Ensure we correctly coerce the length field to a number as according to // https://tc39.es/ecma262/#sec-tonumber routes.set('/simple-cache/getOrSet/length-field-7.1.4-ToNumber', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/length-field-7.1.4-ToNumber'; const res = await fetch( 'https://compute-sdk-test-backend.edgecompute.app/', { backend: 'TheOrigin', }, ); let sentinel = { sentinel: 'sentinel' }; let requestedType; const test = async () => { const length = { [Symbol.toPrimitive](type) { requestedType = type; throw sentinel; }, }; await SimpleCache.getOrSet(key, async () => { return { value: res.body, ttl: 1, length }; }); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); assert(requestedType, 'number', 'requestedType === "number"'); } await assertRejects( async () => await SimpleCache.getOrSet(key, async () => { return { value: res.body, ttl: 1, length: Symbol() }; }), TypeError, `can't convert symbol to number`, ); } }); routes.set( '/simple-cache/getOrSet/value-field-readablestream-empty', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-readablestream-empty'; // TODO: remove this when streams are supported await assertRejects( async () => { const stream = iteratableToStream([]); await SimpleCache.getOrSet(key, async () => { return { value: stream, ttl: 1, length: 0 }; }); }, TypeError, `Content-provided streams are not yet supported for streaming into SimpleCache`, ); } }, ); routes.set( '/simple-cache/getOrSet/value-field-readablestream-locked', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-readablestream-locked'; const stream = iteratableToStream([]); // getReader() causes the stream to become locked stream.getReader(); await assertRejects( async () => { await SimpleCache.getOrSet(key, async () => { return { value: stream, ttl: 1, length: 0 }; }); }, TypeError, `Can't use a ReadableStream that's locked or has ever been read from or canceled`, ); } }, ); routes.set('/simple-cache/getOrSet/value-field-readablestream', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-readablestream'; const res = await fetch( 'https://compute-sdk-test-backend.edgecompute.app/', { backend: 'TheOrigin', }, ); await assertResolves(async () => { await SimpleCache.getOrSet(key, async () => { return { value: res.body, ttl: 100, length: res.headers.get('content-length'), }; }); }); } }); // - URLSearchParams routes.set('/simple-cache/getOrSet/value-field-URLSearchParams', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-URLSearchParams'; const items = [ new URLSearchParams(), new URLSearchParams({ a: 'b', c: 'd' }), ]; for (const searchParams of items) { await assertResolves(async () => { await SimpleCache.getOrSet(key, async () => { return { value: searchParams, ttl: 1 }; }); }); } } }); // - USV strings routes.set('/simple-cache/getOrSet/value-field-strings', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-strings'; const strings = [ // empty '', // lone surrogate '\uD800', // surrogate pair '𠈓', String('carrot'), ]; for (const string of strings) { await assertResolves(async () => { await SimpleCache.getOrSet(key, async () => { return { value: string, ttl: 1 }; }); }); } } }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/simple-cache/getOrSet/value-field-calls-7.1.17-ToString', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-calls-7.1.17-ToString'; let sentinel = { sentinel: 'sentinel' }; const test = async () => { const value = { toString() { throw sentinel; }, }; await SimpleCache.getOrSet(key, async () => { return { value, ttl: 1 }; }); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } await assertRejects( async () => { await SimpleCache.getOrSet(key, async () => { return { value: Symbol(), ttl: 1 }; }); }, TypeError, `can't convert symbol to string`, ); } }, ); // - buffer source routes.set('/simple-cache/getOrSet/value-field-buffer', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-buffer'; const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); await assertResolves(async () => { await SimpleCache.getOrSet(key + constructor.name, async () => { return { value: typedArray.buffer, ttl: 1 }; }); }); } } }); routes.set('/simple-cache/getOrSet/value-field-typed-arrays', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-typed-arrays'; const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); await assertResolves(async () => { await SimpleCache.getOrSet(key + constructor.name, async () => { return { value: typedArray, ttl: 1 }; }); }); } } }); routes.set('/simple-cache/getOrSet/value-field-dataview', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/value-field-dataview'; const typedArrayConstructors = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array, ]; for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); const view = new DataView(typedArray.buffer); await assertResolves(async () => { await SimpleCache.getOrSet(key + constructor.name, async () => { return { value: view, ttl: 1 }; }); }); } } }); routes.set('/simple-cache/getOrSet/returns-SimpleCacheEntry', async () => { if (!isRunningLocally()) { let key = '/simple-cache/getOrSet/returns-SimpleCacheEntry'; let result = await SimpleCache.getOrSet(key, async () => { return { value: 'meow', ttl: 10, }; }); assert( result instanceof SimpleCacheEntry, true, 'result instanceof SimpleCacheEntry', ); } }); routes.set( '/simple-cache/getOrSet/executes-the-set-method-when-key-not-in-cache', async () => { if (!isRunningLocally()) { let called = false; await SimpleCache.getOrSet(Math.random(), async () => { called = true; return { value: 'meow', ttl: 10, }; }); assert(called, true, 'called === true'); } }, ); routes.set( '/simple-cache/getOrSet/does-not-execute-the-set-method-when-key-is-in-cache', async () => { if (!isRunningLocally()) { let key = Math.random(); SimpleCache.set(key, 'meow', 100); let called = false; await SimpleCache.getOrSet(key, async () => { called = true; return { value: 'meow', ttl: 10, }; }); assert(called, false, 'called === false'); } }, ); routes.set( '/simple-cache/getOrSet/does-not-freeze-when-called-after-a-get', async () => { if (!isRunningLocally()) { let key = String(Math.random()); SimpleCache.get(key); await SimpleCache.getOrSet(key, async () => { return { value: key, ttl: 10, }; }); } }, ); } ================================================ FILE: integration-tests/js-compute/fixtures/app/src/client.js ================================================ import { strictEqual } from './assertions.js'; import { routes, isRunningLocally } from './routes.js'; routes.set('/client/requestId', (event) => { strictEqual( typeof event.client.requestId, 'string', 'typeof event.client.requestId', ); strictEqual( event.client.requestId.length, 32, 'event.client.requestId.length', ); }); routes.set('/client/tlsJA3MD5', (event) => { if (isRunningLocally()) { strictEqual(event.client.tlsJA3MD5, null); } else { strictEqual( typeof event.client.tlsJA3MD5, 'string', 'typeof event.client.tlsJA3MD5', ); strictEqual( event.client.tlsJA3MD5.length, 32, 'event.client.tlsJA3MD5.length', ); } }); routes.set('/client/tlsClientHello', (event) => { if (isRunningLocally()) { strictEqual(event.client.tlsClientHello, null); } else { strictEqual( event.client.tlsClientHello instanceof ArrayBuffer, true, 'event.client.tlsClientHello instanceof ArrayBuffer', ); strictEqual( typeof event.client.tlsClientHello.byteLength, 'number', 'typeof event.client.tlsClientHello.byteLength', ); } }); routes.set('/client/tlsClientCertificate', (event) => { if (isRunningLocally()) { strictEqual(event.client.tlsClientCertificate, null); } else { strictEqual( event.client.tlsClientCertificate instanceof ArrayBuffer, true, 'event.client.tlsClientCertificate instanceof ArrayBuffer', ); strictEqual( event.client.tlsClientCertificate.byteLength, 0, 'event.client.tlsClientCertificate.byteLength', ); } }); routes.set('/client/tlsCipherOpensslName', (event) => { if (isRunningLocally()) { strictEqual(event.client.tlsCipherOpensslName, null); } else { strictEqual( typeof event.client.tlsCipherOpensslName, 'string', 'typeof event.client.tlsCipherOpensslName', ); } }); routes.set('/client/tlsProtocol', (event) => { if (isRunningLocally()) { strictEqual(event.client.tlsProtocol, null); } else { strictEqual( typeof event.client.tlsProtocol, 'string', 'typeof event.client.tlsProtocol', ); } }); routes.set('/client/tlsJA4', (event) => { if (isRunningLocally()) { strictEqual(event.client.tlsJA4, null); } else { strictEqual( typeof event.client.tlsJA4, 'string', 'typeof event.client.tlsJA4', ); } }); routes.set('/client/h2Fingerprint', (event) => { if (isRunningLocally()) { strictEqual(event.client.h2Fingerprint, null); } else { // h2Fingerprint may be null for HTTP/1.1 connections const fp = event.client.h2Fingerprint; strictEqual( fp === null || typeof fp === 'string', true, 'event.client.h2Fingerprint is null or string', ); } }); routes.set('/client/ohFingerprint', (event) => { if (isRunningLocally()) { strictEqual(event.client.ohFingerprint, null); } else { strictEqual( typeof event.client.ohFingerprint, 'string', 'typeof event.client.ohFingerprint', ); } }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/compute.js ================================================ import { pass, ok, strictEqual, assertThrows } from './assertions.js'; import { routes } from './routes.js'; import { purgeSurrogateKey, vCpuTime } from 'fastly:compute'; routes.set('/compute/get-vcpu-ms', () => { const cpuTime = vCpuTime(); strictEqual(typeof cpuTime, 'number'); // We can't assert > 0; this only claims millisecond resolution, // and we hopefully spent less than 500us starting. ok(cpuTime >= 0, 'cpuTime >= 0'); ok(cpuTime < 3000, 'cputime < 3000'); const arr = new Array(100_000).fill(1); for (let j = 1; j < 100; j++) { for (let i = 1; i < 100_000; i++) { arr[i] = (arr[i] + arr[i - 1] + i) / 3; } } const cpuTime2 = vCpuTime(); ok(cpuTime2 > cpuTime, 'cpuTime2 > cpuTime'); ok(cpuTime2 - cpuTime > 1, 'cpuTime2 - cpuTime > 1'); return pass('ok'); }); routes.set('/compute/purge-surrogate-key-invalid', () => { assertThrows( () => { purgeSurrogateKey(); }, TypeError, 'purgeSurrogateKey: At least 1 argument required, but only 0 passed', ); return pass('ok'); }); routes.set('/compute/purge-surrogate-key-hard', () => { purgeSurrogateKey('test'); return pass('ok'); }); routes.set('/compute/purge-surrogate-key-soft', () => { purgeSurrogateKey('test', true); return pass('ok'); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/config-store.js ================================================ /// /* eslint-env serviceworker */ import { assert } from './assertions.js'; import { ConfigStore } from 'fastly:config-store'; import { routes } from './routes.js'; import { env } from 'fastly:env'; const CONFIG_STORE_NAME = env('CONFIG_STORE_NAME'); routes.set('/config-store', () => { let config = new ConfigStore(CONFIG_STORE_NAME); let twitterValue = config.get('twitter'); assert( twitterValue, 'https://twitter.com/fastly', `config.get("twitter") === "https://twitter.com/fastly"`, ); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/crypto.js ================================================ /// /* eslint-env serviceworker, shared-node-browser, browser */ import { assert, assertThrows, assertRejects, assertResolves, } from './assertions.js'; import { routes } from './routes.js'; // From https://www.rfc-editor.org/rfc/rfc7517#appendix-A.1 const publicRsaJsonWebKeyData = { alg: 'RS256', e: 'AQAB', ext: true, key_ops: ['verify'], kty: 'RSA', n: '0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw', }; // From https://www.rfc-editor.org/rfc/rfc7517#appendix-A.1 const publicEcdsaJsonWebKeyData = { kty: 'EC', crv: 'P-256', x: 'MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4', y: '4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM', kid: '1', ext: true, key_ops: ['verify'], }; // From https://www.rfc-editor.org/rfc/rfc7517#appendix-A.2 const privateEcdsaJsonWebKeyData = { kty: 'EC', crv: 'P-256', x: 'MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4', y: '4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM', d: '870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE', use: 'sig', kid: '1', ext: true, key_ops: ['sign'], }; // From https://www.rfc-editor.org/rfc/rfc7517#appendix-A.2 const privateRsaJsonWebKeyData = { alg: 'RS256', d: 'X4cTteJY_gn4FYPsXB8rdXix5vwsg1FLN5E3EaG6RJoVH-HLLKD9M7dx5oo7GURknchnrRweUkC7hT5fJLM0WbFAKNLWY2vv7B6NqXSzUvxT0_YSfqijwp3RTzlBaCxWp4doFk5N2o8Gy_nHNKroADIkJ46pRUohsXywbReAdYaMwFs9tv8d_cPVY3i07a3t8MN6TNwm0dSawm9v47UiCl3Sk5ZiG7xojPLu4sbg1U2jx4IBTNBznbJSzFHK66jT8bgkuqsk0GjskDJk19Z4qwjwbsnn4j2WBii3RL-Us2lGVkY8fkFzme1z0HbIkfz0Y6mqnOYtqc0X4jfcKoAC8Q', dp: 'G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0', dq: 's9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk', e: 'AQAB', ext: true, key_ops: ['sign'], kty: 'RSA', n: '0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw', p: '83i-7IvMGXoMXCskv73TKr8637FiO7Z27zv8oj6pbWUQyLPQBQxtPVnwD20R-60eTDmD2ujnMt5PoqMrm8RfmNhVWDtjjMmCMjOpSXicFHj7XOuVIYQyqVWlWEh6dN36GVZYk93N8Bc9vY41xy8B9RzzOGVQzXvNEvn7O0nVbfs', q: '3dfOR9cuYq-0S-mkFLzgItgMEfFzB2q3hWehMuG0oCuqnb3vobLyumqjVZQO1dIrdwgTnCdpYzBcOfW5r370AFXjiWft_NGEiovonizhKpo9VVS78TzFgxkIdrecRezsZ-1kYd_s1qDbxtkDEgfAITAG9LUnADun4vIcb6yelxk', qi: 'GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU', }; // Helper functions to create fresh copies of test data for tests that mutate them function freshPublicRsaKey() { return structuredClone(publicRsaJsonWebKeyData); } function freshPublicEcdsaKey() { return structuredClone(publicEcdsaJsonWebKeyData); } function freshPrivateEcdsaKey() { return structuredClone(privateEcdsaJsonWebKeyData); } function freshPrivateRsaKey() { return structuredClone(privateRsaJsonWebKeyData); } const rsaJsonWebKeyAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' }, }; const ecdsaJsonWebKeyAlgorithm = { name: 'ECDSA', namedCurve: 'P-256', hash: { name: 'SHA-256' }, }; routes.set('/crypto', async () => { assert(typeof crypto, 'object', `typeof crypto`); assert(crypto instanceof Crypto, true, `crypto instanceof Crypto`); }); routes.set('/crypto.subtle', async () => { assert(typeof crypto.subtle, 'object', `typeof crypto.subtle`); assert( crypto.subtle instanceof SubtleCrypto, true, `crypto.subtle instanceof SubtleCrypto`, ); }); // importKey { routes.set('/crypto.subtle.importKey', async () => { assert( typeof crypto.subtle.importKey, 'function', `typeof crypto.subtle.importKey`, ); assert( crypto.subtle.importKey, SubtleCrypto.prototype.importKey, `crypto.subtle.importKey === SubtleCrypto.prototype.importKey`, ); }); routes.set('/crypto.subtle.importKey/length', async () => { assert( crypto.subtle.importKey.length, 5, `crypto.subtle.importKey.length === 5`, ); }); routes.set('/crypto.subtle.importKey/called-as-constructor', async () => { assertThrows( () => { new crypto.subtle.importKey(); }, TypeError, 'crypto.subtle.importKey is not a constructor', ); }); routes.set('/crypto.subtle.importKey/called-with-wrong-this', async () => { await assertRejects(async () => { await crypto.subtle.importKey.call( undefined, 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); }, TypeError); }); routes.set('/crypto.subtle.importKey/called-with-no-arguments', async () => { await assertRejects( async () => { await crypto.subtle.importKey(); }, TypeError, 'SubtleCrypto.importKey: At least 5 arguments required, but only 0 passed', ); }); // first-parameter { routes.set( '/crypto.subtle.importKey/first-parameter-calls-7.1.17-ToString', async () => { const sentinel = Symbol('sentinel'); const test = async () => { const format = { toString() { throw sentinel; }, }; await crypto.subtle.importKey( format, publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.importKey/first-parameter-non-existant-format', async () => { await assertRejects(async () => { await crypto.subtle.importKey( 'jake', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); }, Error); }, ); } // second-parameter { routes.set( '/crypto.subtle.importKey/second-parameter-invalid-format', async () => { await assertRejects(async () => { await crypto.subtle.importKey( 'jwk', Symbol(), rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); }, Error); }, ); // jwk public key { routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-missing-e-field', async () => { await assertRejects(async () => { const testData = structuredClone(publicRsaJsonWebKeyData); delete testData.e; await crypto.subtle.importKey( 'jwk', testData, rsaJsonWebKeyAlgorithm, testData.ext, testData.key_ops, ); }, DOMException); }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-e-field-calls-7.1.17-ToString', async () => { let sentinel = Symbol('sentinel'); const test = async () => { sentinel = Symbol(); let webKeyData = structuredClone(publicRsaJsonWebKeyData); webKeyData.e = { toString() { throw sentinel; }, }; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-invalid-e-field', async () => { await assertRejects( async () => { let webKeyData = structuredClone(publicRsaJsonWebKeyData); webKeyData.e = '`~!@#@#$Q%^%&^*'; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }, Error, "The JWK member 'e' could not be base64url decoded or contained padding", ); }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-missing-kty-field', async () => { await assertRejects(async () => { let webKeyData = structuredClone(publicRsaJsonWebKeyData); delete webKeyData.kty; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-invalid-kty-field', async () => { await assertRejects(async () => { let webKeyData = structuredClone(publicRsaJsonWebKeyData); webKeyData.kty = 'jake'; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-missing-key_ops-field', async () => { await assertResolves(async () => { let webKeyData = structuredClone(publicRsaJsonWebKeyData); const key_ops = Array.from(webKeyData.key_ops); delete webKeyData.key_ops; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, key_ops, ); }); }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-non-sequence-key_ops-field', async () => { await assertRejects(async () => { let webKeyData = structuredClone(publicRsaJsonWebKeyData); const key_ops = Array.from(webKeyData.key_ops); webKeyData.key_ops = 'jake'; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-empty-key_ops-field', async () => { await assertResolves(async () => { let webKeyData = structuredClone(publicRsaJsonWebKeyData); const key_ops = Array.from(webKeyData.key_ops); webKeyData.key_ops = []; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, key_ops, ); }); }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-duplicated-key_ops-field', async () => { await assertRejects(async () => { let webKeyData = structuredClone(publicRsaJsonWebKeyData); const key_ops = Array.from(webKeyData.key_ops); webKeyData.key_ops = ['sign', 'sign']; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-invalid-key_ops-field', async () => { await assertRejects(async () => { let webKeyData = structuredClone(publicRsaJsonWebKeyData); const key_ops = Array.from(webKeyData.key_ops); webKeyData.key_ops = ['sign', 'jake']; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-key_ops-field-calls-7.1.17-ToString', async () => { let sentinel = Symbol('sentinel'); const key_ops = Array.from(publicRsaJsonWebKeyData.key_ops); const test = async () => { sentinel = Symbol(); const op = { toString() { throw sentinel; }, }; let webKeyData = structuredClone(publicRsaJsonWebKeyData); const key_ops = Array.from(webKeyData.key_ops); webKeyData.key_ops = ['sign', op]; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, key_ops, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-missing-n-field', async () => { await assertRejects( async () => { const testData = structuredClone(publicRsaJsonWebKeyData); delete testData.n; await crypto.subtle.importKey( 'jwk', testData, rsaJsonWebKeyAlgorithm, testData.ext, testData.key_ops, ); }, Error, 'Data provided to an operation does not meet requirements', ); }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-n-field-calls-7.1.17-ToString', async () => { let sentinel = Symbol('sentinel'); const test = async () => { sentinel = Symbol(); let webKeyData = structuredClone(publicRsaJsonWebKeyData); webKeyData.n = { toString() { throw sentinel; }, }; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.importKey/rsa-jwk-public/second-parameter-invalid-n-field', async () => { await assertRejects( async () => { let webKeyData = structuredClone(publicRsaJsonWebKeyData); webKeyData.n = '`~!@#@#$Q%^%&^*'; await crypto.subtle.importKey( 'jwk', webKeyData, rsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }, Error, "The JWK member 'n' could not be base64url decoded or contained padding", ); }, ); } // jwk private key // TODO // raw HMAC secret keys // TODO // raw Elliptic Curve public keys { routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-missing-x-field', async () => { await assertRejects( async () => { let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); delete webKeyData.x; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }, DOMException, 'Data provided to an operation does not meet requirements', ); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-x-field-calls-7.1.17-ToString', async () => { let sentinel = Symbol('sentinel'); const test = async () => { sentinel = Symbol(); let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); webKeyData.x = { toString() { throw sentinel; }, }; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-invalid-x-field', async () => { await assertRejects( async () => { let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); webKeyData.x = '`~!@#@#$Q%^%&^*'; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }, Error, "The JWK member 'x' could not be base64url decoded or contained padding", ); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-missing-y-field', async () => { await assertRejects( async () => { let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); delete webKeyData.y; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }, DOMException, 'Data provided to an operation does not meet requirements', ); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-y-field-calls-7.1.17-ToString', async () => { let sentinel = Symbol('sentinel'); const test = async () => { sentinel = Symbol(); let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); webKeyData.y = { toString() { throw sentinel; }, }; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-invalid-y-field', async () => { await assertRejects( async () => { let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); webKeyData.y = '`~!@#@#$Q%^%&^*'; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }, Error, "The JWK member 'y' could not be base64url decoded or contained padding", ); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-missing-kty-field', async () => { await assertRejects(async () => { let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); delete webKeyData.kty; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-invalid-kty-field', async () => { await assertRejects(async () => { let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); webKeyData.kty = 'jake'; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, webKeyData.key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-missing-key_ops-field', async () => { await assertResolves(async () => { let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); const key_ops = Array.from(webKeyData.key_ops); delete webKeyData.key_ops; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, key_ops, ); }); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-non-sequence-key_ops-field', async () => { await assertRejects(async () => { let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); const key_ops = Array.from(webKeyData.key_ops); webKeyData.key_ops = 'jake'; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-empty-key_ops-field', async () => { await assertResolves(async () => { let webKeyData = structuredClone(publicEcdsaJsonWebKeyData); const key_ops = Array.from(webKeyData.key_ops); webKeyData.key_ops = []; await crypto.subtle.importKey( 'jwk', webKeyData, ecdsaJsonWebKeyAlgorithm, webKeyData.ext, key_ops, ); }); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-duplicated-key_ops-field', async () => { await assertRejects(async () => { const testData = structuredClone(publicEcdsaJsonWebKeyData); const key_ops = Array.from(testData.key_ops); testData.key_ops = ['sign', 'sign']; await crypto.subtle.importKey( 'jwk', testData, ecdsaJsonWebKeyAlgorithm, testData.ext, key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-invalid-key_ops-field', async () => { await assertRejects(async () => { const testData = structuredClone(publicEcdsaJsonWebKeyData); const key_ops = Array.from(testData.key_ops); testData.key_ops = ['sign', 'jake']; await crypto.subtle.importKey( 'jwk', testData, ecdsaJsonWebKeyAlgorithm, testData.ext, key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-public/second-parameter-key_ops-field-calls-7.1.17-ToString', async () => { let sentinel = Symbol('sentinel'); const test = async () => { sentinel = Symbol(); const testData = structuredClone(publicEcdsaJsonWebKeyData); const key_ops = Array.from(testData.key_ops); const op = { toString() { throw sentinel; }, }; testData.key_ops = ['sign', op]; await crypto.subtle.importKey( 'jwk', testData, ecdsaJsonWebKeyAlgorithm, testData.ext, key_ops, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-private/second-parameter-d-field-calls-7.1.17-ToString', async () => { let sentinel = Symbol('sentinel'); const test = async () => { sentinel = Symbol(); const testData = structuredClone(privateEcdsaJsonWebKeyData); testData.d = { toString() { throw sentinel; }, }; await crypto.subtle.importKey( 'jwk', testData, ecdsaJsonWebKeyAlgorithm, testData.ext, testData.key_ops, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { console.log( thrownError, typeof thrownError, Object.keys(thrownError), ); assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.importKey/ecdsa-jwk-private/second-parameter-invalid-d-field', async () => { await assertRejects( async () => { const testData = structuredClone(privateEcdsaJsonWebKeyData); testData.d = '`~!@#@#$Q%^%&^*'; await crypto.subtle.importKey( 'jwk', testData, ecdsaJsonWebKeyAlgorithm, testData.ext, testData.key_ops, ); }, Error, "The JWK member 'd' could not be base64url decoded or contained padding", ); }, ); } // pkcs8 Elliptic Curve private keys // TODO // pkcs8 RSA private keys // raw AES } // third-parameter { routes.set( '/crypto.subtle.importKey/third-parameter-undefined', async () => { await assertRejects( async () => { await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, undefined, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); }, Error, 'Algorithm: Unrecognized name', ); }, ); routes.set( '/crypto.subtle.importKey/third-parameter-name-field-calls-7.1.17-ToString', async () => { const sentinel = Symbol('sentinel'); const test = async () => { let algorithm = structuredClone(rsaJsonWebKeyAlgorithm); algorithm.name = { toString() { throw sentinel; }, }; await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, algorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.importKey/third-parameter-invalid-name-field', async () => { await assertRejects(async () => { let algorithm = structuredClone(rsaJsonWebKeyAlgorithm); algorithm.name = '`~!@#@#$Q%^%&^*'; await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, algorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); }, Error); }, ); routes.set( '/crypto.subtle.importKey/third-parameter-hash-name-field-calls-7.1.17-ToString', async () => { const sentinel = Symbol('sentinel'); const test = async () => { let algorithm = structuredClone(rsaJsonWebKeyAlgorithm); algorithm.hash.name = { toString() { throw sentinel; }, }; await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, algorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.importKey/third-parameter-hash-algorithm-does-not-match-json-web-key-hash-algorithm', async () => { await assertRejects( async () => { let algorithm = structuredClone(rsaJsonWebKeyAlgorithm); algorithm.hash.name = 'SHA-1'; await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, algorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); }, Error, "The JWK 'alg' member was inconsistent with that specified by the Web Crypto call", ); }, ); } // fifth-parameter { routes.set( '/crypto.subtle.importKey/fifth-parameter-undefined', async () => { await assertRejects(async () => { await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, undefined, ); }, Error); }, ); routes.set('/crypto.subtle.importKey/fifth-parameter-invalid', async () => { await assertRejects(async () => { await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, ['jake'], ); }, Error); }); routes.set( '/crypto.subtle.importKey/fifth-parameter-duplicate-operations', async () => { await assertResolves(async () => { const key_ops = publicRsaJsonWebKeyData.key_ops.concat( publicRsaJsonWebKeyData.key_ops, ); await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, key_ops, ); }); }, ); routes.set( '/crypto.subtle.importKey/fifth-parameter-operations-do-not-match-json-web-key-operations', async () => { await assertRejects( async () => { await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, ['sign'], ); }, Error, "The JWK 'key_ops' member was inconsistent with that specified by the Web Crypto call. The JWK usage must be a superset of those requested", ); }, ); routes.set( '/crypto.subtle.importKey/fifth-parameter-operation-fields-calls-7.1.17-ToString', async () => { let sentinel = Symbol('sentinel'); const test = async () => { sentinel = Symbol(); const op = { toString() { throw sentinel; }, }; await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, ['sign', op], ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); } // happy paths { routes.set('/crypto.subtle.importKey/JWK-RS256-Public', async () => { const key = await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); await assert(key instanceof CryptoKey, true, `key instanceof CryptoKey`); await assert( key.algorithm, { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256', }, modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), }, `key.algorithm`, ); await assert(key.extractable, true, `key.extractable === true`); await assert(key.type, 'public', `key.type === "public"`); await assert(key.usages, ['verify'], `key.usages deep equals ["verify"]`); }); routes.set('/crypto.subtle.importKey/JWK-EC256-Public', async () => { const key = await crypto.subtle.importKey( 'jwk', publicEcdsaJsonWebKeyData, ecdsaJsonWebKeyAlgorithm, publicEcdsaJsonWebKeyData.ext, publicEcdsaJsonWebKeyData.key_ops, ); await assert(key instanceof CryptoKey, true, `key instanceof CryptoKey`); await assert( key.algorithm, { name: 'ECDSA', namedCurve: 'P-256', }, `key.algorithm`, ); await assert(key.extractable, true, `key.extractable === true`); await assert(key.type, 'public', `key.type === "public"`); await assert(key.usages, ['verify'], `key.usages deep equals ["verify"]`); }); routes.set('/crypto.subtle.importKey/HMAC', async () => { const keyUint8Array = new Uint8Array([1, 0, 1]); for (const algorithm of ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512']) { const key = await globalThis.crypto.subtle.importKey( 'raw', keyUint8Array, { name: 'HMAC', hash: algorithm }, false, ['sign', 'verify'], ); await assert( key instanceof CryptoKey, true, `key instanceof CryptoKey`, ); await assert( key.algorithm, { name: 'HMAC', hash: { name: algorithm }, length: 24, }, `key.algorithm`, ); await assert(key.extractable, false, `key.extractable`); await assert(key.type, 'secret', `key.type`); await assert(key.usages, ['sign', 'verify'], `key.usages`); } }); routes.set('/crypto.subtle.importKey/JWK-HS256-Public', async () => { const key = await crypto.subtle.importKey( 'jwk', { kty: 'oct', k: 'Y0zt37HgOx-BY7SQjYVmrqhPkO44Ii2Jcb9yydUDPfE', alg: 'HS256', ext: true, }, { name: 'HMAC', hash: { name: 'SHA-256' }, }, false, ['sign', 'verify'], ); await assert(key instanceof CryptoKey, true, `key instanceof CryptoKey`); await assert( key.algorithm, { name: 'HMAC', hash: { name: 'SHA-256' }, length: 256, }, `key.algorithm`, ); await assert(key.extractable, false, `key.extractable`); await assert(key.type, 'secret', `key.type`); await assert(key.usages, ['sign', 'verify'], `key.usages`); }); } } // digest { const enc = new TextEncoder(); const data = enc.encode('hello world'); routes.set('/crypto.subtle.digest', async () => { assert( typeof crypto.subtle.digest, 'function', `typeof crypto.subtle.digest`, ); assert( crypto.subtle.digest, SubtleCrypto.prototype.digest, `crypto.subtle.digest === SubtleCrypto.prototype.digest`, ); }); routes.set('/crypto.subtle.digest/length', async () => { assert(crypto.subtle.digest.length, 2, `crypto.subtle.digest.length === 2`); }); routes.set('/crypto.subtle.digest/called-as-constructor', async () => { assertThrows( () => { new crypto.subtle.digest(); }, TypeError, 'crypto.subtle.digest is not a constructor', ); }); routes.set('/crypto.subtle.digest/called-with-wrong-this', async () => { await assertRejects(async () => { await crypto.subtle.digest.call(undefined); }, TypeError); }); routes.set('/crypto.subtle.digest/called-with-no-arguments', async () => { await assertRejects( async () => { await crypto.subtle.digest(); }, TypeError, 'SubtleCrypto.digest: At least 2 arguments required, but only 0 passed', ); }); // first-parameter { routes.set( '/crypto.subtle.digest/first-parameter-calls-7.1.17-ToString', async () => { const sentinel = Symbol('sentinel'); const test = async () => { await crypto.subtle.digest( { name: { toString() { throw sentinel; }, }, }, data, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.digest/first-parameter-non-existant-format', async () => { await assertRejects( async () => { await crypto.subtle.digest('jake', data); }, Error, 'Algorithm: Unrecognized name', ); }, ); } // second-parameter { routes.set('/crypto.subtle.digest/second-parameter-undefined', async () => { await assertRejects(async () => { await crypto.subtle.digest('sha-1', undefined); }, Error); }); } // happy paths { // "MD5" routes.set('/crypto.subtle.digest/md5', async () => { const result = new Uint8Array( await crypto.subtle.digest('md5', new Uint8Array()), ); const expected = new Uint8Array([ 212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126, ]); assert(result, expected, 'result deep equals expected'); }); // "SHA-1" routes.set('/crypto.subtle.digest/sha-1', async () => { const result = new Uint8Array( await crypto.subtle.digest('sha-1', new Uint8Array()), ); const expected = new Uint8Array([ 218, 57, 163, 238, 94, 107, 75, 13, 50, 85, 191, 239, 149, 96, 24, 144, 175, 216, 7, 9, ]); assert(result, expected, 'result deep equals expected'); }); // "SHA-256" routes.set('/crypto.subtle.digest/sha-256', async () => { const result = new Uint8Array( await crypto.subtle.digest('sha-256', new Uint8Array()), ); const expected = new Uint8Array([ 227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85, ]); assert(result, expected, 'result deep equals expected'); }); // "SHA-384" routes.set('/crypto.subtle.digest/sha-384', async () => { const result = new Uint8Array( await crypto.subtle.digest('sha-384', new Uint8Array()), ); const expected = new Uint8Array([ 56, 176, 96, 167, 81, 172, 150, 56, 76, 217, 50, 126, 177, 177, 227, 106, 33, 253, 183, 17, 20, 190, 7, 67, 76, 12, 199, 191, 99, 246, 225, 218, 39, 78, 222, 191, 231, 111, 101, 251, 213, 26, 210, 241, 72, 152, 185, 91, ]); assert(result, expected, 'result deep equals expected'); }); // "SHA-512" routes.set('/crypto.subtle.digest/sha-512', async () => { const result = new Uint8Array( await crypto.subtle.digest('sha-512', new Uint8Array()), ); const expected = new Uint8Array([ 207, 131, 225, 53, 126, 239, 184, 189, 241, 84, 40, 80, 214, 109, 128, 7, 214, 32, 228, 5, 11, 87, 21, 220, 131, 244, 169, 33, 211, 108, 233, 206, 71, 208, 209, 60, 93, 133, 242, 176, 255, 131, 24, 210, 135, 126, 236, 47, 99, 185, 49, 189, 71, 65, 122, 129, 165, 56, 50, 122, 249, 39, 218, 62, ]); assert(result, expected, 'result deep equals expected'); }); } } // sign { const enc = new TextEncoder(); const data = enc.encode('hello world'); routes.set('/crypto.subtle.sign', async () => { assert(typeof crypto.subtle.sign, 'function', `typeof crypto.subtle.sign`); assert( crypto.subtle.sign, SubtleCrypto.prototype.sign, `crypto.subtle.sign === SubtleCrypto.prototype.sign`, ); }); routes.set('/crypto.subtle.sign/length', async () => { assert(crypto.subtle.sign.length, 3, `crypto.subtle.sign.length === 3`); }); routes.set('/crypto.subtle.sign/called-as-constructor', async () => { assertThrows( () => { new crypto.subtle.sign(); }, TypeError, 'crypto.subtle.sign is not a constructor', ); }); routes.set('/crypto.subtle.sign/called-with-wrong-this', async () => { await assertRejects(async () => { await crypto.subtle.sign.call( undefined, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData, data, ); }, TypeError); }); routes.set('/crypto.subtle.sign/called-with-no-arguments', async () => { await assertRejects( async () => { await crypto.subtle.sign(); }, TypeError, 'SubtleCrypto.sign: At least 3 arguments required, but only 0 passed', ); }); // first-parameter { routes.set( '/crypto.subtle.sign/first-parameter-calls-7.1.17-ToString', async () => { const sentinel = Symbol('sentinel'); const key = await crypto.subtle.importKey( 'jwk', privateRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, privateRsaJsonWebKeyData.ext, privateRsaJsonWebKeyData.key_ops, ); const test = async () => { await crypto.subtle.sign( { name: { toString() { throw sentinel; }, }, }, key, data, ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.sign/first-parameter-non-existant-algorithm', async () => { await assertRejects( async () => { const key = await crypto.subtle.importKey( 'jwk', privateRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, privateRsaJsonWebKeyData.ext, privateRsaJsonWebKeyData.key_ops, ); await crypto.subtle.sign('jake', key, data); }, Error, 'Algorithm: Unrecognized name', ); }, ); } // second-parameter { routes.set( '/crypto.subtle.sign/second-parameter-invalid-format', async () => { await assertRejects(async () => { await crypto.subtle.sign(rsaJsonWebKeyAlgorithm, 'jake', data); }, Error); }, ); routes.set( '/crypto.subtle.sign/second-parameter-invalid-usages', async () => { await assertRejects( async () => { const key = await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); await crypto.subtle.sign(rsaJsonWebKeyAlgorithm, key, data); }, Error, "CryptoKey doesn't support signing", ); }, ); } // third-parameter { routes.set( '/crypto.subtle.sign/third-parameter-invalid-format', async () => { await assertRejects(async () => { const key = await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); await crypto.subtle.sign(rsaJsonWebKeyAlgorithm, key, undefined); }, Error); }, ); } // happy-path { routes.set('/crypto.subtle.sign/happy-path-jwk', async () => { const key = await crypto.subtle.importKey( 'jwk', privateRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, privateRsaJsonWebKeyData.ext, privateRsaJsonWebKeyData.key_ops, ); const signature = new Uint8Array( await crypto.subtle.sign(rsaJsonWebKeyAlgorithm, key, data), ); const expected = new Uint8Array([ 70, 96, 33, 185, 93, 42, 67, 49, 243, 70, 88, 68, 194, 148, 53, 249, 255, 192, 232, 132, 161, 194, 41, 244, 174, 211, 218, 203, 7, 238, 71, 182, 101, 49, 139, 222, 165, 70, 222, 105, 82, 156, 184, 44, 100, 108, 121, 237, 250, 119, 66, 228, 156, 243, 71, 105, 62, 246, 22, 2, 160, 116, 71, 147, 202, 168, 24, 92, 224, 41, 148, 161, 124, 80, 212, 169, 212, 64, 29, 189, 2, 171, 174, 188, 159, 89, 93, 122, 219, 166, 105, 92, 107, 173, 103, 238, 145, 226, 94, 139, 71, 124, 17, 233, 49, 138, 89, 246, 3, 82, 238, 154, 169, 188, 66, 198, 32, 23, 230, 90, 164, 140, 51, 47, 221, 149, 161, 14, 254, 169, 224, 223, 119, 94, 27, 63, 199, 93, 65, 53, 24, 151, 146, 242, 239, 41, 108, 136, 31, 99, 42, 213, 128, 244, 140, 238, 157, 107, 117, 241, 219, 137, 97, 39, 109, 185, 176, 97, 193, 60, 117, 244, 106, 62, 193, 188, 87, 199, 37, 70, 137, 37, 231, 110, 228, 228, 139, 53, 240, 56, 92, 102, 220, 176, 127, 248, 24, 217, 208, 29, 209, 216, 29, 251, 100, 252, 243, 183, 195, 96, 126, 102, 136, 48, 39, 186, 45, 202, 10, 187, 22, 52, 183, 190, 149, 153, 32, 12, 90, 66, 49, 122, 190, 154, 167, 9, 12, 32, 77, 177, 222, 54, 211, 233, 219, 205, 133, 0, 113, 77, 158, 1, 125, 5, 15, 195, ]); assert(signature, expected, 'signature deep equals expected'); }); routes.set('/crypto.subtle.sign/happy-path-hmac', async () => { const encoder = new TextEncoder(); const messageUint8Array = encoder.encode('aki'); const keyUint8Array = new Uint8Array([1, 0, 1]); const results = { 'SHA-1': new Uint8Array([ 222, 61, 81, 133, 232, 89, 130, 225, 248, 25, 220, 34, 245, 103, 89, 127, 136, 77, 146, 166, ]), 'SHA-256': new Uint8Array([ 92, 237, 16, 210, 91, 89, 194, 36, 95, 98, 27, 175, 64, 25, 15, 160, 152, 178, 145, 235, 62, 92, 23, 202, 125, 228, 8, 25, 148, 26, 215, 242, ]), 'SHA-384': new Uint8Array([ 238, 20, 74, 173, 238, 236, 161, 229, 250, 167, 72, 210, 188, 239, 233, 39, 233, 166, 114, 241, 140, 229, 201, 129, 243, 173, 74, 198, 223, 145, 228, 96, 253, 91, 166, 111, 244, 23, 141, 62, 112, 156, 90, 166, 214, 69, 185, 48, ]), 'SHA-512': new Uint8Array([ 211, 127, 139, 149, 23, 225, 84, 230, 82, 249, 109, 254, 168, 236, 217, 112, 174, 52, 231, 62, 167, 197, 33, 11, 181, 21, 162, 236, 214, 132, 43, 161, 92, 112, 230, 182, 140, 69, 169, 229, 87, 98, 57, 81, 140, 134, 219, 253, 139, 169, 85, 181, 195, 195, 166, 241, 219, 33, 9, 56, 67, 213, 51, 224, ]), }; for (const algorithm of ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512']) { const key = await globalThis.crypto.subtle.importKey( 'raw', keyUint8Array, { name: 'HMAC', hash: algorithm }, false, ['sign', 'verify'], ); // Sign the message with HMAC and the CryptoKey const signature = new Uint8Array( await globalThis.crypto.subtle.sign('HMAC', key, messageUint8Array), ); const expected = results[algorithm]; assert( signature, expected, `${algorithm} signature deep equals expected`, ); } }); } } // verify { routes.set('/crypto.subtle.verify', async () => { assert( typeof crypto.subtle.verify, 'function', `typeof crypto.subtle.verify`, ); assert( crypto.subtle.verify, SubtleCrypto.prototype.verify, `crypto.subtle.verify === SubtleCrypto.prototype.verify`, ); }); routes.set('/crypto.subtle.verify/length', async () => { assert(crypto.subtle.verify.length, 4, `crypto.subtle.verify.length === 4`); }); routes.set('/crypto.subtle.verify/called-as-constructor', async () => { assertThrows( () => { new crypto.subtle.verify(); }, TypeError, 'crypto.subtle.verify is not a constructor', ); }); routes.set('/crypto.subtle.verify/called-with-wrong-this', async () => { await assertRejects(async () => { const key = await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); await crypto.subtle.verify.call( undefined, rsaJsonWebKeyAlgorithm, key, new Uint8Array(), new Uint8Array(), ); }, TypeError); }); routes.set('/crypto.subtle.verify/called-with-no-arguments', async () => { await assertRejects( async () => { await crypto.subtle.verify(); }, TypeError, 'SubtleCrypto.verify: At least 4 arguments required, but only 0 passed', ); }); // first-parameter { routes.set( '/crypto.subtle.verify/first-parameter-calls-7.1.17-ToString', async () => { const sentinel = Symbol('sentinel'); const test = async () => { const key = await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); await crypto.subtle.verify( { name: { toString() { throw sentinel; }, }, }, key, new Uint8Array(), new Uint8Array(), ); }; await assertRejects(test); try { await test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } }, ); routes.set( '/crypto.subtle.verify/first-parameter-non-existant-algorithm', async () => { await assertRejects( async () => { const key = await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); await crypto.subtle.verify( 'jake', key, new Uint8Array(), new Uint8Array(), ); }, Error, 'Algorithm: Unrecognized name', ); }, ); } // second-parameter { routes.set( '/crypto.subtle.verify/second-parameter-invalid-format', async () => { await assertRejects(async () => { await crypto.subtle.verify( rsaJsonWebKeyAlgorithm, 'jake', new Uint8Array(), new Uint8Array(), ); }, Error); }, ); routes.set( '/crypto.subtle.verify/second-parameter-invalid-usages', async () => { await assertRejects( async () => { const key = await crypto.subtle.importKey( 'jwk', privateRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, privateRsaJsonWebKeyData.ext, privateRsaJsonWebKeyData.key_ops, ); await crypto.subtle.verify( rsaJsonWebKeyAlgorithm, key, new Uint8Array(), new Uint8Array(), ); }, Error, "CryptoKey doesn't support verification", ); }, ); } // third-parameter { routes.set( '/crypto.subtle.verify/third-parameter-invalid-format', async () => { await assertRejects(async () => { const key = await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); await crypto.subtle.verify( rsaJsonWebKeyAlgorithm, key, undefined, new Uint8Array(), ); }, Error); }, ); } // fourth-parameter { routes.set( '/crypto.subtle.verify/fourth-parameter-invalid-format', async () => { await assertRejects(async () => { const key = await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); await crypto.subtle.verify( rsaJsonWebKeyAlgorithm, key, new Uint8Array(), undefined, ); }, Error); }, ); } // incorrect-signature { routes.set('/crypto.subtle.verify/incorrect-signature-jwk', async () => { const key = await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); const signature = new Uint8Array(); const enc = new TextEncoder(); const data = enc.encode('hello world'); const result = await crypto.subtle.verify( rsaJsonWebKeyAlgorithm, key, signature, data, ); assert(result, false, 'result === false'); }); routes.set('/crypto.subtle.verify/incorrect-signature-hmac', async () => { const keyUint8Array = new Uint8Array([1, 0, 1]); const signature = new Uint8Array(); const enc = new TextEncoder(); const data = enc.encode('hello world'); for (const algorithm of ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512']) { const key = await globalThis.crypto.subtle.importKey( 'raw', keyUint8Array, { name: 'HMAC', hash: algorithm }, false, ['sign', 'verify'], ); const result = await crypto.subtle.verify('HMAC', key, signature, data); assert(result, false, 'result'); } }); } // correct-signature { routes.set('/crypto.subtle.verify/correct-signature-jwk-rsa', async () => { const pkey = await crypto.subtle.importKey( 'jwk', privateRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, privateRsaJsonWebKeyData.ext, privateRsaJsonWebKeyData.key_ops, ); const key = await crypto.subtle.importKey( 'jwk', publicRsaJsonWebKeyData, rsaJsonWebKeyAlgorithm, publicRsaJsonWebKeyData.ext, publicRsaJsonWebKeyData.key_ops, ); const enc = new TextEncoder(); const data = enc.encode('hello world'); const signature = await crypto.subtle.sign( rsaJsonWebKeyAlgorithm, pkey, data, ); const result = await crypto.subtle.verify( rsaJsonWebKeyAlgorithm, key, signature, data, ); assert(result, true, 'result === true'); }); routes.set( '/crypto.subtle.verify/correct-signature-jwk-ecdsa', async () => { const pkey = await crypto.subtle.importKey( 'jwk', privateEcdsaJsonWebKeyData, ecdsaJsonWebKeyAlgorithm, privateEcdsaJsonWebKeyData.ext, privateEcdsaJsonWebKeyData.key_ops, ); const key = await crypto.subtle.importKey( 'jwk', publicEcdsaJsonWebKeyData, ecdsaJsonWebKeyAlgorithm, publicEcdsaJsonWebKeyData.ext, publicEcdsaJsonWebKeyData.key_ops, ); const enc = new TextEncoder(); const data = enc.encode('hello world'); const signature = await crypto.subtle.sign( ecdsaJsonWebKeyAlgorithm, pkey, data, ); const result = await crypto.subtle.verify( ecdsaJsonWebKeyAlgorithm, key, signature, data, ); assert(result, true, 'result === true'); }, ); routes.set('/crypto.subtle.verify/correct-signature-hmac', async () => { const results = { 'SHA-1': new Uint8Array([ 222, 61, 81, 133, 232, 89, 130, 225, 248, 25, 220, 34, 245, 103, 89, 127, 136, 77, 146, 166, ]), 'SHA-256': new Uint8Array([ 92, 237, 16, 210, 91, 89, 194, 36, 95, 98, 27, 175, 64, 25, 15, 160, 152, 178, 145, 235, 62, 92, 23, 202, 125, 228, 8, 25, 148, 26, 215, 242, ]), 'SHA-384': new Uint8Array([ 238, 20, 74, 173, 238, 236, 161, 229, 250, 167, 72, 210, 188, 239, 233, 39, 233, 166, 114, 241, 140, 229, 201, 129, 243, 173, 74, 198, 223, 145, 228, 96, 253, 91, 166, 111, 244, 23, 141, 62, 112, 156, 90, 166, 214, 69, 185, 48, ]), 'SHA-512': new Uint8Array([ 211, 127, 139, 149, 23, 225, 84, 230, 82, 249, 109, 254, 168, 236, 217, 112, 174, 52, 231, 62, 167, 197, 33, 11, 181, 21, 162, 236, 214, 132, 43, 161, 92, 112, 230, 182, 140, 69, 169, 229, 87, 98, 57, 81, 140, 134, 219, 253, 139, 169, 85, 181, 195, 195, 166, 241, 219, 33, 9, 56, 67, 213, 51, 224, ]), }; const encoder = new TextEncoder(); const messageUint8Array = encoder.encode('aki'); const keyUint8Array = new Uint8Array([1, 0, 1]); for (const algorithm of ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512']) { const key = await globalThis.crypto.subtle.importKey( 'raw', keyUint8Array, { name: 'HMAC', hash: algorithm }, false, ['sign', 'verify'], ); // Sign the message with HMAC and the CryptoKey // const signature = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, messageUint8Array)); const signature = results[algorithm]; const result = await crypto.subtle.verify( 'HMAC', key, signature, messageUint8Array, ); assert(result, true, 'result'); } }); } } ================================================ FILE: integration-tests/js-compute/fixtures/app/src/device.js ================================================ /// /* eslint-env serviceworker */ import { assert, assertThrows } from './assertions.js'; import { Device } from 'fastly:device'; import { routes } from './routes.js'; routes.set('/device/interface', () => { let actual = Reflect.ownKeys(Device); let expected = ['prototype', 'lookup', 'length', 'name']; assert(actual, expected, `Reflect.ownKeys(Device)`); // Check the prototype descriptors are correct { actual = Reflect.getOwnPropertyDescriptor(Device, 'prototype'); expected = { value: Device.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Device, 'prototype')`, ); } // Check the constructor function's defined parameter length is correct { actual = Reflect.getOwnPropertyDescriptor(Device, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Device, 'length')`, ); } // Check the constructor function's name is correct { actual = Reflect.getOwnPropertyDescriptor(Device, 'name'); expected = { value: 'Device', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Device, 'name')`, ); } // Check the prototype has the correct keys { actual = Reflect.ownKeys(Device.prototype); expected = [ 'constructor', 'name', 'brand', 'model', 'hardwareType', 'isDesktop', 'isGameConsole', 'isMediaPlayer', 'isMobile', 'isSmartTV', 'isTablet', 'isTouchscreen', 'isBot', 'toJSON', Symbol.toStringTag, ]; assert(actual, expected, `Reflect.ownKeys(Device.prototype)`); } // Check the constructor on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor(Device.prototype, 'constructor'); expected = { writable: true, enumerable: false, configurable: true, value: Device.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Device.prototype, 'constructor')`, ); assert( typeof Device.prototype.constructor, 'function', `typeof Device.prototype.constructor`, ); actual = Reflect.getOwnPropertyDescriptor( Device.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Device.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( Device.prototype.constructor, 'name', ); expected = { value: 'Device', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Device.prototype.constructor, 'name')`, ); } // Check the Symbol.toStringTag on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( Device.prototype, Symbol.toStringTag, ); expected = { writable: false, enumerable: false, configurable: true, value: 'Device', }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Device.prototype, [Symbol.toStringTag])`, ); assert( typeof Device.prototype[Symbol.toStringTag], 'string', `typeof Device.prototype[Symbol.toStringTag]`, ); } // Check the lookup static method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(Device, 'lookup'); expected = { writable: true, enumerable: true, configurable: true, value: Device.lookup, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Device, 'lookup')`, ); assert(typeof Device.lookup, 'function', `typeof Device.lookup`); actual = Reflect.getOwnPropertyDescriptor(Device.lookup, 'length'); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Device.lookup, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(Device.lookup, 'name'); expected = { value: 'lookup', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Device.lookup, 'name')`, ); } for (let property of [ 'name', 'brand', 'model', 'hardwareType', 'isDesktop', 'isGameConsole', 'isMediaPlayer', 'isMobile', 'isSmartTV', 'isTablet', 'isTouchscreen', 'isBot', ]) { const descriptors = Reflect.getOwnPropertyDescriptor( Device.prototype, property, ); expected = { enumerable: true, configurable: true }; assert( descriptors.enumerable, true, `Reflect.getOwnPropertyDescriptor(Device, '${property}').enumerable`, ); assert( descriptors.configurable, true, `Reflect.getOwnPropertyDescriptor(Device, '${property}').configurable`, ); assert( descriptors.value, undefined, `Reflect.getOwnPropertyDescriptor(Device, '${property}').value`, ); assert( descriptors.set, undefined, `Reflect.getOwnPropertyDescriptor(Device, '${property}').set`, ); assert( typeof descriptors.get, 'function', `typeof Reflect.getOwnPropertyDescriptor(Device, '${property}').get`, ); } }); // Device constructor { routes.set('/device/constructor/called-as-regular-function', () => { assertThrows(() => { Device(); }, TypeError); }); routes.set('/device/constructor/throws', () => { assertThrows(() => new Device(), TypeError); }); } // Device lookup static method // static lookup(useragent: string): DeviceEntry | null; { routes.set('/device/lookup/called-as-constructor', () => { assertThrows(() => { new Device.lookup('1'); }, TypeError); }); // https://tc39.es/ecma262/#sec-tostring routes.set('/device/lookup/useragent-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const useragent = { toString() { throw sentinel; }, }; Device.lookup(useragent); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { Device.lookup(Symbol()); }, TypeError, `can't convert symbol to string`, ); }); routes.set('/device/lookup/useragent-parameter-not-supplied', () => { assertThrows( () => { Device.lookup(); }, TypeError, `Device.lookup: At least 1 argument required, but only 0 passed`, ); }); routes.set('/device/lookup/useragent-parameter-empty-string', () => { assertThrows( () => { Device.lookup(''); }, Error, `Device.lookup: useragent parameter can not be an empty string`, ); }); routes.set('/device/lookup/useragent-does-not-exist-returns-null', () => { let result = Device.lookup(Math.random()); assert(result, null, `Device.lookup(Math.random()) === null`); }); routes.set('/device/lookup/useragent-exists-all-fields-identified', () => { let useragent = 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 FBAN/FBIOS;FBAV/8.0.0.28.18;FBBV/1665515;FBDV/iPhone4,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/7.0.4;FBSS/2; FBCR/Telekom.de;FBID/phone;FBLC/de_DE;FBOP/5'; let device = Device.lookup(useragent); assert( device instanceof Device, true, `Device.lookup(useragent) instanceof DeviceEntry`, ); assert(device.name, 'iPhone', `device.name`); assert(device.brand, 'Apple', `device.brand`); assert(device.model, 'iPhone4,1', `device.model`); assert(device.hardwareType, 'Mobile Phone', `device.hardwareType`); assert(device.isDesktop, false, `device.isDesktop`); assert(device.isGameConsole, false, `device.isGameConsole`); assert(device.isMediaPlayer, false, `device.isMediaPlayer`); assert(device.isMobile, true, `device.isMobile`); assert(device.isSmartTV, false, `device.isSmartTV`); assert(device.isTablet, false, `device.isTablet`); assert(device.isTouchscreen, true, `device.isTouchscreen`); assert(device.isBot, null, `device.isBot`); }); routes.set( '/device/lookup/useragent-exists-all-fields-identified-tojson', () => { let useragent = 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 FBAN/FBIOS;FBAV/8.0.0.28.18;FBBV/1665515;FBDV/iPhone4,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/7.0.4;FBSS/2; FBCR/Telekom.de;FBID/phone;FBLC/de_DE;FBOP/5'; let device = Device.lookup(useragent); device = device.toJSON(); assert(device.brand, 'Apple', `device.brand`); assert(device.model, 'iPhone4,1', `device.model`); assert(device.hardwareType, 'Mobile Phone', `device.hardwareType`); assert(device.isDesktop, false, `device.isDesktop`); assert(device.isGameConsole, false, `device.isGameConsole`); assert(device.isMediaPlayer, false, `device.isMediaPlayer`); assert(device.isMobile, true, `device.isMobile`); assert(device.isSmartTV, false, `device.isSmartTV`); assert(device.isTablet, false, `device.isTablet`); assert(device.isTouchscreen, true, `device.isTouchscreen`); assert(device.isBot, null, `device.isBot`); }, ); routes.set('/device/lookup/useragent-exists-some-fields-identified', () => { let useragent = 'ghosts-app/1.0.2.1 (ASUSTeK COMPUTER INC.; X550CC; Windows 8 (X86); en)'; let device = Device.lookup(useragent); assert( device instanceof Device, true, `Device.lookup(useragent) instanceof DeviceEntry`, ); assert(device.name, 'Asus TeK', `device.name`); assert(device.brand, 'Asus', `device.brand`); assert(device.model, 'TeK', `device.model`); assert(device.hardwareType, null, `device.hardwareType`); assert(device.isDesktop, false, `device.isDesktop`); assert(device.isGameConsole, null, `device.isGameConsole`); assert(device.isMediaPlayer, null, `device.isMediaPlayer`); assert(device.isMobile, null, `device.isMobile`); assert(device.isSmartTV, null, `device.isSmartTV`); assert(device.isTablet, null, `device.isTablet`); assert(device.isTouchscreen, null, `device.isTouchscreen`); assert(device.isBot, null, `device.isBot`); assert( JSON.stringify(device), '{"name":"Asus TeK","brand":"Asus","model":"TeK","hardwareType":null,"isDesktop":false,"isGameConsole":null,"isMediaPlayer":null,"isMobile":null,"isSmartTV":null,"isTablet":null,"isTouchscreen":null,"isBot":null}', `JSON.stringify(device)`, ); }); } routes.set('/device/lookup/bot-detection', () => { let useragent = 'Googlebot/2.1 (+http://www.google.com/bot.html)'; let device = Device.lookup(useragent); assert( device instanceof Device, true, `Device.lookup(useragent) instanceof DeviceEntry`, ); assert(device.name, 'Googlebot', `device.name`); assert(device.brand, 'Google', `device.brand`); assert(device.isBot, true, `device.isBot`); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/dictionary.js ================================================ /* eslint-env serviceworker */ import { Dictionary } from 'fastly:dictionary'; import { routes } from './routes.js'; import { assertThrows, assert, assertResolves } from './assertions.js'; import { env } from 'fastly:env'; const DICTIONARY_NAME = env('DICTIONARY_NAME'); // Dictionary { routes.set('/dictionary/exposed-as-global', () => { assert(typeof Dictionary, 'function', `typeof Dictionary`); }); routes.set('/dictionary/interface', dictionaryInterfaceTests); // Dictionary constructor { routes.set('/dictionary/constructor/called-as-regular-function', () => { assertThrows( () => { Dictionary(); }, TypeError, `calling a builtin Dictionary constructor without new is forbidden`, ); }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/dictionary/constructor/parameter-calls-7.1.17-ToString', () => { let sentinel = Symbol(); const test = () => { const name = { toString() { throw sentinel; }, }; new Dictionary(name); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => new Dictionary(Symbol()), TypeError, `can't convert symbol to string`, ); }, ); routes.set('/dictionary/constructor/empty-parameter', () => { assertThrows( () => { new Dictionary(); }, TypeError, `Dictionary constructor: At least 1 argument required, but only 0 passed`, ); }); routes.set('/dictionary/constructor/found', () => { const store = createValidDictionary(); assert(store instanceof Dictionary, true, `store instanceof Dictionary`); }); routes.set('/dictionary/constructor/invalid-name', () => { // control Characters (\\u0000-\\u001F) are not allowed const invalidNames = ['1', '-', ' ', 'Ä']; for (const name of invalidNames) { assertThrows( () => { new Dictionary(name); }, TypeError, `Dictionary constructor: name must start with an ascii alpabetical character`, ); } assertThrows( () => { new Dictionary('aÄ'); }, TypeError, `Dictionary constructor: name can contain only ascii alphanumeric characters, underscores, and ascii whitespace`, ); // must be less than 256 characters assertThrows( () => { new Dictionary('a'.repeat(256)); }, TypeError, `Dictionary constructor: name can not be more than 255 characters`, ); // empty string not allowed assertThrows( () => { new Dictionary(''); }, TypeError, `Dictionary constructor: name can not be an empty string`, ); }); } // Dictionary get method { routes.set('/dictionary/get/called-as-constructor', () => { assertThrows(() => { new Dictionary.prototype.get('1'); }, TypeError); }); routes.set('/dictionary/get/called-unbound', () => { assertThrows(() => { Dictionary.prototype.get.call(undefined, '1'); }, TypeError); }); // https://tc39.es/ecma262/#sec-tostring routes.set('/dictionary/get/key-parameter-calls-7.1.17-ToString', () => { let sentinel = Symbol(); const test = () => { const key = { toString() { throw sentinel; }, }; const store = createValidDictionary(); store.get(key); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { const store = createValidDictionary(); store.get(Symbol()); }, TypeError, `can't convert symbol to string`, ); }); routes.set('/dictionary/get/key-parameter-not-supplied', () => { assertThrows( () => { const store = createValidDictionary(); store.get(); }, TypeError, `get: At least 1 argument required, but only 0 passed`, ); }); routes.set('/dictionary/get/key-parameter-empty-string', () => { assertThrows( () => { const store = createValidDictionary(); store.get(''); }, TypeError, `Dictionary key can not be an empty string`, ); }); routes.set('/dictionary/get/key-parameter-255-character-string', () => { assertResolves(() => { const store = createValidDictionary(); const key = 'a'.repeat(255); store.get(key); }); }); routes.set('/dictionary/get/key-parameter-256-character-string', () => { assertThrows( () => { const store = createValidDictionary(); const key = 'a'.repeat(256); store.get(key); }, TypeError, `Dictionary key can not be more than 255 characters`, ); }); routes.set('/dictionary/get/key-does-not-exist-returns-null', () => { let store = createValidDictionary(); let result = store.get(Math.random()); assert(result, null, `store.get(Math.random())`); }); routes.set('/dictionary/get/key-exists', () => { let store = createValidDictionary(); let result = store.get('twitter'); assert( result, 'https://twitter.com/fastly', `store.get('twitter') === "https://twitter.com/fastly"`, ); }); } } function dictionaryInterfaceTests() { let actual = Reflect.ownKeys(Dictionary); let expected = ['prototype', 'length', 'name']; assert(actual, expected, `Reflect.ownKeys(Dictionary)`); actual = Reflect.getOwnPropertyDescriptor(Dictionary, 'prototype'); expected = { value: Dictionary.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Dictionary, 'prototype')`, ); actual = Reflect.getOwnPropertyDescriptor(Dictionary, 'length'); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Dictionary, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(Dictionary, 'name'); expected = { value: 'Dictionary', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Dictionary, 'name')`, ); actual = Reflect.ownKeys(Dictionary.prototype); expected = ['constructor', 'get']; assert(actual, expected, `Reflect.ownKeys(Dictionary.prototype)`); actual = Reflect.getOwnPropertyDescriptor( Dictionary.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: Dictionary.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Dictionary.prototype, 'constructor')`, ); actual = Reflect.getOwnPropertyDescriptor(Dictionary.prototype, 'get'); expected = { writable: true, enumerable: true, configurable: true, value: Dictionary.prototype.get, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Dictionary.prototype, 'get')`, ); assert( typeof Dictionary.prototype.constructor, 'function', `typeof Dictionary.prototype.constructor`, ); assert( typeof Dictionary.prototype.get, 'function', `typeof Dictionary.prototype.get`, ); actual = Reflect.getOwnPropertyDescriptor( Dictionary.prototype.constructor, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Dictionary.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( Dictionary.prototype.constructor, 'name', ); expected = { value: 'Dictionary', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Dictionary.prototype.constructor, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor(Dictionary.prototype.get, 'length'); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Dictionary.prototype.get, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(Dictionary.prototype.get, 'name'); expected = { value: 'get', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Dictionary.prototype.get, 'name')`, ); } function createValidDictionary() { return new Dictionary(DICTIONARY_NAME); } ================================================ FILE: integration-tests/js-compute/fixtures/app/src/early-hints.js ================================================ import { pass, ok, strictEqual, assertThrows } from './assertions.js'; import { routes } from './routes.js'; routes.set('/early-hints/manual-response', (event) => { event.respondWith( new Response(null, { status: 103, headers: { link: '; rel=preload; as=style' }, }), ); event.respondWith(new Response('ok')); }); routes.set('/early-hints/manual-response-late', (event) => { event.respondWith(new Response('ok')); assertThrows(() => { event.respondWith( new Response(null, { status: 103, headers: { link: '; rel=preload; as=style' }, }), ); }); }); routes.set('/early-hints/manual-response-async', async (event) => { await (async () => { event.respondWith( new Response(null, { status: 103, headers: { link: '; rel=preload; as=style' }, }), ); event.respondWith(new Response('ok')); })(); }); routes.set('/early-hints/manual-response-late-async', async (event) => { await (async () => { event.respondWith(new Response('ok')); assertThrows(() => { event.respondWith( new Response(null, { status: 103, headers: { link: '; rel=preload; as=style' }, }), ); }); })(); }); routes.set('/early-hints/send-early-hints', (event) => { event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.respondWith(new Response('ok')); }); routes.set('/early-hints/send-early-hints-late', (event) => { event.respondWith(new Response('ok')); assertThrows(() => { event.sendEarlyHints({ link: '; rel=preload; as=style' }); }); }); routes.set('/early-hints/send-early-hints-multiple-headers', (event) => { event.sendEarlyHints([ ['link', '; rel=preload; as=style'], ['link', '; rel=preload; as=style'], ]); event.respondWith(new Response('ok')); }); routes.set('/early-hints/send-early-hints-async', async (event) => { await (async () => { event.sendEarlyHints({ link: '; rel=preload; as=style' }); event.respondWith(new Response('ok')); })(); }); routes.set('/early-hints/send-early-hints-late-async', async (event) => { await (async () => { event.respondWith(new Response('ok')); assertThrows(() => { event.sendEarlyHints({ link: '; rel=preload; as=style' }); }); })(); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/edge-rate-limiter.js ================================================ /// /* eslint-env serviceworker */ import { assert, assertThrows } from './assertions.js'; import { RateCounter, PenaltyBox, EdgeRateLimiter, } from 'fastly:edge-rate-limiter'; import { routes, isRunningLocally } from './routes.js'; import { env } from 'fastly:env'; const FASTLY_SERVICE_NAME = env('FASTLY_SERVICE_NAME'); const PENALTY_BOX_NAME = `pb${FASTLY_SERVICE_NAME}`; const RATE_COUNTER_NAME = `rc${FASTLY_SERVICE_NAME}`; // RateCounter { routes.set('/rate-counter/interface', () => { let actual = Reflect.ownKeys(RateCounter); let expected = ['prototype', 'length', 'name']; assert(actual, expected, `Reflect.ownKeys(RateCounter)`); // Check the prototype descriptors are correct { actual = Reflect.getOwnPropertyDescriptor(RateCounter, 'prototype'); expected = { value: RateCounter.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter, 'prototype')`, ); } // Check the constructor function's defined parameter length is correct { actual = Reflect.getOwnPropertyDescriptor(RateCounter, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter, 'length')`, ); } // Check the constructor function's name is correct { actual = Reflect.getOwnPropertyDescriptor(RateCounter, 'name'); expected = { value: 'RateCounter', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter, 'name')`, ); } // Check the prototype has the correct keys { actual = Reflect.ownKeys(RateCounter.prototype); expected = [ 'constructor', 'increment', 'lookupRate', 'lookupCount', Symbol.toStringTag, ]; assert(actual, expected, `Reflect.ownKeys(RateCounter.prototype)`); } // Check the constructor on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: RateCounter.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype, 'constructor')`, ); assert( typeof RateCounter.prototype.constructor, 'function', `typeof RateCounter.prototype.constructor`, ); actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype.constructor, 'name', ); expected = { value: 'RateCounter', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype.constructor, 'name')`, ); } // Check the Symbol.toStringTag on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype, Symbol.toStringTag, ); expected = { writable: false, enumerable: false, configurable: true, value: 'RateCounter', }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype, [Symbol.toStringTag])`, ); assert( typeof RateCounter.prototype[Symbol.toStringTag], 'string', `typeof RateCounter.prototype[Symbol.toStringTag]`, ); } // Check the increment method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype, 'increment', ); expected = { writable: true, enumerable: true, configurable: true, value: RateCounter.prototype.increment, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype, 'increment')`, ); assert( typeof RateCounter.prototype.increment, 'function', `typeof RateCounter.prototype.increment`, ); actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype.increment, 'length', ); expected = { value: 2, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype.increment, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype.increment, 'name', ); expected = { value: 'increment', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype.increment, 'name')`, ); } // Check the lookupRate method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype, 'lookupRate', ); expected = { writable: true, enumerable: true, configurable: true, value: RateCounter.prototype.lookupRate, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype, 'lookupRate')`, ); assert( typeof RateCounter.prototype.lookupRate, 'function', `typeof RateCounter.prototype.lookupRate`, ); actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype.lookupRate, 'length', ); expected = { value: 2, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype.lookupRate, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype.lookupRate, 'name', ); expected = { value: 'lookupRate', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype.lookupRate, 'name')`, ); } // Check the lookupCount method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype, 'lookupCount', ); expected = { writable: true, enumerable: true, configurable: true, value: RateCounter.prototype.lookupCount, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype, 'lookupCount')`, ); assert( typeof RateCounter.prototype.lookupCount, 'function', `typeof RateCounter.prototype.lookupCount`, ); actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype.lookupCount, 'length', ); expected = { value: 2, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype.lookupCount, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( RateCounter.prototype.lookupCount, 'name', ); expected = { value: 'lookupCount', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(RateCounter.prototype.lookupCount, 'name')`, ); } }); // RateCounter constructor { routes.set('/rate-counter/constructor/called-as-regular-function', () => { assertThrows( () => { RateCounter(); }, Error, `calling a builtin RateCounter constructor without new is forbidden`, ); }); routes.set( '/rate-counter/constructor/called-as-constructor-no-arguments', () => { assertThrows( () => new RateCounter(), Error, `RateCounter constructor: At least 1 argument required, but only 0 passed`, ); }, ); // Ensure we correctly coerce the parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set( '/rate-counter/constructor/name-parameter-calls-7.1.17-ToString', () => { if (!isRunningLocally()) { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const name = { toString() { throw sentinel; }, }; new RateCounter(name); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { new RateCounter(Symbol()); }, Error, `can't convert symbol to string`, ); } }, ); routes.set('/rate-counter/constructor/happy-path', () => { assert( new RateCounter(RATE_COUNTER_NAME) instanceof RateCounter, true, `new RateCounter("rc") instanceof RateCounter`, ); }); } // RateCounter increment method // increment(entry: string, delta: number): void; { routes.set('/rate-counter/increment/called-as-constructor', () => { assertThrows(() => { new RateCounter.prototype.increment('entry', 1); }, Error); }); // Ensure we correctly coerce the parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set( '/rate-counter/increment/entry-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const entry = { toString() { throw sentinel; }, }; let rc = new RateCounter(RATE_COUNTER_NAME); rc.increment(entry, 1); }; assertThrows(test); try { test(); } catch (thrownError) { console.log({ thrownError }); assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.increment(Symbol(), 1); }, Error, `can't convert symbol to string`, ); }, ); routes.set('/rate-counter/increment/entry-parameter-not-supplied', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.increment(); }, Error, `increment: At least 2 arguments required, but only 0 passed`, ); }); routes.set('/rate-counter/increment/delta-parameter-not-supplied', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.increment('entry'); }, Error, `increment: At least 2 arguments required, but only 1 passed`, ); }); routes.set('/rate-counter/increment/delta-parameter-negative', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.increment('entry', -1); }, Error, `increment: delta parameter is an invalid value, only positive numbers can be used for delta values.`, ); }); routes.set('/rate-counter/increment/delta-parameter-infinity', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.increment('entry', Infinity); }, Error, `increment: delta parameter is an invalid value, only positive numbers can be used for delta values.`, ); }); routes.set('/rate-counter/increment/delta-parameter-NaN', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.increment('entry', NaN); }, Error, `increment: delta parameter is an invalid value, only positive numbers can be used for delta values.`, ); }); routes.set('/rate-counter/increment/returns-undefined', () => { let rc = new RateCounter(RATE_COUNTER_NAME); assert(rc.increment('meow', 1), undefined, "rc.increment('meow', 1)"); }); } // RateCounter lookupRate method // lookupRate(entry: string, window: [1, 10, 60]): number; { routes.set('/rate-counter/lookupRate/called-as-constructor', () => { assertThrows(() => { new RateCounter.prototype.lookupRate('entry', 1); }, Error); }); // Ensure we correctly coerce the parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set( '/rate-counter/lookupRate/entry-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const entry = { toString() { throw sentinel; }, }; let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupRate(entry, 1); }; assertThrows(test); try { test(); } catch (thrownError) { console.log({ thrownError }); assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupRate(Symbol(), 1); }, Error, `can't convert symbol to string`, ); }, ); routes.set('/rate-counter/lookupRate/entry-parameter-not-supplied', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupRate(); }, Error, `lookupRate: At least 2 arguments required, but only 0 passed`, ); }); routes.set('/rate-counter/lookupRate/window-parameter-not-supplied', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupRate('entry'); }, Error, `lookupRate: At least 2 arguments required, but only 1 passed`, ); }); routes.set('/rate-counter/lookupRate/window-parameter-negative', () => { if (!isRunningLocally()) { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupRate('entry', -1); }, Error, `lookupRate: window parameter must be either: 1, 10, or 60`, ); } }); routes.set('/rate-counter/lookupRate/window-parameter-infinity', () => { if (!isRunningLocally()) { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupRate('entry', Infinity); }, Error, `lookupRate: window parameter must be either: 1, 10, or 60`, ); } }); routes.set('/rate-counter/lookupRate/window-parameter-NaN', () => { if (!isRunningLocally()) { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupRate('entry', NaN); }, Error, `lookupRate: window parameter must be either: 1, 10, or 60`, ); } }); routes.set('/rate-counter/lookupRate/returns-number', () => { let rc = new RateCounter(RATE_COUNTER_NAME); assert( typeof rc.lookupRate('meow', 1), 'number', `typeof rc.lookupRate('meow', 1)`, ); }); } // RateCounter lookupCount method // lookupCount(entry: string, duration: [10, 20, 30, 40, 50, 60]): number; { routes.set('/rate-counter/lookupCount/called-as-constructor', () => { assertThrows(() => { new RateCounter.prototype.lookupCount('entry', 1); }, Error); }); // Ensure we correctly coerce the parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set( '/rate-counter/lookupCount/entry-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const entry = { toString() { throw sentinel; }, }; let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupCount(entry, 1); }; assertThrows(test); try { test(); } catch (thrownError) { console.log({ thrownError }); assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupCount(Symbol(), 1); }, Error, `can't convert symbol to string`, ); }, ); routes.set('/rate-counter/lookupCount/entry-parameter-not-supplied', () => { if (!isRunningLocally()) { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupCount(); }, Error, `lookupCount: At least 2 arguments required, but only 0 passed`, ); } }); routes.set( '/rate-counter/lookupCount/duration-parameter-not-supplied', () => { if (!isRunningLocally()) { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupCount('entry'); }, Error, `lookupCount: At least 2 arguments required, but only 1 passed`, ); } }, ); routes.set('/rate-counter/lookupCount/duration-parameter-negative', () => { if (!isRunningLocally()) { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupCount('entry', -1); }, Error, `lookupCount: duration parameter must be either: 10, 20, 30, 40, 50, or 60`, ); } }); routes.set('/rate-counter/lookupCount/duration-parameter-infinity', () => { if (!isRunningLocally()) { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupCount('entry', Infinity); }, Error, `lookupCount: duration parameter must be either: 10, 20, 30, 40, 50, or 60`, ); } }); routes.set('/rate-counter/lookupCount/duration-parameter-NaN', () => { if (!isRunningLocally()) { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); rc.lookupCount('entry', NaN); }, Error, `lookupCount: duration parameter must be either: 10, 20, 30, 40, 50, or 60`, ); } }); routes.set('/rate-counter/lookupCount/returns-number', () => { let rc = new RateCounter(RATE_COUNTER_NAME); assert( typeof rc.lookupCount('meow', 10), 'number', `typeof rc.lookupCount('meow', 1)`, ); }); } } // PenaltyBox { routes.set('/penalty-box/interface', () => { let actual = Reflect.ownKeys(PenaltyBox); let expected = ['prototype', 'length', 'name']; assert(actual, expected, `Reflect.ownKeys(PenaltyBox)`); // Check the prototype descriptors are correct { actual = Reflect.getOwnPropertyDescriptor(PenaltyBox, 'prototype'); expected = { value: PenaltyBox.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox, 'prototype')`, ); } // Check the constructor function's defined parameter length is correct { actual = Reflect.getOwnPropertyDescriptor(PenaltyBox, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox, 'length')`, ); } // Check the constructor function's name is correct { actual = Reflect.getOwnPropertyDescriptor(PenaltyBox, 'name'); expected = { value: 'PenaltyBox', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox, 'name')`, ); } // Check the prototype has the correct keys { actual = Reflect.ownKeys(PenaltyBox.prototype); expected = ['constructor', 'add', 'has', Symbol.toStringTag]; assert(actual, expected, `Reflect.ownKeys(PenaltyBox.prototype)`); } // Check the constructor on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( PenaltyBox.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: PenaltyBox.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype, 'constructor')`, ); assert( typeof PenaltyBox.prototype.constructor, 'function', `typeof PenaltyBox.prototype.constructor`, ); actual = Reflect.getOwnPropertyDescriptor( PenaltyBox.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( PenaltyBox.prototype.constructor, 'name', ); expected = { value: 'PenaltyBox', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype.constructor, 'name')`, ); } // Check the Symbol.toStringTag on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( PenaltyBox.prototype, Symbol.toStringTag, ); expected = { writable: false, enumerable: false, configurable: true, value: 'PenaltyBox', }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype, [Symbol.toStringTag])`, ); assert( typeof PenaltyBox.prototype[Symbol.toStringTag], 'string', `typeof PenaltyBox.prototype[Symbol.toStringTag]`, ); } // Check the add method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype, 'add'); expected = { writable: true, enumerable: true, configurable: true, value: PenaltyBox.prototype.add, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype, 'add')`, ); assert( typeof PenaltyBox.prototype.add, 'function', `typeof PenaltyBox.prototype.add`, ); actual = Reflect.getOwnPropertyDescriptor( PenaltyBox.prototype.add, 'length', ); expected = { value: 2, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype.add, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( PenaltyBox.prototype.add, 'name', ); expected = { value: 'add', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype.add, 'name')`, ); } // Check the has method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype, 'has'); expected = { writable: true, enumerable: true, configurable: true, value: PenaltyBox.prototype.has, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype, 'has')`, ); assert( typeof PenaltyBox.prototype.has, 'function', `typeof PenaltyBox.prototype.has`, ); actual = Reflect.getOwnPropertyDescriptor( PenaltyBox.prototype.has, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype.has, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( PenaltyBox.prototype.has, 'name', ); expected = { value: 'has', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(PenaltyBox.prototype.has, 'name')`, ); } }); // PenaltyBox constructor { routes.set('/penalty-box/constructor/called-as-regular-function', () => { assertThrows( () => { PenaltyBox(); }, Error, `calling a builtin PenaltyBox constructor without new is forbidden`, ); }); routes.set( '/penalty-box/constructor/called-as-constructor-no-arguments', () => { assertThrows( () => new PenaltyBox(), Error, `PenaltyBox constructor: At least 1 argument required, but only 0 passed`, ); }, ); // Ensure we correctly coerce the parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set( '/penalty-box/constructor/name-parameter-calls-7.1.17-ToString', () => { if (!isRunningLocally()) { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const name = { toString() { throw sentinel; }, }; new PenaltyBox(name); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { new PenaltyBox(Symbol()); }, Error, `can't convert symbol to string`, ); } }, ); routes.set('/penalty-box/constructor/happy-path', () => { assert( new PenaltyBox(RATE_COUNTER_NAME) instanceof PenaltyBox, true, `new PenaltyBox("rc") instanceof PenaltyBox`, ); }); } // PenaltyBox has method // has(entry: string): boolean; { routes.set('/penalty-box/has/called-as-constructor', () => { assertThrows(() => { new PenaltyBox.prototype.has('entry'); }, Error); }); // Ensure we correctly coerce the parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set('/penalty-box/has/entry-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const entry = { toString() { throw sentinel; }, }; let pb = new PenaltyBox(PENALTY_BOX_NAME); pb.has(entry); }; assertThrows(test); try { test(); } catch (thrownError) { console.log({ thrownError }); assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { let pb = new PenaltyBox(PENALTY_BOX_NAME); pb.has(Symbol()); }, Error, `can't convert symbol to string`, ); }); routes.set('/penalty-box/has/entry-parameter-not-supplied', () => { assertThrows( () => { let pb = new PenaltyBox(PENALTY_BOX_NAME); pb.has(); }, Error, `has: At least 1 argument required, but only 0 passed`, ); }); routes.set('/penalty-box/has/returns-boolean', () => { let pb = new PenaltyBox(`pb-`); assert(pb.has('meow'), false, "pb.has('meow')"); }); } // PenaltyBox add method // add(entry: string, timeToLive: number): void; { routes.set('/penalty-box/add/called-as-constructor', () => { assertThrows(() => { new PenaltyBox.prototype.add('entry', 1); }, Error); }); // Ensure we correctly coepbe the parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set('/penalty-box/add/entry-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const entry = { toString() { throw sentinel; }, }; let pb = new PenaltyBox(PENALTY_BOX_NAME); pb.add(entry, 1); }; assertThrows(test); try { test(); } catch (thrownError) { console.log({ thrownError }); assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { let pb = new PenaltyBox(PENALTY_BOX_NAME); pb.add(Symbol(), 1); }, Error, `can't convert symbol to string`, ); }); routes.set('/penalty-box/add/entry-parameter-not-supplied', () => { assertThrows( () => { let pb = new PenaltyBox(PENALTY_BOX_NAME); pb.add(); }, Error, `add: At least 2 arguments required, but only 0 passed`, ); }); routes.set('/penalty-box/add/timeToLive-parameter-not-supplied', () => { assertThrows( () => { let pb = new PenaltyBox(PENALTY_BOX_NAME); pb.add('entry'); }, Error, `add: At least 2 arguments required, but only 1 passed`, ); }); routes.set('/penalty-box/add/timeToLive-parameter-negative', () => { assertThrows( () => { let pb = new PenaltyBox(PENALTY_BOX_NAME); pb.add('entry', -1); }, Error, `add: timeToLive parameter is an invalid value, only numbers from 1 to 60 can be used for timeToLive values.`, ); }); routes.set('/penalty-box/add/timeToLive-parameter-infinity', () => { assertThrows( () => { let pb = new PenaltyBox(PENALTY_BOX_NAME); pb.add('entry', Infinity); }, Error, `add: timeToLive parameter is an invalid value, only numbers from 1 to 60 can be used for timeToLive values.`, ); }); routes.set('/penalty-box/add/timeToLive-parameter-NaN', () => { assertThrows( () => { let pb = new PenaltyBox(PENALTY_BOX_NAME); pb.add('entry', NaN); }, Error, `add: timeToLive parameter is an invalid value, only numbers from 1 to 60 can be used for timeToLive values.`, ); }); routes.set('/penalty-box/add/returns-undefined', () => { let pb = new PenaltyBox(PENALTY_BOX_NAME); assert(pb.add('meow', 1), undefined, `pb.add('meow', 1)`); }); } } // EdgeRateLimiter { routes.set('/edge-rate-limiter/interface', () => { let actual = Reflect.ownKeys(EdgeRateLimiter); let expected = ['prototype', 'length', 'name']; assert(actual, expected, `Reflect.ownKeys(EdgeRateLimiter)`); // Check the prototype descriptors are correct { actual = Reflect.getOwnPropertyDescriptor(EdgeRateLimiter, 'prototype'); expected = { value: EdgeRateLimiter.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(EdgeRateLimiter, 'prototype')`, ); } // Check the constructor function's defined parameter length is correct { actual = Reflect.getOwnPropertyDescriptor(EdgeRateLimiter, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(EdgeRateLimiter, 'length')`, ); } // Check the constructor function's name is correct { actual = Reflect.getOwnPropertyDescriptor(EdgeRateLimiter, 'name'); expected = { value: 'EdgeRateLimiter', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(EdgeRateLimiter, 'name')`, ); } // Check the prototype has the correct keys { actual = Reflect.ownKeys(EdgeRateLimiter.prototype); expected = ['constructor', 'checkRate', Symbol.toStringTag]; assert(actual, expected, `Reflect.ownKeys(EdgeRateLimiter.prototype)`); } // Check the constructor on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( EdgeRateLimiter.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: EdgeRateLimiter.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(EdgeRateLimiter.prototype, 'constructor')`, ); assert( typeof EdgeRateLimiter.prototype.constructor, 'function', `typeof EdgeRateLimiter.prototype.constructor`, ); actual = Reflect.getOwnPropertyDescriptor( EdgeRateLimiter.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(EdgeRateLimiter.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( EdgeRateLimiter.prototype.constructor, 'name', ); expected = { value: 'EdgeRateLimiter', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(EdgeRateLimiter.prototype.constructor, 'name')`, ); } // Check the Symbol.toStringTag on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( EdgeRateLimiter.prototype, Symbol.toStringTag, ); expected = { writable: false, enumerable: false, configurable: true, value: 'EdgeRateLimiter', }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(EdgeRateLimiter.prototype, [Symbol.toStringTag])`, ); assert( typeof EdgeRateLimiter.prototype[Symbol.toStringTag], 'string', `typeof EdgeRateLimiter.prototype[Symbol.toStringTag]`, ); } // Check the checkRate method has correct descriptors, length and name { actual = Reflect.getOwnPropertyDescriptor( EdgeRateLimiter.prototype, 'checkRate', ); expected = { writable: true, enumerable: true, configurable: true, value: EdgeRateLimiter.prototype.checkRate, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(EdgeRateLimiter.prototype, 'checkRate')`, ); assert( typeof EdgeRateLimiter.prototype.checkRate, 'function', `typeof EdgeRateLimiter.prototype.checkRate`, ); actual = Reflect.getOwnPropertyDescriptor( EdgeRateLimiter.prototype.checkRate, 'length', ); expected = { value: 5, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(EdgeRateLimiter.prototype.checkRate, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( EdgeRateLimiter.prototype.checkRate, 'name', ); expected = { value: 'checkRate', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(EdgeRateLimiter.prototype.checkRate, 'name')`, ); } }); // EdgeRateLimiter constructor { routes.set( '/edge-rate-limiter/constructor/called-as-regular-function', () => { assertThrows( () => { EdgeRateLimiter(); }, Error, `calling a builtin EdgeRateLimiter constructor without new is forbidden`, ); }, ); routes.set( '/edge-rate-limiter/constructor/called-as-constructor-no-arguments', () => { assertThrows( () => new EdgeRateLimiter(), Error, `EdgeRateLimiter constructor: At least 2 arguments required, but only 0 passed`, ); }, ); // Ensure we correctly coerce the parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set( '/edge-rate-limiter/constructor/rate-counter-not-instance-of-rateCounter', () => { assertThrows( () => { new EdgeRateLimiter(true, true); }, Error, `EdgeRateLimiter constructor: rateCounter parameter must be an instance of RateCounter`, ); }, ); routes.set( '/edge-rate-limiter/constructor/penalty-box-not-instance-of-penaltyBox', () => { assertThrows( () => { new EdgeRateLimiter(new RateCounter(RATE_COUNTER_NAME), true); }, Error, `EdgeRateLimiter constructor: penaltyBox parameter must be an instance of PenaltyBox`, ); }, ); routes.set('/edge-rate-limiter/constructor/happy-path', () => { assert( new EdgeRateLimiter( new RateCounter(RATE_COUNTER_NAME), new PenaltyBox(PENALTY_BOX_NAME), ) instanceof EdgeRateLimiter, true, `new EdgeRateLimiter(new RateCounter("rc"), new PenaltyBox(PENALTY_BOX_NAME)) instanceof EdgeRateLimiter`, ); }); } // EdgeRateLimiter checkRate method // checkRate(entry: string, delta: number, window: [1, 10, 60], limit: number, timeToLive: number): boolean; { routes.set('/edge-rate-limiter/checkRate/called-as-constructor', () => { assertThrows(() => { new EdgeRateLimiter.prototype.checkRate('entry'); }, Error); }); // Ensure we correctly coerce the parameter to a string as according to // https://tc39.es/ecma262/#sec-tostring routes.set( '/edge-rate-limiter/checkRate/entry-parameter-calls-7.1.17-ToString', () => { let sentinel; const test = () => { sentinel = Symbol('sentinel'); const entry = { toString() { throw sentinel; }, }; let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate(entry, 1, 1, 1, 1); }; assertThrows(test); try { test(); } catch (thrownError) { console.log({ thrownError }); assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate(Symbol(), 1, 1, 1, 1); }, Error, `can't convert symbol to string`, ); }, ); routes.set( '/edge-rate-limiter/checkRate/entry-parameter-not-supplied', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate(); }, Error, `checkRate: At least 5 arguments required, but only 0 passed`, ); }, ); routes.set('/edge-rate-limiter/checkRate/delta-parameter-negative', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', -1, 1, 1, 1); }, Error, `checkRate: delta parameter is an invalid value, only positive numbers can be used for delta values.`, ); }); routes.set('/edge-rate-limiter/checkRate/delta-parameter-infinity', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', Infinity, 1, 1, 1); }, Error, `checkRate: delta parameter is an invalid value, only positive numbers can be used for delta values.`, ); }); routes.set('/edge-rate-limiter/checkRate/delta-parameter-NaN', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', NaN, 1, 1, 1); }, Error, `checkRate: delta parameter is an invalid value, only positive numbers can be used for delta values.`, ); }); routes.set('/edge-rate-limiter/checkRate/window-parameter-negative', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', 1, -1, 1, 1); }, Error, `checkRate: window parameter must be either: 1, 10, or 60`, ); }); routes.set('/edge-rate-limiter/checkRate/window-parameter-infinity', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', 1, Infinity, 1, 1); }, Error, `checkRate: window parameter must be either: 1, 10, or 60`, ); }); routes.set('/edge-rate-limiter/checkRate/window-parameter-NaN', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', 1, NaN, 1, 1); }, Error, `checkRate: window parameter must be either: 1, 10, or 60`, ); }); routes.set('/edge-rate-limiter/checkRate/limit-parameter-negative', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', 1, 1, -1, 1); }, Error, `checkRate: limit parameter is an invalid value, only positive numbers can be used for limit values.`, ); }); routes.set('/edge-rate-limiter/checkRate/limit-parameter-infinity', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', 1, 1, Infinity, 1); }, Error, `checkRate: limit parameter is an invalid value, only positive numbers can be used for limit values.`, ); }); routes.set('/edge-rate-limiter/checkRate/limit-parameter-NaN', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', 1, 1, NaN, 1); }, Error, `checkRate: limit parameter is an invalid value, only positive numbers can be used for limit values.`, ); }); routes.set( '/edge-rate-limiter/checkRate/timeToLive-parameter-negative', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', 1, 1, 1, -1); }, Error, `checkRate: timeToLive parameter is an invalid value, only numbers from 1 to 60 can be used for timeToLive values.`, ); }, ); routes.set( '/edge-rate-limiter/checkRate/timeToLive-parameter-infinity', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', 1, 1, 1, Infinity); }, Error, `checkRate: timeToLive parameter is an invalid value, only numbers from 1 to 60 can be used for timeToLive values.`, ); }, ); routes.set('/edge-rate-limiter/checkRate/timeToLive-parameter-NaN', () => { assertThrows( () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); erl.checkRate('entry', 1, 1, 1, NaN); }, Error, `checkRate: timeToLive parameter is an invalid value, only numbers from 1 to 60 can be used for timeToLive values.`, ); }); routes.set('/edge-rate-limiter/checkRate/returns-boolean', () => { let rc = new RateCounter(RATE_COUNTER_NAME); let pb = new PenaltyBox(PENALTY_BOX_NAME); let erl = new EdgeRateLimiter(rc, pb); assert( erl.checkRate('woof', 1, 10, 100, 5), false, "erl.checkRate('meow', 1, 10, 100, 5)", ); }); } } ================================================ FILE: integration-tests/js-compute/fixtures/app/src/env.js ================================================ /* eslint-env serviceworker */ import { env } from 'fastly:env'; import { routes, isRunningLocally } from './routes.js'; import { strictEqual } from './assertions.js'; // hostname didn't exist at initialization, so can still be captured at runtime const wizerHostname = env('FASTLY_HOSTNAME'); const wizerLocal = env('LOCAL_TEST'); routes.set('/env', () => { strictEqual(wizerHostname, undefined); if (isRunningLocally()) { strictEqual( env('FASTLY_HOSTNAME'), 'localhost', `env("FASTLY_HOSTNAME") === "localhost"`, ); } else { strictEqual(env('FASTLY_HOSTNAME'), undefined); } strictEqual(wizerLocal, 'local val'); // at runtime these remain captured from Wizer time, even if we didn't call env strictEqual(env('LOCAL_TEST'), 'local val'); strictEqual(env('TEST'), 'foo'); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/error.js ================================================ import { routes } from './routes.js'; routes.set('/error', async () => { throw new Error('uh oh'); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/fanout.js ================================================ import { assert, assertDoesNotThrow, assertThrows } from './assertions.js'; import { routes } from './routes.js'; import { createFanoutHandoff } from 'fastly:fanout'; routes.set('/createFanoutHandoff', () => { assert(typeof createFanoutHandoff, 'function', 'typeof createFanoutHandoff'); assert( createFanoutHandoff.name, 'createFanoutHandoff', 'createFanoutHandoff.name', ); assert(createFanoutHandoff.length, 2, 'createFanoutHandoff.length'); assertDoesNotThrow(() => createFanoutHandoff(new Request('.'), 'hello')); assertThrows(() => createFanoutHandoff()); assertThrows(() => createFanoutHandoff(1, '')); let result = createFanoutHandoff(new Request('.'), 'hello'); assert(result instanceof Response, true, 'result instanceof Response'); assertThrows( () => new createFanoutHandoff(new Request('.'), 'hello'), TypeError, ); assertDoesNotThrow(() => { createFanoutHandoff.call(undefined, new Request('.'), '1'); }); // https://tc39.es/ecma262/#sec-tostring let sentinel; const test = () => { sentinel = Symbol(); const key = { toString() { throw sentinel; }, }; createFanoutHandoff(new Request('.'), key); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { createFanoutHandoff(new Request('.'), Symbol()); }, TypeError, `can't convert symbol to string`, ); assertThrows( () => createFanoutHandoff(new Request('.')), TypeError, `createFanoutHandoff: At least 2 arguments required, but only 1 passed`, ); assertThrows( () => createFanoutHandoff(new Request('.'), ''), Error, `createFanoutHandoff: Backend parameter can not be an empty string`, ); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/fast-check.js ================================================ var __defProp = Object.defineProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; // ../../../node_modules/fast-check/lib/esm/fast-check-default.js var fast_check_default_exports = {}; __export(fast_check_default_exports, { Arbitrary: () => Arbitrary, ExecutionStatus: () => ExecutionStatus, PreconditionFailure: () => PreconditionFailure, Random: () => Random, Stream: () => Stream, Value: () => Value, VerbosityLevel: () => VerbosityLevel, __commitHash: () => __commitHash2, __type: () => __type2, __version: () => __version2, anything: () => anything, array: () => array, ascii: () => ascii, asciiString: () => asciiString, assert: () => assert, asyncDefaultReportMessage: () => asyncDefaultReportMessage, asyncModelRun: () => asyncModelRun, asyncProperty: () => asyncProperty, asyncStringify: () => asyncStringify, asyncToStringMethod: () => asyncToStringMethod, base64: () => base64, base64String: () => base64String, bigInt: () => bigInt, bigInt64Array: () => bigInt64Array, bigIntN: () => bigIntN, bigUint: () => bigUint, bigUint64Array: () => bigUint64Array, bigUintN: () => bigUintN, boolean: () => boolean, char: () => char, char16bits: () => char16bits, check: () => check, clone: () => clone, cloneIfNeeded: () => cloneIfNeeded, cloneMethod: () => cloneMethod, commands: () => commands, compareBooleanFunc: () => compareBooleanFunc, compareFunc: () => compareFunc, configureGlobal: () => configureGlobal, constant: () => constant, constantFrom: () => constantFrom, context: () => context, createDepthIdentifier: () => createDepthIdentifier, date: () => date, defaultReportMessage: () => defaultReportMessage, dictionary: () => dictionary, domain: () => domain, double: () => double, emailAddress: () => emailAddress, falsy: () => falsy, float: () => float, float32Array: () => float32Array, float64Array: () => float64Array, fullUnicode: () => fullUnicode, fullUnicodeString: () => fullUnicodeString, func: () => func, gen: () => gen, getDepthContextFor: () => getDepthContextFor, hasAsyncToStringMethod: () => hasAsyncToStringMethod, hasCloneMethod: () => hasCloneMethod, hasToStringMethod: () => hasToStringMethod, hash: () => hash, hexa: () => hexa, hexaString: () => hexaString, infiniteStream: () => infiniteStream, int16Array: () => int16Array, int32Array: () => int32Array, int8Array: () => int8Array, integer: () => integer, ipV4: () => ipV4, ipV4Extended: () => ipV4Extended, ipV6: () => ipV6, json: () => json, jsonValue: () => jsonValue, letrec: () => letrec, lorem: () => lorem, mapToConstant: () => mapToConstant, maxSafeInteger: () => maxSafeInteger, maxSafeNat: () => maxSafeNat, memo: () => memo, mixedCase: () => mixedCase, modelRun: () => modelRun, nat: () => nat, object: () => object, oneof: () => oneof, option: () => option, pre: () => pre, property: () => property, readConfigureGlobal: () => readConfigureGlobal, record: () => record, resetConfigureGlobal: () => resetConfigureGlobal, sample: () => sample, scheduledModelRun: () => scheduledModelRun, scheduler: () => scheduler, schedulerFor: () => schedulerFor, shuffledSubarray: () => shuffledSubarray, sparseArray: () => sparseArray, statistics: () => statistics, stream: () => stream, string: () => string, string16bits: () => string16bits, stringMatching: () => stringMatching, stringOf: () => stringOf, stringify: () => stringify, subarray: () => subarray, toStringMethod: () => toStringMethod, tuple: () => tuple, uint16Array: () => uint16Array, uint32Array: () => uint32Array, uint8Array: () => uint8Array, uint8ClampedArray: () => uint8ClampedArray, ulid: () => ulid, unicode: () => unicode, unicodeJson: () => unicodeJson, unicodeJsonValue: () => unicodeJsonValue, unicodeString: () => unicodeString, uniqueArray: () => uniqueArray, uuid: () => uuid, uuidV: () => uuidV, webAuthority: () => webAuthority, webFragments: () => webFragments, webPath: () => webPath, webQueryParameters: () => webQueryParameters, webSegment: () => webSegment, webUrl: () => webUrl, }); // ../../../node_modules/fast-check/lib/esm/check/precondition/PreconditionFailure.js var PreconditionFailure = class _PreconditionFailure extends Error { constructor(interruptExecution = false) { super(); this.interruptExecution = interruptExecution; this.footprint = _PreconditionFailure.SharedFootPrint; } static isFailure(err) { return ( err != null && err.footprint === _PreconditionFailure.SharedFootPrint ); } }; PreconditionFailure.SharedFootPrint = Symbol('fast-check/PreconditionFailure'); // ../../../node_modules/fast-check/lib/esm/check/precondition/Pre.js function pre(expectTruthy) { if (!expectTruthy) { throw new PreconditionFailure(); } } // ../../../node_modules/fast-check/lib/esm/stream/StreamHelpers.js var Nil = class { [Symbol.iterator]() { return this; } next(value) { return { value, done: true }; } }; Nil.nil = new Nil(); function nilHelper() { return Nil.nil; } function* mapHelper(g, f) { for (const v of g) { yield f(v); } } function* flatMapHelper(g, f) { for (const v of g) { yield* f(v); } } function* filterHelper(g, f) { for (const v of g) { if (f(v)) { yield v; } } } function* takeNHelper(g, n) { for (let i = 0; i < n; ++i) { const cur = g.next(); if (cur.done) { break; } yield cur.value; } } function* takeWhileHelper(g, f) { let cur = g.next(); while (!cur.done && f(cur.value)) { yield cur.value; cur = g.next(); } } function* joinHelper(g, others) { for (let cur = g.next(); !cur.done; cur = g.next()) { yield cur.value; } for (const s of others) { for (let cur = s.next(); !cur.done; cur = s.next()) { yield cur.value; } } } // ../../../node_modules/fast-check/lib/esm/stream/Stream.js var safeSymbolIterator = Symbol.iterator; var Stream = class _Stream { static nil() { return new _Stream(nilHelper()); } static of(...elements) { return new _Stream(elements[safeSymbolIterator]()); } constructor(g) { this.g = g; } next() { return this.g.next(); } [safeSymbolIterator]() { return this.g; } map(f) { return new _Stream(mapHelper(this.g, f)); } flatMap(f) { return new _Stream(flatMapHelper(this.g, f)); } dropWhile(f) { let foundEligible = false; function* helper(v) { if (foundEligible || !f(v)) { foundEligible = true; yield v; } } return this.flatMap(helper); } drop(n) { if (n <= 0) { return this; } let idx = 0; function helper() { return idx++ < n; } return this.dropWhile(helper); } takeWhile(f) { return new _Stream(takeWhileHelper(this.g, f)); } take(n) { return new _Stream(takeNHelper(this.g, n)); } filter(f) { return new _Stream(filterHelper(this.g, f)); } every(f) { for (const v of this.g) { if (!f(v)) { return false; } } return true; } has(f) { for (const v of this.g) { if (f(v)) { return [true, v]; } } return [false, null]; } join(...others) { return new _Stream(joinHelper(this.g, others)); } getNthOrLast(nth) { let remaining = nth; let last = null; for (const v of this.g) { if (remaining-- === 0) return v; last = v; } return last; } }; function stream(g) { return new Stream(g); } // ../../../node_modules/fast-check/lib/esm/check/symbols.js var cloneMethod = Symbol('fast-check/cloneMethod'); function hasCloneMethod(instance) { return ( instance !== null && (typeof instance === 'object' || typeof instance === 'function') && cloneMethod in instance && typeof instance[cloneMethod] === 'function' ); } function cloneIfNeeded(instance) { return hasCloneMethod(instance) ? instance[cloneMethod]() : instance; } // ../../../node_modules/fast-check/lib/esm/check/arbitrary/definition/Value.js var safeObjectDefineProperty = Object.defineProperty; var Value = class { constructor(value_, context2, customGetValue = void 0) { this.value_ = value_; this.context = context2; this.hasToBeCloned = customGetValue !== void 0 || hasCloneMethod(value_); this.readOnce = false; if (this.hasToBeCloned) { safeObjectDefineProperty(this, 'value', { get: customGetValue !== void 0 ? customGetValue : this.getValue, }); } else { this.value = value_; } } getValue() { if (this.hasToBeCloned) { if (!this.readOnce) { this.readOnce = true; return this.value_; } return this.value_[cloneMethod](); } return this.value_; } }; // ../../../node_modules/fast-check/lib/esm/check/arbitrary/definition/Arbitrary.js var safeObjectAssign = Object.assign; var Arbitrary = class { filter(refinement) { return new FilterArbitrary(this, refinement); } map(mapper, unmapper) { return new MapArbitrary(this, mapper, unmapper); } chain(chainer) { return new ChainArbitrary(this, chainer); } noShrink() { return new NoShrinkArbitrary(this); } noBias() { return new NoBiasArbitrary(this); } }; var ChainArbitrary = class extends Arbitrary { constructor(arb, chainer) { super(); this.arb = arb; this.chainer = chainer; } generate(mrng, biasFactor) { const clonedMrng = mrng.clone(); const src = this.arb.generate(mrng, biasFactor); return this.valueChainer(src, mrng, clonedMrng, biasFactor); } canShrinkWithoutContext(value) { return false; } shrink(value, context2) { if (this.isSafeContext(context2)) { return ( !context2.stoppedForOriginal ? this.arb .shrink(context2.originalValue, context2.originalContext) .map((v) => this.valueChainer( v, context2.clonedMrng.clone(), context2.clonedMrng, context2.originalBias, ), ) : Stream.nil() ).join( context2.chainedArbitrary .shrink(value, context2.chainedContext) .map((dst) => { const newContext = safeObjectAssign( safeObjectAssign({}, context2), { chainedContext: dst.context, stoppedForOriginal: true, }, ); return new Value(dst.value_, newContext); }), ); } return Stream.nil(); } valueChainer(v, generateMrng, clonedMrng, biasFactor) { const chainedArbitrary = this.chainer(v.value_); const dst = chainedArbitrary.generate(generateMrng, biasFactor); const context2 = { originalBias: biasFactor, originalValue: v.value_, originalContext: v.context, stoppedForOriginal: false, chainedArbitrary, chainedContext: dst.context, clonedMrng, }; return new Value(dst.value_, context2); } isSafeContext(context2) { return ( context2 != null && typeof context2 === 'object' && 'originalBias' in context2 && 'originalValue' in context2 && 'originalContext' in context2 && 'stoppedForOriginal' in context2 && 'chainedArbitrary' in context2 && 'chainedContext' in context2 && 'clonedMrng' in context2 ); } }; var MapArbitrary = class extends Arbitrary { constructor(arb, mapper, unmapper) { super(); this.arb = arb; this.mapper = mapper; this.unmapper = unmapper; this.bindValueMapper = (v) => this.valueMapper(v); } generate(mrng, biasFactor) { const g = this.arb.generate(mrng, biasFactor); return this.valueMapper(g); } canShrinkWithoutContext(value) { if (this.unmapper !== void 0) { try { const unmapped = this.unmapper(value); return this.arb.canShrinkWithoutContext(unmapped); } catch (_err) { return false; } } return false; } shrink(value, context2) { if (this.isSafeContext(context2)) { return this.arb .shrink(context2.originalValue, context2.originalContext) .map(this.bindValueMapper); } if (this.unmapper !== void 0) { const unmapped = this.unmapper(value); return this.arb.shrink(unmapped, void 0).map(this.bindValueMapper); } return Stream.nil(); } mapperWithCloneIfNeeded(v) { const sourceValue = v.value; const mappedValue = this.mapper(sourceValue); if ( v.hasToBeCloned && ((typeof mappedValue === 'object' && mappedValue !== null) || typeof mappedValue === 'function') && Object.isExtensible(mappedValue) && !hasCloneMethod(mappedValue) ) { Object.defineProperty(mappedValue, cloneMethod, { get: () => () => this.mapperWithCloneIfNeeded(v)[0], }); } return [mappedValue, sourceValue]; } valueMapper(v) { const [mappedValue, sourceValue] = this.mapperWithCloneIfNeeded(v); const context2 = { originalValue: sourceValue, originalContext: v.context }; return new Value(mappedValue, context2); } isSafeContext(context2) { return ( context2 != null && typeof context2 === 'object' && 'originalValue' in context2 && 'originalContext' in context2 ); } }; var FilterArbitrary = class extends Arbitrary { constructor(arb, refinement) { super(); this.arb = arb; this.refinement = refinement; this.bindRefinementOnValue = (v) => this.refinementOnValue(v); } generate(mrng, biasFactor) { while (true) { const g = this.arb.generate(mrng, biasFactor); if (this.refinementOnValue(g)) { return g; } } } canShrinkWithoutContext(value) { return this.arb.canShrinkWithoutContext(value) && this.refinement(value); } shrink(value, context2) { return this.arb.shrink(value, context2).filter(this.bindRefinementOnValue); } refinementOnValue(v) { return this.refinement(v.value); } }; var NoShrinkArbitrary = class extends Arbitrary { constructor(arb) { super(); this.arb = arb; } generate(mrng, biasFactor) { return this.arb.generate(mrng, biasFactor); } canShrinkWithoutContext(value) { return this.arb.canShrinkWithoutContext(value); } shrink(_value, _context) { return Stream.nil(); } noShrink() { return this; } }; var NoBiasArbitrary = class extends Arbitrary { constructor(arb) { super(); this.arb = arb; } generate(mrng, _biasFactor) { return this.arb.generate(mrng, void 0); } canShrinkWithoutContext(value) { return this.arb.canShrinkWithoutContext(value); } shrink(value, context2) { return this.arb.shrink(value, context2); } noBias() { return this; } }; function isArbitrary(instance) { return ( typeof instance === 'object' && instance !== null && 'generate' in instance && 'shrink' in instance && 'canShrinkWithoutContext' in instance ); } function assertIsArbitrary(instance) { if (!isArbitrary(instance)) { throw new Error('Unexpected value received: not an instance of Arbitrary'); } } // ../../../node_modules/fast-check/lib/esm/utils/apply.js var untouchedApply = Function.prototype.apply; var ApplySymbol = Symbol('apply'); function safeExtractApply(f) { try { return f.apply; } catch (err) { return void 0; } } function safeApplyHacky(f, instance, args) { const ff = f; ff[ApplySymbol] = untouchedApply; const out = ff[ApplySymbol](instance, args); delete ff[ApplySymbol]; return out; } function safeApply(f, instance, args) { if (safeExtractApply(f) === untouchedApply) { return f.apply(instance, args); } return safeApplyHacky(f, instance, args); } // ../../../node_modules/fast-check/lib/esm/utils/globals.js var SArray = typeof Array !== 'undefined' ? Array : void 0; var SBigInt = typeof BigInt !== 'undefined' ? BigInt : void 0; var SBigInt64Array = typeof BigInt64Array !== 'undefined' ? BigInt64Array : void 0; var SBigUint64Array = typeof BigUint64Array !== 'undefined' ? BigUint64Array : void 0; var SBoolean = typeof Boolean !== 'undefined' ? Boolean : void 0; var SDate = typeof Date !== 'undefined' ? Date : void 0; var SError = typeof Error !== 'undefined' ? Error : void 0; var SFloat32Array = typeof Float32Array !== 'undefined' ? Float32Array : void 0; var SFloat64Array = typeof Float64Array !== 'undefined' ? Float64Array : void 0; var SInt8Array = typeof Int8Array !== 'undefined' ? Int8Array : void 0; var SInt16Array = typeof Int16Array !== 'undefined' ? Int16Array : void 0; var SInt32Array = typeof Int32Array !== 'undefined' ? Int32Array : void 0; var SNumber = typeof Number !== 'undefined' ? Number : void 0; var SString = typeof String !== 'undefined' ? String : void 0; var SSet = typeof Set !== 'undefined' ? Set : void 0; var SUint8Array = typeof Uint8Array !== 'undefined' ? Uint8Array : void 0; var SUint8ClampedArray = typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : void 0; var SUint16Array = typeof Uint16Array !== 'undefined' ? Uint16Array : void 0; var SUint32Array = typeof Uint32Array !== 'undefined' ? Uint32Array : void 0; var SencodeURIComponent = typeof encodeURIComponent !== 'undefined' ? encodeURIComponent : void 0; var untouchedForEach = Array.prototype.forEach; var untouchedIndexOf = Array.prototype.indexOf; var untouchedJoin = Array.prototype.join; var untouchedMap = Array.prototype.map; var untouchedFilter = Array.prototype.filter; var untouchedPush = Array.prototype.push; var untouchedPop = Array.prototype.pop; var untouchedSplice = Array.prototype.splice; var untouchedSlice = Array.prototype.slice; var untouchedSort = Array.prototype.sort; var untouchedEvery = Array.prototype.every; function extractForEach(instance) { try { return instance.forEach; } catch (err) { return void 0; } } function extractIndexOf(instance) { try { return instance.indexOf; } catch (err) { return void 0; } } function extractJoin(instance) { try { return instance.join; } catch (err) { return void 0; } } function extractMap(instance) { try { return instance.map; } catch (err) { return void 0; } } function extractFilter(instance) { try { return instance.filter; } catch (err) { return void 0; } } function extractPush(instance) { try { return instance.push; } catch (err) { return void 0; } } function extractPop(instance) { try { return instance.pop; } catch (err) { return void 0; } } function extractSplice(instance) { try { return instance.splice; } catch (err) { return void 0; } } function extractSlice(instance) { try { return instance.slice; } catch (err) { return void 0; } } function extractSort(instance) { try { return instance.sort; } catch (err) { return void 0; } } function extractEvery(instance) { try { return instance.every; } catch (err) { return void 0; } } function safeForEach(instance, fn) { if (extractForEach(instance) === untouchedForEach) { return instance.forEach(fn); } return safeApply(untouchedForEach, instance, [fn]); } function safeIndexOf(instance, ...args) { if (extractIndexOf(instance) === untouchedIndexOf) { return instance.indexOf(...args); } return safeApply(untouchedIndexOf, instance, args); } function safeJoin(instance, ...args) { if (extractJoin(instance) === untouchedJoin) { return instance.join(...args); } return safeApply(untouchedJoin, instance, args); } function safeMap(instance, fn) { if (extractMap(instance) === untouchedMap) { return instance.map(fn); } return safeApply(untouchedMap, instance, [fn]); } function safeFilter(instance, predicate) { if (extractFilter(instance) === untouchedFilter) { return instance.filter(predicate); } return safeApply(untouchedFilter, instance, [predicate]); } function safePush(instance, ...args) { if (extractPush(instance) === untouchedPush) { return instance.push(...args); } return safeApply(untouchedPush, instance, args); } function safePop(instance) { if (extractPop(instance) === untouchedPop) { return instance.pop(); } return safeApply(untouchedPop, instance, []); } function safeSplice(instance, ...args) { if (extractSplice(instance) === untouchedSplice) { return instance.splice(...args); } return safeApply(untouchedSplice, instance, args); } function safeSlice(instance, ...args) { if (extractSlice(instance) === untouchedSlice) { return instance.slice(...args); } return safeApply(untouchedSlice, instance, args); } function safeSort(instance, ...args) { if (extractSort(instance) === untouchedSort) { return instance.sort(...args); } return safeApply(untouchedSort, instance, args); } function safeEvery(instance, ...args) { if (extractEvery(instance) === untouchedEvery) { return instance.every(...args); } return safeApply(untouchedEvery, instance, args); } var untouchedGetTime = Date.prototype.getTime; var untouchedToISOString = Date.prototype.toISOString; function extractGetTime(instance) { try { return instance.getTime; } catch (err) { return void 0; } } function extractToISOString(instance) { try { return instance.toISOString; } catch (err) { return void 0; } } function safeGetTime(instance) { if (extractGetTime(instance) === untouchedGetTime) { return instance.getTime(); } return safeApply(untouchedGetTime, instance, []); } function safeToISOString(instance) { if (extractToISOString(instance) === untouchedToISOString) { return instance.toISOString(); } return safeApply(untouchedToISOString, instance, []); } var untouchedAdd = Set.prototype.add; function extractAdd(instance) { try { return instance.add; } catch (err) { return void 0; } } function safeAdd(instance, value) { if (extractAdd(instance) === untouchedAdd) { return instance.add(value); } return safeApply(untouchedAdd, instance, [value]); } var untouchedSplit = String.prototype.split; var untouchedStartsWith = String.prototype.startsWith; var untouchedEndsWith = String.prototype.endsWith; var untouchedSubstring = String.prototype.substring; var untouchedToLowerCase = String.prototype.toLowerCase; var untouchedToUpperCase = String.prototype.toUpperCase; var untouchedPadStart = String.prototype.padStart; var untouchedCharCodeAt = String.prototype.charCodeAt; var untouchedReplace = String.prototype.replace; function extractSplit(instance) { try { return instance.split; } catch (err) { return void 0; } } function extractStartsWith(instance) { try { return instance.startsWith; } catch (err) { return void 0; } } function extractEndsWith(instance) { try { return instance.endsWith; } catch (err) { return void 0; } } function extractSubstring(instance) { try { return instance.substring; } catch (err) { return void 0; } } function extractToLowerCase(instance) { try { return instance.toLowerCase; } catch (err) { return void 0; } } function extractToUpperCase(instance) { try { return instance.toUpperCase; } catch (err) { return void 0; } } function extractPadStart(instance) { try { return instance.padStart; } catch (err) { return void 0; } } function extractCharCodeAt(instance) { try { return instance.charCodeAt; } catch (err) { return void 0; } } function extractReplace(instance) { try { return instance.replace; } catch (err) { return void 0; } } function safeSplit(instance, ...args) { if (extractSplit(instance) === untouchedSplit) { return instance.split(...args); } return safeApply(untouchedSplit, instance, args); } function safeStartsWith(instance, ...args) { if (extractStartsWith(instance) === untouchedStartsWith) { return instance.startsWith(...args); } return safeApply(untouchedStartsWith, instance, args); } function safeEndsWith(instance, ...args) { if (extractEndsWith(instance) === untouchedEndsWith) { return instance.endsWith(...args); } return safeApply(untouchedEndsWith, instance, args); } function safeSubstring(instance, ...args) { if (extractSubstring(instance) === untouchedSubstring) { return instance.substring(...args); } return safeApply(untouchedSubstring, instance, args); } function safeToLowerCase(instance) { if (extractToLowerCase(instance) === untouchedToLowerCase) { return instance.toLowerCase(); } return safeApply(untouchedToLowerCase, instance, []); } function safeToUpperCase(instance) { if (extractToUpperCase(instance) === untouchedToUpperCase) { return instance.toUpperCase(); } return safeApply(untouchedToUpperCase, instance, []); } function safePadStart(instance, ...args) { if (extractPadStart(instance) === untouchedPadStart) { return instance.padStart(...args); } return safeApply(untouchedPadStart, instance, args); } function safeCharCodeAt(instance, index) { if (extractCharCodeAt(instance) === untouchedCharCodeAt) { return instance.charCodeAt(index); } return safeApply(untouchedCharCodeAt, instance, [index]); } function safeReplace(instance, pattern, replacement) { if (extractReplace(instance) === untouchedReplace) { return instance.replace(pattern, replacement); } return safeApply(untouchedReplace, instance, [pattern, replacement]); } var untouchedNumberToString = Number.prototype.toString; function extractNumberToString(instance) { try { return instance.toString; } catch (err) { return void 0; } } function safeNumberToString(instance, ...args) { if (extractNumberToString(instance) === untouchedNumberToString) { return instance.toString(...args); } return safeApply(untouchedNumberToString, instance, args); } var untouchedHasOwnProperty = Object.prototype.hasOwnProperty; var untouchedToString = Object.prototype.toString; function safeHasOwnProperty(instance, v) { return safeApply(untouchedHasOwnProperty, instance, [v]); } function safeToString(instance) { return safeApply(untouchedToString, instance, []); } // ../../../node_modules/fast-check/lib/esm/stream/LazyIterableIterator.js var LazyIterableIterator = class { constructor(producer) { this.producer = producer; } [Symbol.iterator]() { if (this.it === void 0) { this.it = this.producer(); } return this.it; } next() { if (this.it === void 0) { this.it = this.producer(); } return this.it.next(); } }; function makeLazy(producer) { return new LazyIterableIterator(producer); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/TupleArbitrary.js var safeArrayIsArray = Array.isArray; var safeObjectDefineProperty2 = Object.defineProperty; function tupleMakeItCloneable(vs, values) { return safeObjectDefineProperty2(vs, cloneMethod, { value: () => { const cloned = []; for (let idx = 0; idx !== values.length; ++idx) { safePush(cloned, values[idx].value); } tupleMakeItCloneable(cloned, values); return cloned; }, }); } function tupleWrapper(values) { let cloneable = false; const vs = []; const ctxs = []; for (let idx = 0; idx !== values.length; ++idx) { const v = values[idx]; cloneable = cloneable || v.hasToBeCloned; safePush(vs, v.value); safePush(ctxs, v.context); } if (cloneable) { tupleMakeItCloneable(vs, values); } return new Value(vs, ctxs); } function tupleShrink(arbs, value, context2) { const shrinks = []; const safeContext = safeArrayIsArray(context2) ? context2 : []; for (let idx = 0; idx !== arbs.length; ++idx) { safePush( shrinks, makeLazy(() => arbs[idx] .shrink(value[idx], safeContext[idx]) .map((v) => { const nextValues = safeMap( value, (v2, idx2) => new Value(cloneIfNeeded(v2), safeContext[idx2]), ); return [ ...safeSlice(nextValues, 0, idx), v, ...safeSlice(nextValues, idx + 1), ]; }) .map(tupleWrapper), ), ); } return Stream.nil().join(...shrinks); } var TupleArbitrary = class extends Arbitrary { constructor(arbs) { super(); this.arbs = arbs; for (let idx = 0; idx !== arbs.length; ++idx) { const arb = arbs[idx]; if (arb == null || arb.generate == null) throw new Error( `Invalid parameter encountered at index ${idx}: expecting an Arbitrary`, ); } } generate(mrng, biasFactor) { const mapped = []; for (let idx = 0; idx !== this.arbs.length; ++idx) { safePush(mapped, this.arbs[idx].generate(mrng, biasFactor)); } return tupleWrapper(mapped); } canShrinkWithoutContext(value) { if (!safeArrayIsArray(value) || value.length !== this.arbs.length) { return false; } for (let index = 0; index !== this.arbs.length; ++index) { if (!this.arbs[index].canShrinkWithoutContext(value[index])) { return false; } } return true; } shrink(value, context2) { return tupleShrink(this.arbs, value, context2); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/tuple.js function tuple(...arbs) { return new TupleArbitrary(arbs); } // ../../../node_modules/fast-check/lib/esm/check/property/IRawProperty.js var safeMathLog = Math.log; function runIdToFrequency(runId) { return 2 + ~~(safeMathLog(runId + 1) * 0.4342944819032518); } // ../../../node_modules/fast-check/lib/esm/check/runner/configuration/GlobalParameters.js var globalParameters = {}; function configureGlobal(parameters) { globalParameters = parameters; } function readConfigureGlobal() { return globalParameters; } function resetConfigureGlobal() { globalParameters = {}; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/NoUndefinedAsContext.js var UndefinedContextPlaceholder = Symbol('UndefinedContextPlaceholder'); function noUndefinedAsContext(value) { if (value.context !== void 0) { return value; } if (value.hasToBeCloned) { return new Value( value.value_, UndefinedContextPlaceholder, () => value.value, ); } return new Value(value.value_, UndefinedContextPlaceholder); } // ../../../node_modules/fast-check/lib/esm/check/property/AsyncProperty.generic.js var AsyncProperty = class _AsyncProperty { constructor(arb, predicate) { this.arb = arb; this.predicate = predicate; const { asyncBeforeEach, asyncAfterEach, beforeEach, afterEach } = readConfigureGlobal() || {}; if (asyncBeforeEach !== void 0 && beforeEach !== void 0) { throw SError( `Global "asyncBeforeEach" and "beforeEach" parameters can't be set at the same time when running async properties`, ); } if (asyncAfterEach !== void 0 && afterEach !== void 0) { throw SError( `Global "asyncAfterEach" and "afterEach" parameters can't be set at the same time when running async properties`, ); } this.beforeEachHook = asyncBeforeEach || beforeEach || _AsyncProperty.dummyHook; this.afterEachHook = asyncAfterEach || afterEach || _AsyncProperty.dummyHook; } isAsync() { return true; } generate(mrng, runId) { const value = this.arb.generate( mrng, runId != null ? runIdToFrequency(runId) : void 0, ); return noUndefinedAsContext(value); } shrink(value) { if ( value.context === void 0 && !this.arb.canShrinkWithoutContext(value.value_) ) { return Stream.nil(); } const safeContext = value.context !== UndefinedContextPlaceholder ? value.context : void 0; return this.arb.shrink(value.value_, safeContext).map(noUndefinedAsContext); } async runBeforeEach() { await this.beforeEachHook(); } async runAfterEach() { await this.afterEachHook(); } async run(v, dontRunHook) { if (!dontRunHook) { await this.beforeEachHook(); } try { const output = await this.predicate(v); return output == null || output === true ? null : { error: new SError('Property failed by returning false'), errorMessage: 'Error: Property failed by returning false', }; } catch (err) { if (PreconditionFailure.isFailure(err)) return err; if (err instanceof SError && err.stack) { return { error: err, errorMessage: err.stack }; } return { error: err, errorMessage: SString(err) }; } finally { if (!dontRunHook) { await this.afterEachHook(); } } } beforeEach(hookFunction) { const previousBeforeEachHook = this.beforeEachHook; this.beforeEachHook = () => hookFunction(previousBeforeEachHook); return this; } afterEach(hookFunction) { const previousAfterEachHook = this.afterEachHook; this.afterEachHook = () => hookFunction(previousAfterEachHook); return this; } }; AsyncProperty.dummyHook = () => {}; // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/AlwaysShrinkableArbitrary.js var AlwaysShrinkableArbitrary = class extends Arbitrary { constructor(arb) { super(); this.arb = arb; } generate(mrng, biasFactor) { const value = this.arb.generate(mrng, biasFactor); return noUndefinedAsContext(value); } canShrinkWithoutContext(value) { return true; } shrink(value, context2) { if (context2 === void 0 && !this.arb.canShrinkWithoutContext(value)) { return Stream.nil(); } const safeContext = context2 !== UndefinedContextPlaceholder ? context2 : void 0; return this.arb.shrink(value, safeContext).map(noUndefinedAsContext); } }; // ../../../node_modules/fast-check/lib/esm/check/property/AsyncProperty.js function asyncProperty(...args) { if (args.length < 2) { throw new Error('asyncProperty expects at least two parameters'); } const arbs = safeSlice(args, 0, args.length - 1); const p = args[args.length - 1]; safeForEach(arbs, assertIsArbitrary); const mappedArbs = safeMap(arbs, (arb) => new AlwaysShrinkableArbitrary(arb)); return new AsyncProperty(tuple(...mappedArbs), (t) => p(...t)); } // ../../../node_modules/fast-check/lib/esm/check/property/Property.generic.js var Property = class _Property { constructor(arb, predicate) { this.arb = arb; this.predicate = predicate; const { beforeEach = _Property.dummyHook, afterEach = _Property.dummyHook, asyncBeforeEach, asyncAfterEach, } = readConfigureGlobal() || {}; if (asyncBeforeEach !== void 0) { throw SError( `"asyncBeforeEach" can't be set when running synchronous properties`, ); } if (asyncAfterEach !== void 0) { throw SError( `"asyncAfterEach" can't be set when running synchronous properties`, ); } this.beforeEachHook = beforeEach; this.afterEachHook = afterEach; } isAsync() { return false; } generate(mrng, runId) { const value = this.arb.generate( mrng, runId != null ? runIdToFrequency(runId) : void 0, ); return noUndefinedAsContext(value); } shrink(value) { if ( value.context === void 0 && !this.arb.canShrinkWithoutContext(value.value_) ) { return Stream.nil(); } const safeContext = value.context !== UndefinedContextPlaceholder ? value.context : void 0; return this.arb.shrink(value.value_, safeContext).map(noUndefinedAsContext); } runBeforeEach() { this.beforeEachHook(); } runAfterEach() { this.afterEachHook(); } run(v, dontRunHook) { if (!dontRunHook) { this.beforeEachHook(); } try { const output = this.predicate(v); return output == null || output === true ? null : { error: new SError('Property failed by returning false'), errorMessage: 'Error: Property failed by returning false', }; } catch (err) { if (PreconditionFailure.isFailure(err)) return err; if (err instanceof SError && err.stack) { return { error: err, errorMessage: err.stack }; } return { error: err, errorMessage: SString(err) }; } finally { if (!dontRunHook) { this.afterEachHook(); } } } beforeEach(hookFunction) { const previousBeforeEachHook = this.beforeEachHook; this.beforeEachHook = () => hookFunction(previousBeforeEachHook); return this; } afterEach(hookFunction) { const previousAfterEachHook = this.afterEachHook; this.afterEachHook = () => hookFunction(previousAfterEachHook); return this; } }; Property.dummyHook = () => {}; // ../../../node_modules/fast-check/lib/esm/check/property/Property.js function property(...args) { if (args.length < 2) { throw new Error('property expects at least two parameters'); } const arbs = safeSlice(args, 0, args.length - 1); const p = args[args.length - 1]; safeForEach(arbs, assertIsArbitrary); const mappedArbs = safeMap(arbs, (arb) => new AlwaysShrinkableArbitrary(arb)); return new Property(tuple(...mappedArbs), (t) => p(...t)); } // ../../../node_modules/pure-rand/lib/esm/pure-rand-default.js var pure_rand_default_exports = {}; __export(pure_rand_default_exports, { __commitHash: () => __commitHash, __type: () => __type, __version: () => __version, congruential32: () => congruential32, generateN: () => generateN, mersenne: () => MersenneTwister_default, skipN: () => skipN, uniformArrayIntDistribution: () => uniformArrayIntDistribution, uniformBigIntDistribution: () => uniformBigIntDistribution, uniformIntDistribution: () => uniformIntDistribution, unsafeGenerateN: () => unsafeGenerateN, unsafeSkipN: () => unsafeSkipN, unsafeUniformArrayIntDistribution: () => unsafeUniformArrayIntDistribution, unsafeUniformBigIntDistribution: () => unsafeUniformBigIntDistribution, unsafeUniformIntDistribution: () => unsafeUniformIntDistribution, xoroshiro128plus: () => xoroshiro128plus, xorshift128plus: () => xorshift128plus, }); // ../../../node_modules/pure-rand/lib/esm/generator/RandomGenerator.js function unsafeGenerateN(rng, num) { var out = []; for (var idx = 0; idx != num; ++idx) { out.push(rng.unsafeNext()); } return out; } function generateN(rng, num) { var nextRng = rng.clone(); var out = unsafeGenerateN(nextRng, num); return [out, nextRng]; } function unsafeSkipN(rng, num) { for (var idx = 0; idx != num; ++idx) { rng.unsafeNext(); } } function skipN(rng, num) { var nextRng = rng.clone(); unsafeSkipN(nextRng, num); return nextRng; } // ../../../node_modules/pure-rand/lib/esm/generator/LinearCongruential.js var MULTIPLIER = 214013; var INCREMENT = 2531011; var MASK = 4294967295; var MASK_2 = (1 << 31) - 1; var computeNextSeed = function (seed) { return (seed * MULTIPLIER + INCREMENT) & MASK; }; var computeValueFromNextSeed = function (nextseed) { return (nextseed & MASK_2) >> 16; }; var LinearCongruential32 = (function () { function LinearCongruential322(seed) { this.seed = seed; } LinearCongruential322.prototype.clone = function () { return new LinearCongruential322(this.seed); }; LinearCongruential322.prototype.next = function () { var nextRng = new LinearCongruential322(this.seed); var out = nextRng.unsafeNext(); return [out, nextRng]; }; LinearCongruential322.prototype.unsafeNext = function () { var s1 = computeNextSeed(this.seed); var v1 = computeValueFromNextSeed(s1); var s2 = computeNextSeed(s1); var v2 = computeValueFromNextSeed(s2); this.seed = computeNextSeed(s2); var v3 = computeValueFromNextSeed(this.seed); var vnext = v3 + ((v2 + (v1 << 15)) << 15); return vnext | 0; }; LinearCongruential322.prototype.getState = function () { return [this.seed]; }; return LinearCongruential322; })(); function fromState(state) { var valid = state.length === 1; if (!valid) { throw new Error( 'The state must have been produced by a congruential32 RandomGenerator', ); } return new LinearCongruential32(state[0]); } var congruential32 = Object.assign( function (seed) { return new LinearCongruential32(seed); }, { fromState }, ); // ../../../node_modules/pure-rand/lib/esm/generator/MersenneTwister.js var __read = function (o, n) { var m = typeof Symbol === 'function' && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error }; } finally { try { if (r && !r.done && (m = i['return'])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spreadArray = function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var MersenneTwister = (function () { function MersenneTwister2(states, index) { this.states = states; this.index = index; } MersenneTwister2.twist = function (prev) { var mt = prev.slice(); for (var idx = 0; idx !== MersenneTwister2.N - MersenneTwister2.M; ++idx) { var y_1 = (mt[idx] & MersenneTwister2.MASK_UPPER) + (mt[idx + 1] & MersenneTwister2.MASK_LOWER); mt[idx] = mt[idx + MersenneTwister2.M] ^ (y_1 >>> 1) ^ (-(y_1 & 1) & MersenneTwister2.A); } for ( var idx = MersenneTwister2.N - MersenneTwister2.M; idx !== MersenneTwister2.N - 1; ++idx ) { var y_2 = (mt[idx] & MersenneTwister2.MASK_UPPER) + (mt[idx + 1] & MersenneTwister2.MASK_LOWER); mt[idx] = mt[idx + MersenneTwister2.M - MersenneTwister2.N] ^ (y_2 >>> 1) ^ (-(y_2 & 1) & MersenneTwister2.A); } var y = (mt[MersenneTwister2.N - 1] & MersenneTwister2.MASK_UPPER) + (mt[0] & MersenneTwister2.MASK_LOWER); mt[MersenneTwister2.N - 1] = mt[MersenneTwister2.M - 1] ^ (y >>> 1) ^ (-(y & 1) & MersenneTwister2.A); return mt; }; MersenneTwister2.seeded = function (seed) { var out = Array(MersenneTwister2.N); out[0] = seed; for (var idx = 1; idx !== MersenneTwister2.N; ++idx) { var xored = out[idx - 1] ^ (out[idx - 1] >>> 30); out[idx] = (Math.imul(MersenneTwister2.F, xored) + idx) | 0; } return out; }; MersenneTwister2.from = function (seed) { return new MersenneTwister2( MersenneTwister2.twist(MersenneTwister2.seeded(seed)), 0, ); }; MersenneTwister2.prototype.clone = function () { return new MersenneTwister2(this.states, this.index); }; MersenneTwister2.prototype.next = function () { var nextRng = new MersenneTwister2(this.states, this.index); var out = nextRng.unsafeNext(); return [out, nextRng]; }; MersenneTwister2.prototype.unsafeNext = function () { var y = this.states[this.index]; y ^= this.states[this.index] >>> MersenneTwister2.U; y ^= (y << MersenneTwister2.S) & MersenneTwister2.B; y ^= (y << MersenneTwister2.T) & MersenneTwister2.C; y ^= y >>> MersenneTwister2.L; if (++this.index >= MersenneTwister2.N) { this.states = MersenneTwister2.twist(this.states); this.index = 0; } return y; }; MersenneTwister2.prototype.getState = function () { return __spreadArray([this.index], __read(this.states), false); }; MersenneTwister2.fromState = function (state) { var valid = state.length === MersenneTwister2.N + 1 && state[0] >= 0 && state[0] < MersenneTwister2.N; if (!valid) { throw new Error( 'The state must have been produced by a mersenne RandomGenerator', ); } return new MersenneTwister2(state.slice(1), state[0]); }; MersenneTwister2.N = 624; MersenneTwister2.M = 397; MersenneTwister2.R = 31; MersenneTwister2.A = 2567483615; MersenneTwister2.F = 1812433253; MersenneTwister2.U = 11; MersenneTwister2.S = 7; MersenneTwister2.B = 2636928640; MersenneTwister2.T = 15; MersenneTwister2.C = 4022730752; MersenneTwister2.L = 18; MersenneTwister2.MASK_LOWER = Math.pow(2, MersenneTwister2.R) - 1; MersenneTwister2.MASK_UPPER = Math.pow(2, MersenneTwister2.R); return MersenneTwister2; })(); function fromState2(state) { return MersenneTwister.fromState(state); } var MersenneTwister_default = Object.assign( function (seed) { return MersenneTwister.from(seed); }, { fromState: fromState2 }, ); // ../../../node_modules/pure-rand/lib/esm/generator/XorShift.js var XorShift128Plus = (function () { function XorShift128Plus2(s01, s00, s11, s10) { this.s01 = s01; this.s00 = s00; this.s11 = s11; this.s10 = s10; } XorShift128Plus2.prototype.clone = function () { return new XorShift128Plus2(this.s01, this.s00, this.s11, this.s10); }; XorShift128Plus2.prototype.next = function () { var nextRng = new XorShift128Plus2(this.s01, this.s00, this.s11, this.s10); var out = nextRng.unsafeNext(); return [out, nextRng]; }; XorShift128Plus2.prototype.unsafeNext = function () { var a0 = this.s00 ^ (this.s00 << 23); var a1 = this.s01 ^ ((this.s01 << 23) | (this.s00 >>> 9)); var b0 = a0 ^ this.s10 ^ ((a0 >>> 18) | (a1 << 14)) ^ ((this.s10 >>> 5) | (this.s11 << 27)); var b1 = a1 ^ this.s11 ^ (a1 >>> 18) ^ (this.s11 >>> 5); var out = (this.s00 + this.s10) | 0; this.s01 = this.s11; this.s00 = this.s10; this.s11 = b1; this.s10 = b0; return out; }; XorShift128Plus2.prototype.jump = function () { var nextRng = new XorShift128Plus2(this.s01, this.s00, this.s11, this.s10); nextRng.unsafeJump(); return nextRng; }; XorShift128Plus2.prototype.unsafeJump = function () { var ns01 = 0; var ns00 = 0; var ns11 = 0; var ns10 = 0; var jump = [1667051007, 2321340297, 1548169110, 304075285]; for (var i = 0; i !== 4; ++i) { for (var mask = 1; mask; mask <<= 1) { if (jump[i] & mask) { ns01 ^= this.s01; ns00 ^= this.s00; ns11 ^= this.s11; ns10 ^= this.s10; } this.unsafeNext(); } } this.s01 = ns01; this.s00 = ns00; this.s11 = ns11; this.s10 = ns10; }; XorShift128Plus2.prototype.getState = function () { return [this.s01, this.s00, this.s11, this.s10]; }; return XorShift128Plus2; })(); function fromState3(state) { var valid = state.length === 4; if (!valid) { throw new Error( 'The state must have been produced by a xorshift128plus RandomGenerator', ); } return new XorShift128Plus(state[0], state[1], state[2], state[3]); } var xorshift128plus = Object.assign( function (seed) { return new XorShift128Plus(-1, ~seed, seed | 0, 0); }, { fromState: fromState3 }, ); // ../../../node_modules/pure-rand/lib/esm/generator/XoroShiro.js var XoroShiro128Plus = (function () { function XoroShiro128Plus2(s01, s00, s11, s10) { this.s01 = s01; this.s00 = s00; this.s11 = s11; this.s10 = s10; } XoroShiro128Plus2.prototype.clone = function () { return new XoroShiro128Plus2(this.s01, this.s00, this.s11, this.s10); }; XoroShiro128Plus2.prototype.next = function () { var nextRng = new XoroShiro128Plus2(this.s01, this.s00, this.s11, this.s10); var out = nextRng.unsafeNext(); return [out, nextRng]; }; XoroShiro128Plus2.prototype.unsafeNext = function () { var out = (this.s00 + this.s10) | 0; var a0 = this.s10 ^ this.s00; var a1 = this.s11 ^ this.s01; var s00 = this.s00; var s01 = this.s01; this.s00 = (s00 << 24) ^ (s01 >>> 8) ^ a0 ^ (a0 << 16); this.s01 = (s01 << 24) ^ (s00 >>> 8) ^ a1 ^ ((a1 << 16) | (a0 >>> 16)); this.s10 = (a1 << 5) ^ (a0 >>> 27); this.s11 = (a0 << 5) ^ (a1 >>> 27); return out; }; XoroShiro128Plus2.prototype.jump = function () { var nextRng = new XoroShiro128Plus2(this.s01, this.s00, this.s11, this.s10); nextRng.unsafeJump(); return nextRng; }; XoroShiro128Plus2.prototype.unsafeJump = function () { var ns01 = 0; var ns00 = 0; var ns11 = 0; var ns10 = 0; var jump = [3639956645, 3750757012, 1261568508, 386426335]; for (var i = 0; i !== 4; ++i) { for (var mask = 1; mask; mask <<= 1) { if (jump[i] & mask) { ns01 ^= this.s01; ns00 ^= this.s00; ns11 ^= this.s11; ns10 ^= this.s10; } this.unsafeNext(); } } this.s01 = ns01; this.s00 = ns00; this.s11 = ns11; this.s10 = ns10; }; XoroShiro128Plus2.prototype.getState = function () { return [this.s01, this.s00, this.s11, this.s10]; }; return XoroShiro128Plus2; })(); function fromState4(state) { var valid = state.length === 4; if (!valid) { throw new Error( 'The state must have been produced by a xoroshiro128plus RandomGenerator', ); } return new XoroShiro128Plus(state[0], state[1], state[2], state[3]); } var xoroshiro128plus = Object.assign( function (seed) { return new XoroShiro128Plus(-1, ~seed, seed | 0, 0); }, { fromState: fromState4 }, ); // ../../../node_modules/pure-rand/lib/esm/distribution/internals/ArrayInt.js function addArrayIntToNew(arrayIntA, arrayIntB) { if (arrayIntA.sign !== arrayIntB.sign) { return substractArrayIntToNew(arrayIntA, { sign: -arrayIntB.sign, data: arrayIntB.data, }); } var data = []; var reminder = 0; var dataA = arrayIntA.data; var dataB = arrayIntB.data; for ( var indexA = dataA.length - 1, indexB = dataB.length - 1; indexA >= 0 || indexB >= 0; --indexA, --indexB ) { var vA = indexA >= 0 ? dataA[indexA] : 0; var vB = indexB >= 0 ? dataB[indexB] : 0; var current = vA + vB + reminder; data.push(current >>> 0); reminder = ~~(current / 4294967296); } if (reminder !== 0) { data.push(reminder); } return { sign: arrayIntA.sign, data: data.reverse() }; } function addOneToPositiveArrayInt(arrayInt) { arrayInt.sign = 1; var data = arrayInt.data; for (var index = data.length - 1; index >= 0; --index) { if (data[index] === 4294967295) { data[index] = 0; } else { data[index] += 1; return arrayInt; } } data.unshift(1); return arrayInt; } function isStrictlySmaller(dataA, dataB) { var maxLength = Math.max(dataA.length, dataB.length); for (var index = 0; index < maxLength; ++index) { var indexA = index + dataA.length - maxLength; var indexB = index + dataB.length - maxLength; var vA = indexA >= 0 ? dataA[indexA] : 0; var vB = indexB >= 0 ? dataB[indexB] : 0; if (vA < vB) return true; if (vA > vB) return false; } return false; } function substractArrayIntToNew(arrayIntA, arrayIntB) { if (arrayIntA.sign !== arrayIntB.sign) { return addArrayIntToNew(arrayIntA, { sign: -arrayIntB.sign, data: arrayIntB.data, }); } var dataA = arrayIntA.data; var dataB = arrayIntB.data; if (isStrictlySmaller(dataA, dataB)) { var out = substractArrayIntToNew(arrayIntB, arrayIntA); out.sign = -out.sign; return out; } var data = []; var reminder = 0; for ( var indexA = dataA.length - 1, indexB = dataB.length - 1; indexA >= 0 || indexB >= 0; --indexA, --indexB ) { var vA = indexA >= 0 ? dataA[indexA] : 0; var vB = indexB >= 0 ? dataB[indexB] : 0; var current = vA - vB - reminder; data.push(current >>> 0); reminder = current < 0 ? 1 : 0; } return { sign: arrayIntA.sign, data: data.reverse() }; } function trimArrayIntInplace(arrayInt) { var data = arrayInt.data; var firstNonZero = 0; for ( ; firstNonZero !== data.length && data[firstNonZero] === 0; ++firstNonZero ) {} if (firstNonZero === data.length) { arrayInt.sign = 1; arrayInt.data = [0]; return arrayInt; } data.splice(0, firstNonZero); return arrayInt; } function fromNumberToArrayInt64(out, n) { if (n < 0) { var posN = -n; out.sign = -1; out.data[0] = ~~(posN / 4294967296); out.data[1] = posN >>> 0; } else { out.sign = 1; out.data[0] = ~~(n / 4294967296); out.data[1] = n >>> 0; } return out; } function substractArrayInt64(out, arrayIntA, arrayIntB) { var lowA = arrayIntA.data[1]; var highA = arrayIntA.data[0]; var signA = arrayIntA.sign; var lowB = arrayIntB.data[1]; var highB = arrayIntB.data[0]; var signB = arrayIntB.sign; out.sign = 1; if (signA === 1 && signB === -1) { var low_1 = lowA + lowB; var high = highA + highB + (low_1 > 4294967295 ? 1 : 0); out.data[0] = high >>> 0; out.data[1] = low_1 >>> 0; return out; } var lowFirst = lowA; var highFirst = highA; var lowSecond = lowB; var highSecond = highB; if (signA === -1) { lowFirst = lowB; highFirst = highB; lowSecond = lowA; highSecond = highA; } var reminderLow = 0; var low = lowFirst - lowSecond; if (low < 0) { reminderLow = 1; low = low >>> 0; } out.data[0] = highFirst - highSecond - reminderLow; out.data[1] = low; return out; } // ../../../node_modules/pure-rand/lib/esm/distribution/internals/UnsafeUniformIntDistributionInternal.js function unsafeUniformIntDistributionInternal(rangeSize, rng) { var MaxAllowed = rangeSize > 2 ? ~~(4294967296 / rangeSize) * rangeSize : 4294967296; var deltaV = rng.unsafeNext() + 2147483648; while (deltaV >= MaxAllowed) { deltaV = rng.unsafeNext() + 2147483648; } return deltaV % rangeSize; } // ../../../node_modules/pure-rand/lib/esm/distribution/internals/UnsafeUniformArrayIntDistributionInternal.js function unsafeUniformArrayIntDistributionInternal(out, rangeSize, rng) { var rangeLength = rangeSize.length; while (true) { for (var index = 0; index !== rangeLength; ++index) { var indexRangeSize = index === 0 ? rangeSize[0] + 1 : 4294967296; var g = unsafeUniformIntDistributionInternal(indexRangeSize, rng); out[index] = g; } for (var index = 0; index !== rangeLength; ++index) { var current = out[index]; var currentInRange = rangeSize[index]; if (current < currentInRange) { return out; } else if (current > currentInRange) { break; } } } } // ../../../node_modules/pure-rand/lib/esm/distribution/UnsafeUniformArrayIntDistribution.js function unsafeUniformArrayIntDistribution(from, to, rng) { var rangeSize = trimArrayIntInplace( addOneToPositiveArrayInt(substractArrayIntToNew(to, from)), ); var emptyArrayIntData = rangeSize.data.slice(0); var g = unsafeUniformArrayIntDistributionInternal( emptyArrayIntData, rangeSize.data, rng, ); return trimArrayIntInplace(addArrayIntToNew({ sign: 1, data: g }, from)); } // ../../../node_modules/pure-rand/lib/esm/distribution/UniformArrayIntDistribution.js function uniformArrayIntDistribution(from, to, rng) { if (rng != null) { var nextRng = rng.clone(); return [unsafeUniformArrayIntDistribution(from, to, nextRng), nextRng]; } return function (rng2) { var nextRng2 = rng2.clone(); return [unsafeUniformArrayIntDistribution(from, to, nextRng2), nextRng2]; }; } // ../../../node_modules/pure-rand/lib/esm/distribution/UnsafeUniformBigIntDistribution.js var SBigInt2 = typeof BigInt !== 'undefined' ? BigInt : void 0; function unsafeUniformBigIntDistribution(from, to, rng) { var diff = to - from + SBigInt2(1); var MinRng = SBigInt2(-2147483648); var NumValues = SBigInt2(4294967296); var FinalNumValues = NumValues; var NumIterations = 1; while (FinalNumValues < diff) { FinalNumValues *= NumValues; ++NumIterations; } var MaxAcceptedRandom = FinalNumValues - (FinalNumValues % diff); while (true) { var value = SBigInt2(0); for (var num = 0; num !== NumIterations; ++num) { var out = rng.unsafeNext(); value = NumValues * value + (SBigInt2(out) - MinRng); } if (value < MaxAcceptedRandom) { var inDiff = value % diff; return inDiff + from; } } } // ../../../node_modules/pure-rand/lib/esm/distribution/UniformBigIntDistribution.js function uniformBigIntDistribution(from, to, rng) { if (rng != null) { var nextRng = rng.clone(); return [unsafeUniformBigIntDistribution(from, to, nextRng), nextRng]; } return function (rng2) { var nextRng2 = rng2.clone(); return [unsafeUniformBigIntDistribution(from, to, nextRng2), nextRng2]; }; } // ../../../node_modules/pure-rand/lib/esm/distribution/UnsafeUniformIntDistribution.js var safeNumberMaxSafeInteger = Number.MAX_SAFE_INTEGER; var sharedA = { sign: 1, data: [0, 0] }; var sharedB = { sign: 1, data: [0, 0] }; var sharedC = { sign: 1, data: [0, 0] }; var sharedData = [0, 0]; function uniformLargeIntInternal(from, to, rangeSize, rng) { var rangeSizeArrayIntValue = rangeSize <= safeNumberMaxSafeInteger ? fromNumberToArrayInt64(sharedC, rangeSize) : substractArrayInt64( sharedC, fromNumberToArrayInt64(sharedA, to), fromNumberToArrayInt64(sharedB, from), ); if (rangeSizeArrayIntValue.data[1] === 4294967295) { rangeSizeArrayIntValue.data[0] += 1; rangeSizeArrayIntValue.data[1] = 0; } else { rangeSizeArrayIntValue.data[1] += 1; } unsafeUniformArrayIntDistributionInternal( sharedData, rangeSizeArrayIntValue.data, rng, ); return sharedData[0] * 4294967296 + sharedData[1] + from; } function unsafeUniformIntDistribution(from, to, rng) { var rangeSize = to - from; if (rangeSize <= 4294967295) { var g = unsafeUniformIntDistributionInternal(rangeSize + 1, rng); return g + from; } return uniformLargeIntInternal(from, to, rangeSize, rng); } // ../../../node_modules/pure-rand/lib/esm/distribution/UniformIntDistribution.js function uniformIntDistribution(from, to, rng) { if (rng != null) { var nextRng = rng.clone(); return [unsafeUniformIntDistribution(from, to, nextRng), nextRng]; } return function (rng2) { var nextRng2 = rng2.clone(); return [unsafeUniformIntDistribution(from, to, nextRng2), nextRng2]; }; } // ../../../node_modules/pure-rand/lib/esm/pure-rand-default.js var __type = 'module'; var __version = '6.1.0'; var __commitHash = 'a413dd2b721516be2ef29adffb515c5ae67bfbad'; // ../../../node_modules/pure-rand/lib/esm/pure-rand.js var pure_rand_default = pure_rand_default_exports; // ../../../node_modules/fast-check/lib/esm/check/runner/configuration/VerbosityLevel.js var VerbosityLevel; (function (VerbosityLevel2) { VerbosityLevel2[(VerbosityLevel2['None'] = 0)] = 'None'; VerbosityLevel2[(VerbosityLevel2['Verbose'] = 1)] = 'Verbose'; VerbosityLevel2[(VerbosityLevel2['VeryVerbose'] = 2)] = 'VeryVerbose'; })(VerbosityLevel || (VerbosityLevel = {})); // ../../../node_modules/fast-check/lib/esm/check/runner/configuration/QualifiedParameters.js var safeDateNow = Date.now; var safeMathMin = Math.min; var safeMathRandom = Math.random; var QualifiedParameters = class _QualifiedParameters { constructor(op) { const p = op || {}; this.seed = _QualifiedParameters.readSeed(p); this.randomType = _QualifiedParameters.readRandomType(p); this.numRuns = _QualifiedParameters.readNumRuns(p); this.verbose = _QualifiedParameters.readVerbose(p); this.maxSkipsPerRun = _QualifiedParameters.readOrDefault( p, 'maxSkipsPerRun', 100, ); this.timeout = _QualifiedParameters.safeTimeout( _QualifiedParameters.readOrDefault(p, 'timeout', null), ); this.skipAllAfterTimeLimit = _QualifiedParameters.safeTimeout( _QualifiedParameters.readOrDefault(p, 'skipAllAfterTimeLimit', null), ); this.interruptAfterTimeLimit = _QualifiedParameters.safeTimeout( _QualifiedParameters.readOrDefault(p, 'interruptAfterTimeLimit', null), ); this.markInterruptAsFailure = _QualifiedParameters.readBoolean( p, 'markInterruptAsFailure', ); this.skipEqualValues = _QualifiedParameters.readBoolean( p, 'skipEqualValues', ); this.ignoreEqualValues = _QualifiedParameters.readBoolean( p, 'ignoreEqualValues', ); this.logger = _QualifiedParameters.readOrDefault(p, 'logger', (v) => { console.log(v); }); this.path = _QualifiedParameters.readOrDefault(p, 'path', ''); this.unbiased = _QualifiedParameters.readBoolean(p, 'unbiased'); this.examples = _QualifiedParameters.readOrDefault(p, 'examples', []); this.endOnFailure = _QualifiedParameters.readBoolean(p, 'endOnFailure'); this.reporter = _QualifiedParameters.readOrDefault(p, 'reporter', null); this.asyncReporter = _QualifiedParameters.readOrDefault( p, 'asyncReporter', null, ); this.errorWithCause = _QualifiedParameters.readBoolean(p, 'errorWithCause'); } toParameters() { const orUndefined = (value) => (value !== null ? value : void 0); const parameters = { seed: this.seed, randomType: this.randomType, numRuns: this.numRuns, maxSkipsPerRun: this.maxSkipsPerRun, timeout: orUndefined(this.timeout), skipAllAfterTimeLimit: orUndefined(this.skipAllAfterTimeLimit), interruptAfterTimeLimit: orUndefined(this.interruptAfterTimeLimit), markInterruptAsFailure: this.markInterruptAsFailure, skipEqualValues: this.skipEqualValues, ignoreEqualValues: this.ignoreEqualValues, path: this.path, logger: this.logger, unbiased: this.unbiased, verbose: this.verbose, examples: this.examples, endOnFailure: this.endOnFailure, reporter: orUndefined(this.reporter), asyncReporter: orUndefined(this.asyncReporter), errorWithCause: this.errorWithCause, }; return parameters; } static read(op) { return new _QualifiedParameters(op); } }; QualifiedParameters.createQualifiedRandomGenerator = (random) => { return (seed) => { const rng = random(seed); if (rng.unsafeJump === void 0) { rng.unsafeJump = () => unsafeSkipN(rng, 42); } return rng; }; }; QualifiedParameters.readSeed = (p) => { if (p.seed == null) return safeDateNow() ^ (safeMathRandom() * 4294967296); const seed32 = p.seed | 0; if (p.seed === seed32) return seed32; const gap = p.seed - seed32; return seed32 ^ (gap * 4294967296); }; QualifiedParameters.readRandomType = (p) => { if (p.randomType == null) return pure_rand_default.xorshift128plus; if (typeof p.randomType === 'string') { switch (p.randomType) { case 'mersenne': return QualifiedParameters.createQualifiedRandomGenerator( pure_rand_default.mersenne, ); case 'congruential': case 'congruential32': return QualifiedParameters.createQualifiedRandomGenerator( pure_rand_default.congruential32, ); case 'xorshift128plus': return pure_rand_default.xorshift128plus; case 'xoroshiro128plus': return pure_rand_default.xoroshiro128plus; default: throw new Error(`Invalid random specified: '${p.randomType}'`); } } const mrng = p.randomType(0); if ('min' in mrng && mrng.min !== -2147483648) { throw new Error( `Invalid random number generator: min must equal -0x80000000, got ${String(mrng.min)}`, ); } if ('max' in mrng && mrng.max !== 2147483647) { throw new Error( `Invalid random number generator: max must equal 0x7fffffff, got ${String(mrng.max)}`, ); } if ('unsafeJump' in mrng) { return p.randomType; } return QualifiedParameters.createQualifiedRandomGenerator(p.randomType); }; QualifiedParameters.readNumRuns = (p) => { const defaultValue = 100; if (p.numRuns != null) return p.numRuns; if (p.num_runs != null) return p.num_runs; return defaultValue; }; QualifiedParameters.readVerbose = (p) => { if (p.verbose == null) return VerbosityLevel.None; if (typeof p.verbose === 'boolean') { return p.verbose === true ? VerbosityLevel.Verbose : VerbosityLevel.None; } if (p.verbose <= VerbosityLevel.None) { return VerbosityLevel.None; } if (p.verbose >= VerbosityLevel.VeryVerbose) { return VerbosityLevel.VeryVerbose; } return p.verbose | 0; }; QualifiedParameters.readBoolean = (p, key) => p[key] === true; QualifiedParameters.readOrDefault = (p, key, defaultValue) => { const value = p[key]; return value != null ? value : defaultValue; }; QualifiedParameters.safeTimeout = (value) => { if (value === null) { return null; } return safeMathMin(value, 2147483647); }; // ../../../node_modules/fast-check/lib/esm/check/property/SkipAfterProperty.js function interruptAfter(timeMs, setTimeoutSafe, clearTimeoutSafe) { let timeoutHandle = null; const promise = new Promise((resolve) => { timeoutHandle = setTimeoutSafe(() => { const preconditionFailure = new PreconditionFailure(true); resolve(preconditionFailure); }, timeMs); }); return { clear: () => clearTimeoutSafe(timeoutHandle), promise, }; } var SkipAfterProperty = class { constructor( property2, getTime, timeLimit, interruptExecution, setTimeoutSafe, clearTimeoutSafe, ) { this.property = property2; this.getTime = getTime; this.interruptExecution = interruptExecution; this.setTimeoutSafe = setTimeoutSafe; this.clearTimeoutSafe = clearTimeoutSafe; this.skipAfterTime = this.getTime() + timeLimit; if ( this.property.runBeforeEach !== void 0 && this.property.runAfterEach !== void 0 ) { this.runBeforeEach = () => this.property.runBeforeEach(); this.runAfterEach = () => this.property.runAfterEach(); } } isAsync() { return this.property.isAsync(); } generate(mrng, runId) { return this.property.generate(mrng, runId); } shrink(value) { return this.property.shrink(value); } run(v, dontRunHook) { const remainingTime = this.skipAfterTime - this.getTime(); if (remainingTime <= 0) { const preconditionFailure = new PreconditionFailure( this.interruptExecution, ); if (this.isAsync()) { return Promise.resolve(preconditionFailure); } else { return preconditionFailure; } } if (this.interruptExecution && this.isAsync()) { const t = interruptAfter( remainingTime, this.setTimeoutSafe, this.clearTimeoutSafe, ); const propRun = Promise.race([ this.property.run(v, dontRunHook), t.promise, ]); propRun.then(t.clear, t.clear); return propRun; } return this.property.run(v, dontRunHook); } }; // ../../../node_modules/fast-check/lib/esm/check/property/TimeoutProperty.js var timeoutAfter = (timeMs, setTimeoutSafe, clearTimeoutSafe) => { let timeoutHandle = null; const promise = new Promise((resolve) => { timeoutHandle = setTimeoutSafe(() => { resolve({ error: new SError( `Property timeout: exceeded limit of ${timeMs} milliseconds`, ), errorMessage: `Property timeout: exceeded limit of ${timeMs} milliseconds`, }); }, timeMs); }); return { clear: () => clearTimeoutSafe(timeoutHandle), promise, }; }; var TimeoutProperty = class { constructor(property2, timeMs, setTimeoutSafe, clearTimeoutSafe) { this.property = property2; this.timeMs = timeMs; this.setTimeoutSafe = setTimeoutSafe; this.clearTimeoutSafe = clearTimeoutSafe; if ( this.property.runBeforeEach !== void 0 && this.property.runAfterEach !== void 0 ) { this.runBeforeEach = () => Promise.resolve(this.property.runBeforeEach()); this.runAfterEach = () => Promise.resolve(this.property.runAfterEach()); } } isAsync() { return true; } generate(mrng, runId) { return this.property.generate(mrng, runId); } shrink(value) { return this.property.shrink(value); } async run(v, dontRunHook) { const t = timeoutAfter( this.timeMs, this.setTimeoutSafe, this.clearTimeoutSafe, ); const propRun = Promise.race([ this.property.run(v, dontRunHook), t.promise, ]); propRun.then(t.clear, t.clear); return propRun; } }; // ../../../node_modules/fast-check/lib/esm/check/property/UnbiasedProperty.js var UnbiasedProperty = class { constructor(property2) { this.property = property2; if ( this.property.runBeforeEach !== void 0 && this.property.runAfterEach !== void 0 ) { this.runBeforeEach = () => this.property.runBeforeEach(); this.runAfterEach = () => this.property.runAfterEach(); } } isAsync() { return this.property.isAsync(); } generate(mrng, _runId) { return this.property.generate(mrng, void 0); } shrink(value) { return this.property.shrink(value); } run(v, dontRunHook) { return this.property.run(v, dontRunHook); } }; // ../../../node_modules/fast-check/lib/esm/utils/stringify.js var safeArrayFrom = Array.from; var safeBufferIsBuffer = typeof Buffer !== 'undefined' ? Buffer.isBuffer : void 0; var safeJsonStringify = JSON.stringify; var safeNumberIsNaN = Number.isNaN; var safeObjectKeys = Object.keys; var safeObjectGetOwnPropertySymbols = Object.getOwnPropertySymbols; var safeObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var safeObjectGetPrototypeOf = Object.getPrototypeOf; var safeNegativeInfinity = Number.NEGATIVE_INFINITY; var safePositiveInfinity = Number.POSITIVE_INFINITY; var toStringMethod = Symbol('fast-check/toStringMethod'); function hasToStringMethod(instance) { return ( instance !== null && (typeof instance === 'object' || typeof instance === 'function') && toStringMethod in instance && typeof instance[toStringMethod] === 'function' ); } var asyncToStringMethod = Symbol('fast-check/asyncToStringMethod'); function hasAsyncToStringMethod(instance) { return ( instance !== null && (typeof instance === 'object' || typeof instance === 'function') && asyncToStringMethod in instance && typeof instance[asyncToStringMethod] === 'function' ); } var findSymbolNameRegex = /^Symbol\((.*)\)$/; function getSymbolDescription(s) { if (s.description !== void 0) return s.description; const m = findSymbolNameRegex.exec(SString(s)); return m && m[1].length ? m[1] : null; } function stringifyNumber(numValue) { switch (numValue) { case 0: return 1 / numValue === safeNegativeInfinity ? '-0' : '0'; case safeNegativeInfinity: return 'Number.NEGATIVE_INFINITY'; case safePositiveInfinity: return 'Number.POSITIVE_INFINITY'; default: return numValue === numValue ? SString(numValue) : 'Number.NaN'; } } function isSparseArray(arr) { let previousNumberedIndex = -1; for (const index in arr) { const numberedIndex = Number(index); if (numberedIndex !== previousNumberedIndex + 1) return true; previousNumberedIndex = numberedIndex; } return previousNumberedIndex + 1 !== arr.length; } function stringifyInternal(value, previousValues, getAsyncContent) { const currentValues = [...previousValues, value]; if (typeof value === 'object') { if (safeIndexOf(previousValues, value) !== -1) { return '[cyclic]'; } } if (hasAsyncToStringMethod(value)) { const content = getAsyncContent(value); if (content.state === 'fulfilled') { return content.value; } } if (hasToStringMethod(value)) { try { return value[toStringMethod](); } catch (err) {} } switch (safeToString(value)) { case '[object Array]': { const arr = value; if (arr.length >= 50 && isSparseArray(arr)) { const assignments = []; for (const index in arr) { if (!safeNumberIsNaN(Number(index))) safePush( assignments, `${index}:${stringifyInternal(arr[index], currentValues, getAsyncContent)}`, ); } return assignments.length !== 0 ? `Object.assign(Array(${arr.length}),{${safeJoin(assignments, ',')}})` : `Array(${arr.length})`; } const stringifiedArray = safeJoin( safeMap(arr, (v) => stringifyInternal(v, currentValues, getAsyncContent), ), ',', ); return arr.length === 0 || arr.length - 1 in arr ? `[${stringifiedArray}]` : `[${stringifiedArray},]`; } case '[object BigInt]': return `${value}n`; case '[object Boolean]': { const unboxedToString = value == true ? 'true' : 'false'; return typeof value === 'boolean' ? unboxedToString : `new Boolean(${unboxedToString})`; } case '[object Date]': { const d = value; return safeNumberIsNaN(safeGetTime(d)) ? `new Date(NaN)` : `new Date(${safeJsonStringify(safeToISOString(d))})`; } case '[object Map]': return `new Map(${stringifyInternal(Array.from(value), currentValues, getAsyncContent)})`; case '[object Null]': return `null`; case '[object Number]': return typeof value === 'number' ? stringifyNumber(value) : `new Number(${stringifyNumber(Number(value))})`; case '[object Object]': { try { const toStringAccessor = value.toString; if ( typeof toStringAccessor === 'function' && toStringAccessor !== Object.prototype.toString ) { return value.toString(); } } catch (err) { return '[object Object]'; } const mapper = (k) => `${k === '__proto__' ? '["__proto__"]' : typeof k === 'symbol' ? `[${stringifyInternal(k, currentValues, getAsyncContent)}]` : safeJsonStringify(k)}:${stringifyInternal(value[k], currentValues, getAsyncContent)}`; const stringifiedProperties = [ ...safeMap(safeObjectKeys(value), mapper), ...safeMap( safeFilter(safeObjectGetOwnPropertySymbols(value), (s) => { const descriptor = safeObjectGetOwnPropertyDescriptor(value, s); return descriptor && descriptor.enumerable; }), mapper, ), ]; const rawRepr = '{' + safeJoin(stringifiedProperties, ',') + '}'; if (safeObjectGetPrototypeOf(value) === null) { return rawRepr === '{}' ? 'Object.create(null)' : `Object.assign(Object.create(null),${rawRepr})`; } return rawRepr; } case '[object Set]': return `new Set(${stringifyInternal(Array.from(value), currentValues, getAsyncContent)})`; case '[object String]': return typeof value === 'string' ? safeJsonStringify(value) : `new String(${safeJsonStringify(value)})`; case '[object Symbol]': { const s = value; if (Symbol.keyFor(s) !== void 0) { return `Symbol.for(${safeJsonStringify(Symbol.keyFor(s))})`; } const desc = getSymbolDescription(s); if (desc === null) { return 'Symbol()'; } const knownSymbol = desc.startsWith('Symbol.') && Symbol[desc.substring(7)]; return s === knownSymbol ? desc : `Symbol(${safeJsonStringify(desc)})`; } case '[object Promise]': { const promiseContent = getAsyncContent(value); switch (promiseContent.state) { case 'fulfilled': return `Promise.resolve(${stringifyInternal(promiseContent.value, currentValues, getAsyncContent)})`; case 'rejected': return `Promise.reject(${stringifyInternal(promiseContent.value, currentValues, getAsyncContent)})`; case 'pending': return `new Promise(() => {/*pending*/})`; case 'unknown': default: return `new Promise(() => {/*unknown*/})`; } } case '[object Error]': if (value instanceof Error) { return `new Error(${stringifyInternal(value.message, currentValues, getAsyncContent)})`; } break; case '[object Undefined]': return `undefined`; case '[object Int8Array]': case '[object Uint8Array]': case '[object Uint8ClampedArray]': case '[object Int16Array]': case '[object Uint16Array]': case '[object Int32Array]': case '[object Uint32Array]': case '[object Float32Array]': case '[object Float64Array]': case '[object BigInt64Array]': case '[object BigUint64Array]': { if ( typeof safeBufferIsBuffer === 'function' && safeBufferIsBuffer(value) ) { return `Buffer.from(${stringifyInternal(safeArrayFrom(value.values()), currentValues, getAsyncContent)})`; } const valuePrototype = safeObjectGetPrototypeOf(value); const className = valuePrototype && valuePrototype.constructor && valuePrototype.constructor.name; if (typeof className === 'string') { const typedArray2 = value; const valuesFromTypedArr = typedArray2.values(); return `${className}.from(${stringifyInternal(safeArrayFrom(valuesFromTypedArr), currentValues, getAsyncContent)})`; } break; } } try { return value.toString(); } catch (_a) { return safeToString(value); } } function stringify(value) { return stringifyInternal(value, [], () => ({ state: 'unknown', value: void 0, })); } function possiblyAsyncStringify(value) { const stillPendingMarker = Symbol(); const pendingPromisesForCache = []; const cache = /* @__PURE__ */ new Map(); function createDelay0() { let handleId = null; const cancel = () => { if (handleId !== null) { clearTimeout(handleId); } }; const delay = new Promise((resolve) => { handleId = setTimeout(() => { handleId = null; resolve(stillPendingMarker); }, 0); }); return { delay, cancel }; } const unknownState = { state: 'unknown', value: void 0 }; const getAsyncContent = function getAsyncContent2(data) { const cacheKey = data; if (cache.has(cacheKey)) { return cache.get(cacheKey); } const delay0 = createDelay0(); const p = asyncToStringMethod in data ? Promise.resolve().then(() => data[asyncToStringMethod]()) : data; p.catch(() => {}); pendingPromisesForCache.push( Promise.race([p, delay0.delay]).then( (successValue) => { if (successValue === stillPendingMarker) cache.set(cacheKey, { state: 'pending', value: void 0 }); else cache.set(cacheKey, { state: 'fulfilled', value: successValue }); delay0.cancel(); }, (errorValue) => { cache.set(cacheKey, { state: 'rejected', value: errorValue }); delay0.cancel(); }, ), ); cache.set(cacheKey, unknownState); return unknownState; }; function loop() { const stringifiedValue = stringifyInternal(value, [], getAsyncContent); if (pendingPromisesForCache.length === 0) { return stringifiedValue; } return Promise.all(pendingPromisesForCache.splice(0)).then(loop); } return loop(); } async function asyncStringify(value) { return Promise.resolve(possiblyAsyncStringify(value)); } // ../../../node_modules/fast-check/lib/esm/check/property/IgnoreEqualValuesProperty.js function fromSyncCached(cachedValue) { return cachedValue === null ? new PreconditionFailure() : cachedValue; } function fromCached(...data) { if (data[1]) return data[0].then(fromSyncCached); return fromSyncCached(data[0]); } function fromCachedUnsafe(cachedValue, isAsync) { return fromCached(cachedValue, isAsync); } var IgnoreEqualValuesProperty = class { constructor(property2, skipRuns) { this.property = property2; this.skipRuns = skipRuns; this.coveredCases = /* @__PURE__ */ new Map(); if ( this.property.runBeforeEach !== void 0 && this.property.runAfterEach !== void 0 ) { this.runBeforeEach = () => this.property.runBeforeEach(); this.runAfterEach = () => this.property.runAfterEach(); } } isAsync() { return this.property.isAsync(); } generate(mrng, runId) { return this.property.generate(mrng, runId); } shrink(value) { return this.property.shrink(value); } run(v, dontRunHook) { const stringifiedValue = stringify(v); if (this.coveredCases.has(stringifiedValue)) { const lastOutput = this.coveredCases.get(stringifiedValue); if (!this.skipRuns) { return lastOutput; } return fromCachedUnsafe(lastOutput, this.property.isAsync()); } const out = this.property.run(v, dontRunHook); this.coveredCases.set(stringifiedValue, out); return out; } }; // ../../../node_modules/fast-check/lib/esm/check/runner/DecorateProperty.js var safeDateNow2 = Date.now; var safeSetTimeout = setTimeout; var safeClearTimeout = clearTimeout; function decorateProperty(rawProperty, qParams) { let prop = rawProperty; if (rawProperty.isAsync() && qParams.timeout != null) { prop = new TimeoutProperty( prop, qParams.timeout, safeSetTimeout, safeClearTimeout, ); } if (qParams.unbiased) { prop = new UnbiasedProperty(prop); } if (qParams.skipAllAfterTimeLimit != null) { prop = new SkipAfterProperty( prop, safeDateNow2, qParams.skipAllAfterTimeLimit, false, safeSetTimeout, safeClearTimeout, ); } if (qParams.interruptAfterTimeLimit != null) { prop = new SkipAfterProperty( prop, safeDateNow2, qParams.interruptAfterTimeLimit, true, safeSetTimeout, safeClearTimeout, ); } if (qParams.skipEqualValues) { prop = new IgnoreEqualValuesProperty(prop, true); } if (qParams.ignoreEqualValues) { prop = new IgnoreEqualValuesProperty(prop, false); } return prop; } // ../../../node_modules/fast-check/lib/esm/check/runner/reporter/ExecutionStatus.js var ExecutionStatus; (function (ExecutionStatus2) { ExecutionStatus2[(ExecutionStatus2['Success'] = 0)] = 'Success'; ExecutionStatus2[(ExecutionStatus2['Skipped'] = -1)] = 'Skipped'; ExecutionStatus2[(ExecutionStatus2['Failure'] = 1)] = 'Failure'; })(ExecutionStatus || (ExecutionStatus = {})); // ../../../node_modules/fast-check/lib/esm/check/runner/reporter/RunExecution.js var RunExecution = class _RunExecution { constructor(verbosity, interruptedAsFailure) { this.verbosity = verbosity; this.interruptedAsFailure = interruptedAsFailure; this.isSuccess = () => this.pathToFailure == null; this.firstFailure = () => this.pathToFailure ? +safeSplit(this.pathToFailure, ':')[0] : -1; this.numShrinks = () => this.pathToFailure ? safeSplit(this.pathToFailure, ':').length - 1 : 0; this.rootExecutionTrees = []; this.currentLevelExecutionTrees = this.rootExecutionTrees; this.failure = null; this.numSkips = 0; this.numSuccesses = 0; this.interrupted = false; } appendExecutionTree(status, value) { const currentTree = { status, value, children: [] }; this.currentLevelExecutionTrees.push(currentTree); return currentTree; } fail(value, id, failure) { if (this.verbosity >= VerbosityLevel.Verbose) { const currentTree = this.appendExecutionTree( ExecutionStatus.Failure, value, ); this.currentLevelExecutionTrees = currentTree.children; } if (this.pathToFailure == null) this.pathToFailure = `${id}`; else this.pathToFailure += `:${id}`; this.value = value; this.failure = failure; } skip(value) { if (this.verbosity >= VerbosityLevel.VeryVerbose) { this.appendExecutionTree(ExecutionStatus.Skipped, value); } if (this.pathToFailure == null) { ++this.numSkips; } } success(value) { if (this.verbosity >= VerbosityLevel.VeryVerbose) { this.appendExecutionTree(ExecutionStatus.Success, value); } if (this.pathToFailure == null) { ++this.numSuccesses; } } interrupt() { this.interrupted = true; } extractFailures() { if (this.isSuccess()) { return []; } const failures = []; let cursor = this.rootExecutionTrees; while ( cursor.length > 0 && cursor[cursor.length - 1].status === ExecutionStatus.Failure ) { const failureTree = cursor[cursor.length - 1]; failures.push(failureTree.value); cursor = failureTree.children; } return failures; } toRunDetails(seed, basePath, maxSkips, qParams) { if (!this.isSuccess()) { return { failed: true, interrupted: this.interrupted, numRuns: this.firstFailure() + 1 - this.numSkips, numSkips: this.numSkips, numShrinks: this.numShrinks(), seed, counterexample: this.value, counterexamplePath: _RunExecution.mergePaths( basePath, this.pathToFailure, ), error: this.failure.errorMessage, errorInstance: this.failure.error, failures: this.extractFailures(), executionSummary: this.rootExecutionTrees, verbose: this.verbosity, runConfiguration: qParams.toParameters(), }; } const considerInterruptedAsFailure = this.interruptedAsFailure || this.numSuccesses === 0; const failed = this.numSkips > maxSkips || (this.interrupted && considerInterruptedAsFailure); const out = { failed, interrupted: this.interrupted, numRuns: this.numSuccesses, numSkips: this.numSkips, numShrinks: 0, seed, counterexample: null, counterexamplePath: null, error: null, errorInstance: null, failures: [], executionSummary: this.rootExecutionTrees, verbose: this.verbosity, runConfiguration: qParams.toParameters(), }; return out; } }; RunExecution.mergePaths = (offsetPath, path) => { if (offsetPath.length === 0) return path; const offsetItems = offsetPath.split(':'); const remainingItems = path.split(':'); const middle = +offsetItems[offsetItems.length - 1] + +remainingItems[0]; return [ ...offsetItems.slice(0, offsetItems.length - 1), `${middle}`, ...remainingItems.slice(1), ].join(':'); }; // ../../../node_modules/fast-check/lib/esm/check/runner/RunnerIterator.js var RunnerIterator = class { constructor(sourceValues, shrink, verbose, interruptedAsFailure) { this.sourceValues = sourceValues; this.shrink = shrink; this.runExecution = new RunExecution(verbose, interruptedAsFailure); this.currentIdx = -1; this.nextValues = sourceValues; } [Symbol.iterator]() { return this; } next() { const nextValue = this.nextValues.next(); if (nextValue.done || this.runExecution.interrupted) { return { done: true, value: void 0 }; } this.currentValue = nextValue.value; ++this.currentIdx; return { done: false, value: nextValue.value.value_ }; } handleResult(result) { if ( result != null && typeof result === 'object' && !PreconditionFailure.isFailure(result) ) { this.runExecution.fail(this.currentValue.value_, this.currentIdx, result); this.currentIdx = -1; this.nextValues = this.shrink(this.currentValue); } else if (result != null) { if (!result.interruptExecution) { this.runExecution.skip(this.currentValue.value_); this.sourceValues.skippedOne(); } else { this.runExecution.interrupt(); } } else { this.runExecution.success(this.currentValue.value_); } } }; // ../../../node_modules/fast-check/lib/esm/check/runner/SourceValuesIterator.js var SourceValuesIterator = class { constructor(initialValues, maxInitialIterations, remainingSkips) { this.initialValues = initialValues; this.maxInitialIterations = maxInitialIterations; this.remainingSkips = remainingSkips; } [Symbol.iterator]() { return this; } next() { if (--this.maxInitialIterations !== -1 && this.remainingSkips >= 0) { const n = this.initialValues.next(); if (!n.done) return { value: n.value, done: false }; } return { value: void 0, done: true }; } skippedOne() { --this.remainingSkips; ++this.maxInitialIterations; } }; // ../../../node_modules/fast-check/lib/esm/random/generator/Random.js var Random = class _Random { constructor(sourceRng) { this.internalRng = sourceRng.clone(); } clone() { return new _Random(this.internalRng); } next(bits) { return unsafeUniformIntDistribution(0, (1 << bits) - 1, this.internalRng); } nextBoolean() { return unsafeUniformIntDistribution(0, 1, this.internalRng) == 1; } nextInt(min, max) { return unsafeUniformIntDistribution( min == null ? _Random.MIN_INT : min, max == null ? _Random.MAX_INT : max, this.internalRng, ); } nextBigInt(min, max) { return unsafeUniformBigIntDistribution(min, max, this.internalRng); } nextArrayInt(min, max) { return unsafeUniformArrayIntDistribution(min, max, this.internalRng); } nextDouble() { const a = this.next(26); const b = this.next(27); return (a * _Random.DBL_FACTOR + b) * _Random.DBL_DIVISOR; } getState() { if ( 'getState' in this.internalRng && typeof this.internalRng.getState === 'function' ) { return this.internalRng.getState(); } return void 0; } }; Random.MIN_INT = 2147483648 | 0; Random.MAX_INT = 2147483647 | 0; Random.DBL_FACTOR = Math.pow(2, 27); Random.DBL_DIVISOR = Math.pow(2, -53); // ../../../node_modules/fast-check/lib/esm/check/runner/Tosser.js function tossNext(generator, rng, index) { rng.unsafeJump(); return generator.generate(new Random(rng), index); } function* toss(generator, seed, random, examples) { for (let idx = 0; idx !== examples.length; ++idx) { yield new Value(examples[idx], void 0); } for (let idx = 0, rng = random(seed); ; ++idx) { yield tossNext(generator, rng, idx); } } function lazyGenerate(generator, rng, idx) { return () => generator.generate(new Random(rng), idx); } function* lazyToss(generator, seed, random, examples) { yield* safeMap(examples, (e) => () => new Value(e, void 0)); let idx = 0; let rng = random(seed); for (;;) { rng = rng.jump ? rng.jump() : skipN(rng, 42); yield lazyGenerate(generator, rng, idx++); } } // ../../../node_modules/fast-check/lib/esm/check/runner/utils/PathWalker.js function produce(producer) { return producer(); } function pathWalk(path, initialProducers, shrink) { const producers = initialProducers; const segments = path.split(':').map((text) => +text); if (segments.length === 0) { return producers.map(produce); } if (!segments.every((v) => !Number.isNaN(v))) { throw new Error(`Unable to replay, got invalid path=${path}`); } let values = producers.drop(segments[0]).map(produce); for (const s of segments.slice(1)) { const valueToShrink = values.getNthOrLast(0); if (valueToShrink === null) { throw new Error(`Unable to replay, got wrong path=${path}`); } values = shrink(valueToShrink).drop(s); } return values; } // ../../../node_modules/fast-check/lib/esm/check/runner/utils/RunDetailsFormatter.js var safeObjectAssign2 = Object.assign; function formatHints(hints) { if (hints.length === 1) { return `Hint: ${hints[0]}`; } return hints.map((h2, idx) => `Hint (${idx + 1}): ${h2}`).join('\n'); } function formatFailures(failures, stringifyOne) { return `Encountered failures were: - ${failures.map(stringifyOne).join('\n- ')}`; } function formatExecutionSummary(executionTrees, stringifyOne) { const summaryLines = []; const remainingTreesAndDepth = []; for (const tree of executionTrees.slice().reverse()) { remainingTreesAndDepth.push({ depth: 1, tree }); } while (remainingTreesAndDepth.length !== 0) { const currentTreeAndDepth = remainingTreesAndDepth.pop(); const currentTree = currentTreeAndDepth.tree; const currentDepth = currentTreeAndDepth.depth; const statusIcon = currentTree.status === ExecutionStatus.Success ? '\x1B[32m\u221A\x1B[0m' : currentTree.status === ExecutionStatus.Failure ? '\x1B[31m\xD7\x1B[0m' : '\x1B[33m!\x1B[0m'; const leftPadding = Array(currentDepth).join('. '); summaryLines.push( `${leftPadding}${statusIcon} ${stringifyOne(currentTree.value)}`, ); for (const tree of currentTree.children.slice().reverse()) { remainingTreesAndDepth.push({ depth: currentDepth + 1, tree }); } } return `Execution summary: ${summaryLines.join('\n')}`; } function preFormatTooManySkipped(out, stringifyOne) { const message = `Failed to run property, too many pre-condition failures encountered { seed: ${out.seed} } Ran ${out.numRuns} time(s) Skipped ${out.numSkips} time(s)`; let details = null; const hints = [ 'Try to reduce the number of rejected values by combining map, flatMap and built-in arbitraries', 'Increase failure tolerance by setting maxSkipsPerRun to an higher value', ]; if (out.verbose >= VerbosityLevel.VeryVerbose) { details = formatExecutionSummary(out.executionSummary, stringifyOne); } else { safePush( hints, 'Enable verbose mode at level VeryVerbose in order to check all generated values and their associated status', ); } return { message, details, hints }; } function preFormatFailure(out, stringifyOne) { const noErrorInMessage = out.runConfiguration.errorWithCause; const messageErrorPart = noErrorInMessage ? '' : ` Got ${safeReplace(out.error, /^Error: /, 'error: ')}`; const message = `Property failed after ${out.numRuns} tests { seed: ${out.seed}, path: "${out.counterexamplePath}", endOnFailure: true } Counterexample: ${stringifyOne(out.counterexample)} Shrunk ${out.numShrinks} time(s)${messageErrorPart}`; let details = null; const hints = []; if (out.verbose >= VerbosityLevel.VeryVerbose) { details = formatExecutionSummary(out.executionSummary, stringifyOne); } else if (out.verbose === VerbosityLevel.Verbose) { details = formatFailures(out.failures, stringifyOne); } else { safePush( hints, 'Enable verbose mode in order to have the list of all failing values encountered during the run', ); } return { message, details, hints }; } function preFormatEarlyInterrupted(out, stringifyOne) { const message = `Property interrupted after ${out.numRuns} tests { seed: ${out.seed} }`; let details = null; const hints = []; if (out.verbose >= VerbosityLevel.VeryVerbose) { details = formatExecutionSummary(out.executionSummary, stringifyOne); } else { safePush( hints, 'Enable verbose mode at level VeryVerbose in order to check all generated values and their associated status', ); } return { message, details, hints }; } function defaultReportMessageInternal(out, stringifyOne) { if (!out.failed) return; const { message, details, hints } = out.counterexamplePath === null ? out.interrupted ? preFormatEarlyInterrupted(out, stringifyOne) : preFormatTooManySkipped(out, stringifyOne) : preFormatFailure(out, stringifyOne); let errorMessage = message; if (details != null) errorMessage += ` ${details}`; if (hints.length > 0) errorMessage += ` ${formatHints(hints)}`; return errorMessage; } function defaultReportMessage(out) { return defaultReportMessageInternal(out, stringify); } async function asyncDefaultReportMessage(out) { const pendingStringifieds = []; function stringifyOne(value) { const stringified = possiblyAsyncStringify(value); if (typeof stringified === 'string') { return stringified; } pendingStringifieds.push(Promise.all([value, stringified])); return '\u2026'; } const firstTryMessage = defaultReportMessageInternal(out, stringifyOne); if (pendingStringifieds.length === 0) { return firstTryMessage; } const registeredValues = new Map(await Promise.all(pendingStringifieds)); function stringifySecond(value) { const asyncStringifiedIfRegistered = registeredValues.get(value); if (asyncStringifiedIfRegistered !== void 0) { return asyncStringifiedIfRegistered; } return stringify(value); } return defaultReportMessageInternal(out, stringifySecond); } function buildError(errorMessage, out) { if (!out.runConfiguration.errorWithCause) { throw new SError(errorMessage); } const ErrorWithCause = SError; const error = new ErrorWithCause(errorMessage, { cause: out.errorInstance }); if (!('cause' in error)) { safeObjectAssign2(error, { cause: out.errorInstance }); } return error; } function throwIfFailed(out) { if (!out.failed) return; throw buildError(defaultReportMessage(out), out); } async function asyncThrowIfFailed(out) { if (!out.failed) return; throw buildError(await asyncDefaultReportMessage(out), out); } function reportRunDetails(out) { if (out.runConfiguration.asyncReporter) return out.runConfiguration.asyncReporter(out); else if (out.runConfiguration.reporter) return out.runConfiguration.reporter(out); else return throwIfFailed(out); } async function asyncReportRunDetails(out) { if (out.runConfiguration.asyncReporter) return out.runConfiguration.asyncReporter(out); else if (out.runConfiguration.reporter) return out.runConfiguration.reporter(out); else return asyncThrowIfFailed(out); } // ../../../node_modules/fast-check/lib/esm/check/runner/Runner.js var safeObjectAssign3 = Object.assign; function runIt(property2, shrink, sourceValues, verbose, interruptedAsFailure) { const isModernProperty = property2.runBeforeEach !== void 0 && property2.runAfterEach !== void 0; const runner = new RunnerIterator( sourceValues, shrink, verbose, interruptedAsFailure, ); for (const v of runner) { if (isModernProperty) { property2.runBeforeEach(); } const out = property2.run(v, isModernProperty); if (isModernProperty) { property2.runAfterEach(); } runner.handleResult(out); } return runner.runExecution; } async function asyncRunIt( property2, shrink, sourceValues, verbose, interruptedAsFailure, ) { const isModernProperty = property2.runBeforeEach !== void 0 && property2.runAfterEach !== void 0; const runner = new RunnerIterator( sourceValues, shrink, verbose, interruptedAsFailure, ); for (const v of runner) { if (isModernProperty) { await property2.runBeforeEach(); } const out = await property2.run(v, isModernProperty); if (isModernProperty) { await property2.runAfterEach(); } runner.handleResult(out); } return runner.runExecution; } function check(rawProperty, params) { if (rawProperty == null || rawProperty.generate == null) throw new Error( 'Invalid property encountered, please use a valid property', ); if (rawProperty.run == null) throw new Error( 'Invalid property encountered, please use a valid property not an arbitrary', ); const qParams = QualifiedParameters.read( safeObjectAssign3(safeObjectAssign3({}, readConfigureGlobal()), params), ); if (qParams.reporter !== null && qParams.asyncReporter !== null) throw new Error( 'Invalid parameters encountered, reporter and asyncReporter cannot be specified together', ); if (qParams.asyncReporter !== null && !rawProperty.isAsync()) throw new Error( 'Invalid parameters encountered, only asyncProperty can be used when asyncReporter specified', ); const property2 = decorateProperty(rawProperty, qParams); const maxInitialIterations = qParams.path.length === 0 || qParams.path.indexOf(':') === -1 ? qParams.numRuns : -1; const maxSkips = qParams.numRuns * qParams.maxSkipsPerRun; const shrink = (...args) => property2.shrink(...args); const initialValues = qParams.path.length === 0 ? toss(property2, qParams.seed, qParams.randomType, qParams.examples) : pathWalk( qParams.path, stream( lazyToss( property2, qParams.seed, qParams.randomType, qParams.examples, ), ), shrink, ); const sourceValues = new SourceValuesIterator( initialValues, maxInitialIterations, maxSkips, ); const finalShrink = !qParams.endOnFailure ? shrink : Stream.nil; return property2.isAsync() ? asyncRunIt( property2, finalShrink, sourceValues, qParams.verbose, qParams.markInterruptAsFailure, ).then((e) => e.toRunDetails(qParams.seed, qParams.path, maxSkips, qParams), ) : runIt( property2, finalShrink, sourceValues, qParams.verbose, qParams.markInterruptAsFailure, ).toRunDetails(qParams.seed, qParams.path, maxSkips, qParams); } function assert(property2, params) { const out = check(property2, params); if (property2.isAsync()) return out.then(asyncReportRunDetails); else reportRunDetails(out); } // ../../../node_modules/fast-check/lib/esm/check/runner/Sampler.js function toProperty(generator, qParams) { const prop = !Object.prototype.hasOwnProperty.call(generator, 'isAsync') ? new Property(generator, () => true) : generator; return qParams.unbiased === true ? new UnbiasedProperty(prop) : prop; } function streamSample(generator, params) { const extendedParams = typeof params === 'number' ? Object.assign(Object.assign({}, readConfigureGlobal()), { numRuns: params, }) : Object.assign(Object.assign({}, readConfigureGlobal()), params); const qParams = QualifiedParameters.read(extendedParams); const nextProperty = toProperty(generator, qParams); const shrink = nextProperty.shrink.bind(nextProperty); const tossedValues = qParams.path.length === 0 ? stream( toss( nextProperty, qParams.seed, qParams.randomType, qParams.examples, ), ) : pathWalk( qParams.path, stream( lazyToss( nextProperty, qParams.seed, qParams.randomType, qParams.examples, ), ), shrink, ); return tossedValues.take(qParams.numRuns).map((s) => s.value_); } function sample(generator, params) { return [...streamSample(generator, params)]; } function round2(n) { return (Math.round(n * 100) / 100).toFixed(2); } function statistics(generator, classify, params) { const extendedParams = typeof params === 'number' ? Object.assign(Object.assign({}, readConfigureGlobal()), { numRuns: params, }) : Object.assign(Object.assign({}, readConfigureGlobal()), params); const qParams = QualifiedParameters.read(extendedParams); const recorded = {}; for (const g of streamSample(generator, params)) { const out = classify(g); const categories = Array.isArray(out) ? out : [out]; for (const c of categories) { recorded[c] = (recorded[c] || 0) + 1; } } const data = Object.entries(recorded) .sort((a, b) => b[1] - a[1]) .map((i) => [i[0], `${round2((i[1] * 100) / qParams.numRuns)}%`]); const longestName = data .map((i) => i[0].length) .reduce((p, c) => Math.max(p, c), 0); const longestPercent = data .map((i) => i[1].length) .reduce((p, c) => Math.max(p, c), 0); for (const item of data) { qParams.logger( `${item[0].padEnd(longestName, '.')}..${item[1].padStart(longestPercent, '.')}`, ); } } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/GeneratorValueBuilder.js function buildGeneratorValue( mrng, biasFactor, computePreBuiltValues, arbitraryCache, ) { const preBuiltValues = computePreBuiltValues(); let localMrng = mrng.clone(); const context2 = { mrng: mrng.clone(), biasFactor, history: [] }; const valueFunction = (arb) => { const preBuiltValue = preBuiltValues[context2.history.length]; if (preBuiltValue !== void 0 && preBuiltValue.arb === arb) { const value2 = preBuiltValue.value; context2.history.push({ arb, value: value2, context: preBuiltValue.context, mrng: preBuiltValue.mrng, }); localMrng = preBuiltValue.mrng.clone(); return value2; } const g = arb.generate(localMrng, biasFactor); context2.history.push({ arb, value: g.value_, context: g.context, mrng: localMrng.clone(), }); return g.value; }; const memoedValueFunction = (arb, ...args) => { return valueFunction(arbitraryCache(arb, args)); }; const valueMethods = { values() { return context2.history.map((c) => c.value); }, [cloneMethod]() { return buildGeneratorValue( mrng, biasFactor, computePreBuiltValues, arbitraryCache, ).value; }, [toStringMethod]() { return stringify(context2.history.map((c) => c.value)); }, }; const value = Object.assign(memoedValueFunction, valueMethods); return new Value(value, context2); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/StableArbitraryGeneratorCache.js function buildStableArbitraryGeneratorCache(isEqual) { const previousCallsPerBuilder = /* @__PURE__ */ new Map(); return function stableArbitraryGeneratorCache(builder, args) { const entriesForBuilder = previousCallsPerBuilder.get(builder); if (entriesForBuilder === void 0) { const newValue2 = builder(...args); previousCallsPerBuilder.set(builder, [{ args, value: newValue2 }]); return newValue2; } const safeEntriesForBuilder = entriesForBuilder; for (const entry of safeEntriesForBuilder) { if (isEqual(args, entry.args)) { return entry.value; } } const newValue = builder(...args); safeEntriesForBuilder.push({ args, value: newValue }); return newValue; }; } function naiveIsEqual(v1, v2) { if ( v1 !== null && typeof v1 === 'object' && v2 !== null && typeof v2 === 'object' ) { if (Array.isArray(v1)) { if (!Array.isArray(v2)) return false; if (v1.length !== v2.length) return false; } else if (Array.isArray(v2)) { return false; } if (Object.keys(v1).length !== Object.keys(v2).length) { return false; } for (const index in v1) { if (!(index in v2)) { return false; } if (!naiveIsEqual(v1[index], v2[index])) { return false; } } return true; } else { return Object.is(v1, v2); } } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/GeneratorArbitrary.js var GeneratorArbitrary = class extends Arbitrary { constructor() { super(...arguments); this.arbitraryCache = buildStableArbitraryGeneratorCache(naiveIsEqual); } generate(mrng, biasFactor) { return buildGeneratorValue(mrng, biasFactor, () => [], this.arbitraryCache); } canShrinkWithoutContext(value) { return false; } shrink(_value, context2) { if (context2 === void 0) { return Stream.nil(); } const safeContext = context2; const mrng = safeContext.mrng; const biasFactor = safeContext.biasFactor; const history = safeContext.history; return tupleShrink( history.map((c) => c.arb), history.map((c) => c.value), history.map((c) => c.context), ).map((shrink) => { function computePreBuiltValues() { const subValues = shrink.value; const subContexts = shrink.context; return history.map((entry, index) => ({ arb: entry.arb, value: subValues[index], context: subContexts[index], mrng: entry.mrng, })); } return buildGeneratorValue( mrng, biasFactor, computePreBuiltValues, this.arbitraryCache, ); }); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/gen.js function gen() { return new GeneratorArbitrary(); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/BiasNumericRange.js var safeMathFloor = Math.floor; var safeMathLog2 = Math.log; function integerLogLike(v) { return safeMathFloor(safeMathLog2(v) / safeMathLog2(2)); } function bigIntLogLike(v) { if (v === SBigInt(0)) return SBigInt(0); return SBigInt(SString(v).length); } function biasNumericRange(min, max, logLike) { if (min === max) { return [{ min, max }]; } if (min < 0 && max > 0) { const logMin = logLike(-min); const logMax = logLike(max); return [ { min: -logMin, max: logMax }, { min: max - logMax, max }, { min, max: min + logMin }, ]; } const logGap = logLike(max - min); const arbCloseToMin = { min, max: min + logGap }; const arbCloseToMax = { min: max - logGap, max }; return min < 0 ? [arbCloseToMax, arbCloseToMin] : [arbCloseToMin, arbCloseToMax]; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/ShrinkInteger.js var safeMathCeil = Math.ceil; var safeMathFloor2 = Math.floor; function halvePosInteger(n) { return safeMathFloor2(n / 2); } function halveNegInteger(n) { return safeMathCeil(n / 2); } function shrinkInteger(current, target, tryTargetAsap) { const realGap = current - target; function* shrinkDecr() { let previous = tryTargetAsap ? void 0 : target; const gap = tryTargetAsap ? realGap : halvePosInteger(realGap); for ( let toremove = gap; toremove > 0; toremove = halvePosInteger(toremove) ) { const next = toremove === realGap ? target : current - toremove; yield new Value(next, previous); previous = next; } } function* shrinkIncr() { let previous = tryTargetAsap ? void 0 : target; const gap = tryTargetAsap ? realGap : halveNegInteger(realGap); for ( let toremove = gap; toremove < 0; toremove = halveNegInteger(toremove) ) { const next = toremove === realGap ? target : current - toremove; yield new Value(next, previous); previous = next; } } return realGap > 0 ? stream(shrinkDecr()) : stream(shrinkIncr()); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/IntegerArbitrary.js var safeMathSign = Math.sign; var safeNumberIsInteger = Number.isInteger; var safeObjectIs = Object.is; var IntegerArbitrary = class _IntegerArbitrary extends Arbitrary { constructor(min, max) { super(); this.min = min; this.max = max; } generate(mrng, biasFactor) { const range = this.computeGenerateRange(mrng, biasFactor); return new Value(mrng.nextInt(range.min, range.max), void 0); } canShrinkWithoutContext(value) { return ( typeof value === 'number' && safeNumberIsInteger(value) && !safeObjectIs(value, -0) && this.min <= value && value <= this.max ); } shrink(current, context2) { if (!_IntegerArbitrary.isValidContext(current, context2)) { const target = this.defaultTarget(); return shrinkInteger(current, target, true); } if (this.isLastChanceTry(current, context2)) { return Stream.of(new Value(context2, void 0)); } return shrinkInteger(current, context2, false); } defaultTarget() { if (this.min <= 0 && this.max >= 0) { return 0; } return this.min < 0 ? this.max : this.min; } computeGenerateRange(mrng, biasFactor) { if (biasFactor === void 0 || mrng.nextInt(1, biasFactor) !== 1) { return { min: this.min, max: this.max }; } const ranges = biasNumericRange(this.min, this.max, integerLogLike); if (ranges.length === 1) { return ranges[0]; } const id = mrng.nextInt(-2 * (ranges.length - 1), ranges.length - 2); return id < 0 ? ranges[0] : ranges[id + 1]; } isLastChanceTry(current, context2) { if (current > 0) return current === context2 + 1 && current > this.min; if (current < 0) return current === context2 - 1 && current < this.max; return false; } static isValidContext(current, context2) { if (context2 === void 0) { return false; } if (typeof context2 !== 'number') { throw new Error(`Invalid context type passed to IntegerArbitrary (#1)`); } if (context2 !== 0 && safeMathSign(current) !== safeMathSign(context2)) { throw new Error(`Invalid context value passed to IntegerArbitrary (#2)`); } return true; } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/integer.js var safeNumberIsInteger2 = Number.isInteger; function buildCompleteIntegerConstraints(constraints) { const min = constraints.min !== void 0 ? constraints.min : -2147483648; const max = constraints.max !== void 0 ? constraints.max : 2147483647; return { min, max }; } function integer(constraints = {}) { const fullConstraints = buildCompleteIntegerConstraints(constraints); if (fullConstraints.min > fullConstraints.max) { throw new Error( 'fc.integer maximum value should be equal or greater than the minimum one', ); } if (!safeNumberIsInteger2(fullConstraints.min)) { throw new Error('fc.integer minimum value should be an integer'); } if (!safeNumberIsInteger2(fullConstraints.max)) { throw new Error('fc.integer maximum value should be an integer'); } return new IntegerArbitrary(fullConstraints.min, fullConstraints.max); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/DepthContext.js var depthContextCache = /* @__PURE__ */ new Map(); function getDepthContextFor(contextMeta) { if (contextMeta === void 0) { return { depth: 0 }; } if (typeof contextMeta !== 'string') { return contextMeta; } const cachedContext = depthContextCache.get(contextMeta); if (cachedContext !== void 0) { return cachedContext; } const context2 = { depth: 0 }; depthContextCache.set(contextMeta, context2); return context2; } function createDepthIdentifier() { const identifier = { depth: 0 }; return identifier; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/implementations/NoopSlicedGenerator.js var NoopSlicedGenerator = class { constructor(arb, mrng, biasFactor) { this.arb = arb; this.mrng = mrng; this.biasFactor = biasFactor; } attemptExact() { return; } next() { return this.arb.generate(this.mrng, this.biasFactor); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/implementations/SlicedBasedGenerator.js var safeMathMin2 = Math.min; var safeMathMax = Math.max; var SlicedBasedGenerator = class { constructor(arb, mrng, slices, biasFactor) { this.arb = arb; this.mrng = mrng; this.slices = slices; this.biasFactor = biasFactor; this.activeSliceIndex = 0; this.nextIndexInSlice = 0; this.lastIndexInSlice = -1; } attemptExact(targetLength) { if (targetLength !== 0 && this.mrng.nextInt(1, this.biasFactor) === 1) { const eligibleIndices = []; for (let index = 0; index !== this.slices.length; ++index) { const slice = this.slices[index]; if (slice.length === targetLength) { safePush(eligibleIndices, index); } } if (eligibleIndices.length === 0) { return; } this.activeSliceIndex = eligibleIndices[this.mrng.nextInt(0, eligibleIndices.length - 1)]; this.nextIndexInSlice = 0; this.lastIndexInSlice = targetLength - 1; } } next() { if (this.nextIndexInSlice <= this.lastIndexInSlice) { return new Value( this.slices[this.activeSliceIndex][this.nextIndexInSlice++], void 0, ); } if (this.mrng.nextInt(1, this.biasFactor) !== 1) { return this.arb.generate(this.mrng, this.biasFactor); } this.activeSliceIndex = this.mrng.nextInt(0, this.slices.length - 1); const slice = this.slices[this.activeSliceIndex]; if (this.mrng.nextInt(1, this.biasFactor) !== 1) { this.nextIndexInSlice = 1; this.lastIndexInSlice = slice.length - 1; return new Value(slice[0], void 0); } const rangeBoundaryA = this.mrng.nextInt(0, slice.length - 1); const rangeBoundaryB = this.mrng.nextInt(0, slice.length - 1); this.nextIndexInSlice = safeMathMin2(rangeBoundaryA, rangeBoundaryB); this.lastIndexInSlice = safeMathMax(rangeBoundaryA, rangeBoundaryB); return new Value(slice[this.nextIndexInSlice++], void 0); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/BuildSlicedGenerator.js function buildSlicedGenerator(arb, mrng, slices, biasFactor) { if ( biasFactor === void 0 || slices.length === 0 || mrng.nextInt(1, biasFactor) !== 1 ) { return new NoopSlicedGenerator(arb, mrng, biasFactor); } return new SlicedBasedGenerator(arb, mrng, slices, biasFactor); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/ArrayArbitrary.js var safeMathFloor3 = Math.floor; var safeMathLog3 = Math.log; var safeMathMax2 = Math.max; var safeArrayIsArray2 = Array.isArray; function biasedMaxLength(minLength, maxLength) { if (minLength === maxLength) { return minLength; } return ( minLength + safeMathFloor3(safeMathLog3(maxLength - minLength) / safeMathLog3(2)) ); } var ArrayArbitrary = class _ArrayArbitrary extends Arbitrary { constructor( arb, minLength, maxGeneratedLength, maxLength, depthIdentifier, setBuilder, customSlices, ) { super(); this.arb = arb; this.minLength = minLength; this.maxGeneratedLength = maxGeneratedLength; this.maxLength = maxLength; this.setBuilder = setBuilder; this.customSlices = customSlices; this.lengthArb = integer({ min: minLength, max: maxGeneratedLength }); this.depthContext = getDepthContextFor(depthIdentifier); } preFilter(tab) { if (this.setBuilder === void 0) { return tab; } const s = this.setBuilder(); for (let index = 0; index !== tab.length; ++index) { s.tryAdd(tab[index]); } return s.getData(); } static makeItCloneable(vs, shrinkables) { vs[cloneMethod] = () => { const cloned = []; for (let idx = 0; idx !== shrinkables.length; ++idx) { safePush(cloned, shrinkables[idx].value); } this.makeItCloneable(cloned, shrinkables); return cloned; }; return vs; } generateNItemsNoDuplicates(setBuilder, N, mrng, biasFactorItems) { let numSkippedInRow = 0; const s = setBuilder(); const slicedGenerator = buildSlicedGenerator( this.arb, mrng, this.customSlices, biasFactorItems, ); while (s.size() < N && numSkippedInRow < this.maxGeneratedLength) { const current = slicedGenerator.next(); if (s.tryAdd(current)) { numSkippedInRow = 0; } else { numSkippedInRow += 1; } } return s.getData(); } safeGenerateNItemsNoDuplicates(setBuilder, N, mrng, biasFactorItems) { const depthImpact = safeMathMax2( 0, N - biasedMaxLength(this.minLength, this.maxGeneratedLength), ); this.depthContext.depth += depthImpact; try { return this.generateNItemsNoDuplicates( setBuilder, N, mrng, biasFactorItems, ); } finally { this.depthContext.depth -= depthImpact; } } generateNItems(N, mrng, biasFactorItems) { const items = []; const slicedGenerator = buildSlicedGenerator( this.arb, mrng, this.customSlices, biasFactorItems, ); slicedGenerator.attemptExact(N); for (let index = 0; index !== N; ++index) { const current = slicedGenerator.next(); safePush(items, current); } return items; } safeGenerateNItems(N, mrng, biasFactorItems) { const depthImpact = safeMathMax2( 0, N - biasedMaxLength(this.minLength, this.maxGeneratedLength), ); this.depthContext.depth += depthImpact; try { return this.generateNItems(N, mrng, biasFactorItems); } finally { this.depthContext.depth -= depthImpact; } } wrapper(itemsRaw, shrunkOnce, itemsRawLengthContext, startIndex) { const items = shrunkOnce ? this.preFilter(itemsRaw) : itemsRaw; let cloneable = false; const vs = []; const itemsContexts = []; for (let idx = 0; idx !== items.length; ++idx) { const s = items[idx]; cloneable = cloneable || s.hasToBeCloned; safePush(vs, s.value); safePush(itemsContexts, s.context); } if (cloneable) { _ArrayArbitrary.makeItCloneable(vs, items); } const context2 = { shrunkOnce, lengthContext: itemsRaw.length === items.length && itemsRawLengthContext !== void 0 ? itemsRawLengthContext : void 0, itemsContexts, startIndex, }; return new Value(vs, context2); } generate(mrng, biasFactor) { const biasMeta = this.applyBias(mrng, biasFactor); const targetSize = biasMeta.size; const items = this.setBuilder !== void 0 ? this.safeGenerateNItemsNoDuplicates( this.setBuilder, targetSize, mrng, biasMeta.biasFactorItems, ) : this.safeGenerateNItems(targetSize, mrng, biasMeta.biasFactorItems); return this.wrapper(items, false, void 0, 0); } applyBias(mrng, biasFactor) { if (biasFactor === void 0) { return { size: this.lengthArb.generate(mrng, void 0).value }; } if (this.minLength === this.maxGeneratedLength) { return { size: this.lengthArb.generate(mrng, void 0).value, biasFactorItems: biasFactor, }; } if (mrng.nextInt(1, biasFactor) !== 1) { return { size: this.lengthArb.generate(mrng, void 0).value }; } if ( mrng.nextInt(1, biasFactor) !== 1 || this.minLength === this.maxGeneratedLength ) { return { size: this.lengthArb.generate(mrng, void 0).value, biasFactorItems: biasFactor, }; } const maxBiasedLength = biasedMaxLength( this.minLength, this.maxGeneratedLength, ); const targetSizeValue = integer({ min: this.minLength, max: maxBiasedLength, }).generate(mrng, void 0); return { size: targetSizeValue.value, biasFactorItems: biasFactor }; } canShrinkWithoutContext(value) { if ( !safeArrayIsArray2(value) || this.minLength > value.length || value.length > this.maxLength ) { return false; } for (let index = 0; index !== value.length; ++index) { if (!(index in value)) { return false; } if (!this.arb.canShrinkWithoutContext(value[index])) { return false; } } const filtered = this.preFilter( safeMap(value, (item) => new Value(item, void 0)), ); return filtered.length === value.length; } shrinkItemByItem(value, safeContext, endIndex) { const shrinks = []; for (let index = safeContext.startIndex; index < endIndex; ++index) { safePush( shrinks, makeLazy(() => this.arb .shrink(value[index], safeContext.itemsContexts[index]) .map((v) => { const beforeCurrent = safeMap( safeSlice(value, 0, index), (v2, i) => new Value(cloneIfNeeded(v2), safeContext.itemsContexts[i]), ); const afterCurrent = safeMap( safeSlice(value, index + 1), (v2, i) => new Value( cloneIfNeeded(v2), safeContext.itemsContexts[i + index + 1], ), ); return [[...beforeCurrent, v, ...afterCurrent], void 0, index]; }), ), ); } return Stream.nil().join(...shrinks); } shrinkImpl(value, context2) { if (value.length === 0) { return Stream.nil(); } const safeContext = context2 !== void 0 ? context2 : { shrunkOnce: false, lengthContext: void 0, itemsContexts: [], startIndex: 0, }; return this.lengthArb .shrink(value.length, safeContext.lengthContext) .drop( safeContext.shrunkOnce && safeContext.lengthContext === void 0 && value.length > this.minLength + 1 ? 1 : 0, ) .map((lengthValue) => { const sliceStart = value.length - lengthValue.value; return [ safeMap( safeSlice(value, sliceStart), (v, index) => new Value( cloneIfNeeded(v), safeContext.itemsContexts[index + sliceStart], ), ), lengthValue.context, 0, ]; }) .join( makeLazy(() => value.length > this.minLength ? this.shrinkItemByItem(value, safeContext, 1) : this.shrinkItemByItem(value, safeContext, value.length), ), ) .join( value.length > this.minLength ? makeLazy(() => { const subContext = { shrunkOnce: false, lengthContext: void 0, itemsContexts: safeSlice(safeContext.itemsContexts, 1), startIndex: 0, }; return this.shrinkImpl(safeSlice(value, 1), subContext) .filter((v) => this.minLength <= v[0].length + 1) .map((v) => { return [ [ new Value( cloneIfNeeded(value[0]), safeContext.itemsContexts[0], ), ...v[0], ], void 0, 0, ]; }); }) : Stream.nil(), ); } shrink(value, context2) { return this.shrinkImpl(value, context2).map((contextualValue) => this.wrapper( contextualValue[0], true, contextualValue[1], contextualValue[2], ), ); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/MaxLengthFromMinLength.js var safeMathFloor4 = Math.floor; var safeMathMin3 = Math.min; var MaxLengthUpperBound = 2147483647; var orderedSize = ['xsmall', 'small', 'medium', 'large', 'xlarge']; var orderedRelativeSize = ['-4', '-3', '-2', '-1', '=', '+1', '+2', '+3', '+4']; var DefaultSize = 'small'; function maxLengthFromMinLength(minLength, size) { switch (size) { case 'xsmall': return safeMathFloor4(1.1 * minLength) + 1; case 'small': return 2 * minLength + 10; case 'medium': return 11 * minLength + 100; case 'large': return 101 * minLength + 1e3; case 'xlarge': return 1001 * minLength + 1e4; default: throw new Error( `Unable to compute lengths based on received size: ${size}`, ); } } function relativeSizeToSize(size, defaultSize) { const sizeInRelative = safeIndexOf(orderedRelativeSize, size); if (sizeInRelative === -1) { return size; } const defaultSizeInSize = safeIndexOf(orderedSize, defaultSize); if (defaultSizeInSize === -1) { throw new Error( `Unable to offset size based on the unknown defaulted one: ${defaultSize}`, ); } const resultingSizeInSize = defaultSizeInSize + sizeInRelative - 4; return resultingSizeInSize < 0 ? orderedSize[0] : resultingSizeInSize >= orderedSize.length ? orderedSize[orderedSize.length - 1] : orderedSize[resultingSizeInSize]; } function maxGeneratedLengthFromSizeForArbitrary( size, minLength, maxLength, specifiedMaxLength, ) { const { baseSize: defaultSize = DefaultSize, defaultSizeToMaxWhenMaxSpecified, } = readConfigureGlobal() || {}; const definedSize = size !== void 0 ? size : specifiedMaxLength && defaultSizeToMaxWhenMaxSpecified ? 'max' : defaultSize; if (definedSize === 'max') { return maxLength; } const finalSize = relativeSizeToSize(definedSize, defaultSize); return safeMathMin3(maxLengthFromMinLength(minLength, finalSize), maxLength); } function depthBiasFromSizeForArbitrary(depthSizeOrSize, specifiedMaxDepth) { if (typeof depthSizeOrSize === 'number') { return 1 / depthSizeOrSize; } const { baseSize: defaultSize = DefaultSize, defaultSizeToMaxWhenMaxSpecified, } = readConfigureGlobal() || {}; const definedSize = depthSizeOrSize !== void 0 ? depthSizeOrSize : specifiedMaxDepth && defaultSizeToMaxWhenMaxSpecified ? 'max' : defaultSize; if (definedSize === 'max') { return 0; } const finalSize = relativeSizeToSize(definedSize, defaultSize); switch (finalSize) { case 'xsmall': return 1; case 'small': return 0.5; case 'medium': return 0.25; case 'large': return 0.125; case 'xlarge': return 0.0625; } } function resolveSize(size) { const { baseSize: defaultSize = DefaultSize } = readConfigureGlobal() || {}; if (size === void 0) { return defaultSize; } return relativeSizeToSize(size, defaultSize); } // ../../../node_modules/fast-check/lib/esm/arbitrary/array.js function array(arb, constraints = {}) { const size = constraints.size; const minLength = constraints.minLength || 0; const maxLengthOrUnset = constraints.maxLength; const depthIdentifier = constraints.depthIdentifier; const maxLength = maxLengthOrUnset !== void 0 ? maxLengthOrUnset : MaxLengthUpperBound; const specifiedMaxLength = maxLengthOrUnset !== void 0; const maxGeneratedLength = maxGeneratedLengthFromSizeForArbitrary( size, minLength, maxLength, specifiedMaxLength, ); const customSlices = constraints.experimentalCustomSlices || []; return new ArrayArbitrary( arb, minLength, maxGeneratedLength, maxLength, depthIdentifier, void 0, customSlices, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/ShrinkBigInt.js function halveBigInt(n) { return n / SBigInt(2); } function shrinkBigInt(current, target, tryTargetAsap) { const realGap = current - target; function* shrinkDecr() { let previous = tryTargetAsap ? void 0 : target; const gap = tryTargetAsap ? realGap : halveBigInt(realGap); for (let toremove = gap; toremove > 0; toremove = halveBigInt(toremove)) { const next = current - toremove; yield new Value(next, previous); previous = next; } } function* shrinkIncr() { let previous = tryTargetAsap ? void 0 : target; const gap = tryTargetAsap ? realGap : halveBigInt(realGap); for (let toremove = gap; toremove < 0; toremove = halveBigInt(toremove)) { const next = current - toremove; yield new Value(next, previous); previous = next; } } return realGap > 0 ? stream(shrinkDecr()) : stream(shrinkIncr()); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/BigIntArbitrary.js var BigIntArbitrary = class _BigIntArbitrary extends Arbitrary { constructor(min, max) { super(); this.min = min; this.max = max; } generate(mrng, biasFactor) { const range = this.computeGenerateRange(mrng, biasFactor); return new Value(mrng.nextBigInt(range.min, range.max), void 0); } computeGenerateRange(mrng, biasFactor) { if (biasFactor === void 0 || mrng.nextInt(1, biasFactor) !== 1) { return { min: this.min, max: this.max }; } const ranges = biasNumericRange(this.min, this.max, bigIntLogLike); if (ranges.length === 1) { return ranges[0]; } const id = mrng.nextInt(-2 * (ranges.length - 1), ranges.length - 2); return id < 0 ? ranges[0] : ranges[id + 1]; } canShrinkWithoutContext(value) { return typeof value === 'bigint' && this.min <= value && value <= this.max; } shrink(current, context2) { if (!_BigIntArbitrary.isValidContext(current, context2)) { const target = this.defaultTarget(); return shrinkBigInt(current, target, true); } if (this.isLastChanceTry(current, context2)) { return Stream.of(new Value(context2, void 0)); } return shrinkBigInt(current, context2, false); } defaultTarget() { if (this.min <= 0 && this.max >= 0) { return SBigInt(0); } return this.min < 0 ? this.max : this.min; } isLastChanceTry(current, context2) { if (current > 0) return current === context2 + SBigInt(1) && current > this.min; if (current < 0) return current === context2 - SBigInt(1) && current < this.max; return false; } static isValidContext(current, context2) { if (context2 === void 0) { return false; } if (typeof context2 !== 'bigint') { throw new Error(`Invalid context type passed to BigIntArbitrary (#1)`); } const differentSigns = (current > 0 && context2 < 0) || (current < 0 && context2 > 0); if (context2 !== SBigInt(0) && differentSigns) { throw new Error(`Invalid context value passed to BigIntArbitrary (#2)`); } return true; } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/bigInt.js function buildCompleteBigIntConstraints(constraints) { const DefaultPow = 256; const DefaultMin = SBigInt(-1) << SBigInt(DefaultPow - 1); const DefaultMax = (SBigInt(1) << SBigInt(DefaultPow - 1)) - SBigInt(1); const min = constraints.min; const max = constraints.max; return { min: min !== void 0 ? min : DefaultMin - (max !== void 0 && max < SBigInt(0) ? max * max : SBigInt(0)), max: max !== void 0 ? max : DefaultMax + (min !== void 0 && min > SBigInt(0) ? min * min : SBigInt(0)), }; } function extractBigIntConstraints(args) { if (args[0] === void 0) { return {}; } if (args[1] === void 0) { const constraints = args[0]; return constraints; } return { min: args[0], max: args[1] }; } function bigInt(...args) { const constraints = buildCompleteBigIntConstraints( extractBigIntConstraints(args), ); if (constraints.min > constraints.max) { throw new Error('fc.bigInt expects max to be greater than or equal to min'); } return new BigIntArbitrary(constraints.min, constraints.max); } // ../../../node_modules/fast-check/lib/esm/arbitrary/bigIntN.js function bigIntN(n) { if (n < 1) { throw new Error( 'fc.bigIntN expects requested number of bits to be superior or equal to 1', ); } const min = SBigInt(-1) << SBigInt(n - 1); const max = (SBigInt(1) << SBigInt(n - 1)) - SBigInt(1); return new BigIntArbitrary(min, max); } // ../../../node_modules/fast-check/lib/esm/arbitrary/bigUint.js function computeDefaultMax() { return (SBigInt(1) << SBigInt(256)) - SBigInt(1); } function bigUint(constraints) { const requestedMax = typeof constraints === 'object' ? constraints.max : constraints; const max = requestedMax !== void 0 ? requestedMax : computeDefaultMax(); if (max < 0) { throw new Error( 'fc.bigUint expects max to be greater than or equal to zero', ); } return new BigIntArbitrary(SBigInt(0), max); } // ../../../node_modules/fast-check/lib/esm/arbitrary/bigUintN.js function bigUintN(n) { if (n < 0) { throw new Error( 'fc.bigUintN expects requested number of bits to be superior or equal to 0', ); } const min = SBigInt(0); const max = (SBigInt(1) << SBigInt(n)) - SBigInt(1); return new BigIntArbitrary(min, max); } // ../../../node_modules/fast-check/lib/esm/arbitrary/boolean.js function booleanMapper(v) { return v === 1; } function booleanUnmapper(v) { if (typeof v !== 'boolean') throw new Error('Unsupported input type'); return v === true ? 1 : 0; } function boolean() { return integer({ min: 0, max: 1 }) .map(booleanMapper, booleanUnmapper) .noBias(); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/ConstantArbitrary.js var safeObjectIs2 = Object.is; var ConstantArbitrary = class extends Arbitrary { constructor(values) { super(); this.values = values; } generate(mrng, _biasFactor) { const idx = this.values.length === 1 ? 0 : mrng.nextInt(0, this.values.length - 1); const value = this.values[idx]; if (!hasCloneMethod(value)) { return new Value(value, idx); } return new Value(value, idx, () => value[cloneMethod]()); } canShrinkWithoutContext(value) { for (let idx = 0; idx !== this.values.length; ++idx) { if (safeObjectIs2(this.values[idx], value)) { return true; } } return false; } shrink(value, context2) { if (context2 === 0 || safeObjectIs2(value, this.values[0])) { return Stream.nil(); } return Stream.of(new Value(this.values[0], 0)); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/constantFrom.js function constantFrom(...values) { if (values.length === 0) { throw new Error('fc.constantFrom expects at least one parameter'); } return new ConstantArbitrary(values); } // ../../../node_modules/fast-check/lib/esm/arbitrary/falsy.js function falsy(constraints) { if (!constraints || !constraints.withBigInt) { return constantFrom(false, null, void 0, 0, '', NaN); } return constantFrom(false, null, void 0, 0, '', NaN, SBigInt(0)); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/IndexToCharString.js var indexToCharStringMapper = String.fromCodePoint; function indexToCharStringUnmapper(c) { if (typeof c !== 'string') { throw new Error('Cannot unmap non-string'); } if (c.length === 0 || c.length > 2) { throw new Error('Cannot unmap string with more or less than one character'); } const c1 = safeCharCodeAt(c, 0); if (c.length === 1) { return c1; } const c2 = safeCharCodeAt(c, 1); if (c1 < 55296 || c1 > 56319 || c2 < 56320 || c2 > 57343) { throw new Error('Cannot unmap invalid surrogate pairs'); } return c.codePointAt(0); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/CharacterArbitraryBuilder.js function buildCharacterArbitrary(min, max, mapToCode, unmapFromCode) { return integer({ min, max }).map( (n) => indexToCharStringMapper(mapToCode(n)), (c) => unmapFromCode(indexToCharStringUnmapper(c)), ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/IndexToPrintableIndex.js function indexToPrintableIndexMapper(v) { if (v < 95) return v + 32; if (v <= 126) return v - 95; return v; } function indexToPrintableIndexUnmapper(v) { if (v >= 32 && v <= 126) return v - 32; if (v >= 0 && v <= 31) return v + 95; return v; } // ../../../node_modules/fast-check/lib/esm/arbitrary/ascii.js function ascii() { return buildCharacterArbitrary( 0, 127, indexToPrintableIndexMapper, indexToPrintableIndexUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/base64.js function base64Mapper(v) { if (v < 26) return v + 65; if (v < 52) return v + 97 - 26; if (v < 62) return v + 48 - 52; return v === 62 ? 43 : 47; } function base64Unmapper(v) { if (v >= 65 && v <= 90) return v - 65; if (v >= 97 && v <= 122) return v - 97 + 26; if (v >= 48 && v <= 57) return v - 48 + 52; return v === 43 ? 62 : v === 47 ? 63 : -1; } function base64() { return buildCharacterArbitrary(0, 63, base64Mapper, base64Unmapper); } // ../../../node_modules/fast-check/lib/esm/arbitrary/char.js function identity(v) { return v; } function char() { return buildCharacterArbitrary(32, 126, identity, identity); } // ../../../node_modules/fast-check/lib/esm/arbitrary/char16bits.js function char16bits() { return buildCharacterArbitrary( 0, 65535, indexToPrintableIndexMapper, indexToPrintableIndexUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/fullUnicode.js var gapSize = 57343 + 1 - 55296; function unicodeMapper(v) { if (v < 55296) return indexToPrintableIndexMapper(v); return v + gapSize; } function unicodeUnmapper(v) { if (v < 55296) return indexToPrintableIndexUnmapper(v); if (v <= 57343) return -1; return v - gapSize; } function fullUnicode() { return buildCharacterArbitrary( 0, 1114111 - gapSize, unicodeMapper, unicodeUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/hexa.js function hexaMapper(v) { return v < 10 ? v + 48 : v + 97 - 10; } function hexaUnmapper(v) { return v < 58 ? v - 48 : v >= 97 && v < 103 ? v - 97 + 10 : -1; } function hexa() { return buildCharacterArbitrary(0, 15, hexaMapper, hexaUnmapper); } // ../../../node_modules/fast-check/lib/esm/arbitrary/unicode.js var gapSize2 = 57343 + 1 - 55296; function unicodeMapper2(v) { if (v < 55296) return indexToPrintableIndexMapper(v); return v + gapSize2; } function unicodeUnmapper2(v) { if (v < 55296) return indexToPrintableIndexUnmapper(v); if (v <= 57343) return -1; return v - gapSize2; } function unicode() { return buildCharacterArbitrary( 0, 65535 - gapSize2, unicodeMapper2, unicodeUnmapper2, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/constant.js function constant(value) { return new ConstantArbitrary([value]); } // ../../../node_modules/fast-check/lib/esm/arbitrary/context.js var ContextImplem = class _ContextImplem { constructor() { this.receivedLogs = []; } log(data) { this.receivedLogs.push(data); } size() { return this.receivedLogs.length; } toString() { return JSON.stringify({ logs: this.receivedLogs }); } [cloneMethod]() { return new _ContextImplem(); } }; function context() { return constant(new ContextImplem()); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/TimeToDate.js var safeNaN = Number.NaN; var safeNumberIsNaN2 = Number.isNaN; function timeToDateMapper(time) { return new SDate(time); } function timeToDateUnmapper(value) { if (!(value instanceof SDate) || value.constructor !== SDate) { throw new SError('Not a valid value for date unmapper'); } return safeGetTime(value); } function timeToDateMapperWithNaN(valueForNaN) { return (time) => { return time === valueForNaN ? new SDate(safeNaN) : timeToDateMapper(time); }; } function timeToDateUnmapperWithNaN(valueForNaN) { return (value) => { const time = timeToDateUnmapper(value); return safeNumberIsNaN2(time) ? valueForNaN : time; }; } // ../../../node_modules/fast-check/lib/esm/arbitrary/date.js var safeNumberIsNaN3 = Number.isNaN; function date(constraints = {}) { const intMin = constraints.min !== void 0 ? safeGetTime(constraints.min) : -864e13; const intMax = constraints.max !== void 0 ? safeGetTime(constraints.max) : 864e13; const noInvalidDate = constraints.noInvalidDate === void 0 || constraints.noInvalidDate; if (safeNumberIsNaN3(intMin)) throw new Error('fc.date min must be valid instance of Date'); if (safeNumberIsNaN3(intMax)) throw new Error('fc.date max must be valid instance of Date'); if (intMin > intMax) throw new Error('fc.date max must be greater or equal to min'); if (noInvalidDate) { return integer({ min: intMin, max: intMax }).map( timeToDateMapper, timeToDateUnmapper, ); } const valueForNaN = intMax + 1; return integer({ min: intMin, max: intMax + 1 }).map( timeToDateMapperWithNaN(valueForNaN), timeToDateUnmapperWithNaN(valueForNaN), ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/CloneArbitrary.js var safeSymbolIterator2 = Symbol.iterator; var safeIsArray = Array.isArray; var safeObjectIs3 = Object.is; var CloneArbitrary = class _CloneArbitrary extends Arbitrary { constructor(arb, numValues) { super(); this.arb = arb; this.numValues = numValues; } generate(mrng, biasFactor) { const items = []; if (this.numValues <= 0) { return this.wrapper(items); } for (let idx = 0; idx !== this.numValues - 1; ++idx) { safePush(items, this.arb.generate(mrng.clone(), biasFactor)); } safePush(items, this.arb.generate(mrng, biasFactor)); return this.wrapper(items); } canShrinkWithoutContext(value) { if (!safeIsArray(value) || value.length !== this.numValues) { return false; } if (value.length === 0) { return true; } for (let index = 1; index < value.length; ++index) { if (!safeObjectIs3(value[0], value[index])) { return false; } } return this.arb.canShrinkWithoutContext(value[0]); } shrink(value, context2) { if (value.length === 0) { return Stream.nil(); } return new Stream( this.shrinkImpl(value, context2 !== void 0 ? context2 : []), ).map((v) => this.wrapper(v)); } *shrinkImpl(value, contexts) { const its = safeMap(value, (v, idx) => this.arb.shrink(v, contexts[idx])[safeSymbolIterator2](), ); let cur = safeMap(its, (it) => it.next()); while (!cur[0].done) { yield safeMap(cur, (c) => c.value); cur = safeMap(its, (it) => it.next()); } } static makeItCloneable(vs, shrinkables) { vs[cloneMethod] = () => { const cloned = []; for (let idx = 0; idx !== shrinkables.length; ++idx) { safePush(cloned, shrinkables[idx].value); } this.makeItCloneable(cloned, shrinkables); return cloned; }; return vs; } wrapper(items) { let cloneable = false; const vs = []; const contexts = []; for (let idx = 0; idx !== items.length; ++idx) { const s = items[idx]; cloneable = cloneable || s.hasToBeCloned; safePush(vs, s.value); safePush(contexts, s.context); } if (cloneable) { _CloneArbitrary.makeItCloneable(vs, items); } return new Value(vs, contexts); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/clone.js function clone(arb, numValues) { return new CloneArbitrary(arb, numValues); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/CustomEqualSet.js var CustomEqualSet = class { constructor(isEqual) { this.isEqual = isEqual; this.data = []; } tryAdd(value) { for (let idx = 0; idx !== this.data.length; ++idx) { if (this.isEqual(this.data[idx], value)) { return false; } } safePush(this.data, value); return true; } size() { return this.data.length; } getData() { return this.data; } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/StrictlyEqualSet.js var safeNumberIsNaN4 = Number.isNaN; var StrictlyEqualSet = class { constructor(selector) { this.selector = selector; this.selectedItemsExceptNaN = new SSet(); this.data = []; } tryAdd(value) { const selected = this.selector(value); if (safeNumberIsNaN4(selected)) { safePush(this.data, value); return true; } const sizeBefore = this.selectedItemsExceptNaN.size; safeAdd(this.selectedItemsExceptNaN, selected); if (sizeBefore !== this.selectedItemsExceptNaN.size) { safePush(this.data, value); return true; } return false; } size() { return this.data.length; } getData() { return this.data; } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/SameValueSet.js var safeObjectIs4 = Object.is; var SameValueSet = class { constructor(selector) { this.selector = selector; this.selectedItemsExceptMinusZero = new SSet(); this.data = []; this.hasMinusZero = false; } tryAdd(value) { const selected = this.selector(value); if (safeObjectIs4(selected, -0)) { if (this.hasMinusZero) { return false; } safePush(this.data, value); this.hasMinusZero = true; return true; } const sizeBefore = this.selectedItemsExceptMinusZero.size; safeAdd(this.selectedItemsExceptMinusZero, selected); if (sizeBefore !== this.selectedItemsExceptMinusZero.size) { safePush(this.data, value); return true; } return false; } size() { return this.data.length; } getData() { return this.data; } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/SameValueZeroSet.js var SameValueZeroSet = class { constructor(selector) { this.selector = selector; this.selectedItems = new SSet(); this.data = []; } tryAdd(value) { const selected = this.selector(value); const sizeBefore = this.selectedItems.size; safeAdd(this.selectedItems, selected); if (sizeBefore !== this.selectedItems.size) { safePush(this.data, value); return true; } return false; } size() { return this.data.length; } getData() { return this.data; } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/uniqueArray.js function buildUniqueArraySetBuilder(constraints) { if (typeof constraints.comparator === 'function') { if (constraints.selector === void 0) { const comparator2 = constraints.comparator; const isEqualForBuilder2 = (nextA, nextB) => comparator2(nextA.value_, nextB.value_); return () => new CustomEqualSet(isEqualForBuilder2); } const comparator = constraints.comparator; const selector2 = constraints.selector; const refinedSelector2 = (next) => selector2(next.value_); const isEqualForBuilder = (nextA, nextB) => comparator(refinedSelector2(nextA), refinedSelector2(nextB)); return () => new CustomEqualSet(isEqualForBuilder); } const selector = constraints.selector || ((v) => v); const refinedSelector = (next) => selector(next.value_); switch (constraints.comparator) { case 'IsStrictlyEqual': return () => new StrictlyEqualSet(refinedSelector); case 'SameValueZero': return () => new SameValueZeroSet(refinedSelector); case 'SameValue': case void 0: return () => new SameValueSet(refinedSelector); } } function uniqueArray(arb, constraints = {}) { const minLength = constraints.minLength !== void 0 ? constraints.minLength : 0; const maxLength = constraints.maxLength !== void 0 ? constraints.maxLength : MaxLengthUpperBound; const maxGeneratedLength = maxGeneratedLengthFromSizeForArbitrary( constraints.size, minLength, maxLength, constraints.maxLength !== void 0, ); const depthIdentifier = constraints.depthIdentifier; const setBuilder = buildUniqueArraySetBuilder(constraints); const arrayArb = new ArrayArbitrary( arb, minLength, maxGeneratedLength, maxLength, depthIdentifier, setBuilder, [], ); if (minLength === 0) return arrayArb; return arrayArb.filter((tab) => tab.length >= minLength); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/KeyValuePairsToObject.js var safeObjectCreate = Object.create; var safeObjectDefineProperty3 = Object.defineProperty; var safeObjectGetOwnPropertyDescriptor2 = Object.getOwnPropertyDescriptor; var safeObjectGetPrototypeOf2 = Object.getPrototypeOf; var safeObjectGetOwnPropertySymbols2 = Object.getOwnPropertySymbols; var safeObjectGetOwnPropertyNames = Object.getOwnPropertyNames; var safeObjectEntries = Object.entries; function keyValuePairsToObjectMapper(definition) { const obj = definition[1] ? safeObjectCreate(null) : {}; for (const keyValue of definition[0]) { safeObjectDefineProperty3(obj, keyValue[0], { enumerable: true, configurable: true, writable: true, value: keyValue[1], }); } return obj; } function buildIsValidPropertyNameFilter(obj) { return function isValidPropertyNameFilter(key) { const descriptor = safeObjectGetOwnPropertyDescriptor2(obj, key); return ( descriptor !== void 0 && !!descriptor.configurable && !!descriptor.enumerable && !!descriptor.writable && descriptor.get === void 0 && descriptor.set === void 0 ); }; } function keyValuePairsToObjectUnmapper(value) { if (typeof value !== 'object' || value === null) { throw new SError( 'Incompatible instance received: should be a non-null object', ); } const hasNullPrototype = safeObjectGetPrototypeOf2(value) === null; const hasObjectPrototype = 'constructor' in value && value.constructor === Object; if (!hasNullPrototype && !hasObjectPrototype) { throw new SError( 'Incompatible instance received: should be of exact type Object', ); } if (safeObjectGetOwnPropertySymbols2(value).length > 0) { throw new SError('Incompatible instance received: should contain symbols'); } if ( !safeEvery( safeObjectGetOwnPropertyNames(value), buildIsValidPropertyNameFilter(value), ) ) { throw new SError( 'Incompatible instance received: should contain only c/e/w properties without get/set', ); } return [safeObjectEntries(value), hasNullPrototype]; } // ../../../node_modules/fast-check/lib/esm/arbitrary/dictionary.js function dictionaryKeyExtractor(entry) { return entry[0]; } function dictionary(keyArb, valueArb, constraints = {}) { const noNullPrototype = constraints.noNullPrototype !== false; return tuple( uniqueArray(tuple(keyArb, valueArb), { minLength: constraints.minKeys, maxLength: constraints.maxKeys, size: constraints.size, selector: dictionaryKeyExtractor, depthIdentifier: constraints.depthIdentifier, }), noNullPrototype ? constant(false) : boolean(), ).map(keyValuePairsToObjectMapper, keyValuePairsToObjectUnmapper); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/FrequencyArbitrary.js var safePositiveInfinity2 = Number.POSITIVE_INFINITY; var safeMaxSafeInteger = Number.MAX_SAFE_INTEGER; var safeNumberIsInteger3 = Number.isInteger; var safeMathFloor5 = Math.floor; var safeMathPow = Math.pow; var safeMathMin4 = Math.min; var FrequencyArbitrary = class _FrequencyArbitrary extends Arbitrary { static from(warbs, constraints, label) { if (warbs.length === 0) { throw new Error(`${label} expects at least one weighted arbitrary`); } let totalWeight = 0; for (let idx = 0; idx !== warbs.length; ++idx) { const currentArbitrary = warbs[idx].arbitrary; if (currentArbitrary === void 0) { throw new Error(`${label} expects arbitraries to be specified`); } const currentWeight = warbs[idx].weight; totalWeight += currentWeight; if (!safeNumberIsInteger3(currentWeight)) { throw new Error(`${label} expects weights to be integer values`); } if (currentWeight < 0) { throw new Error( `${label} expects weights to be superior or equal to 0`, ); } } if (totalWeight <= 0) { throw new Error( `${label} expects the sum of weights to be strictly superior to 0`, ); } const sanitizedConstraints = { depthBias: depthBiasFromSizeForArbitrary( constraints.depthSize, constraints.maxDepth !== void 0, ), maxDepth: constraints.maxDepth != void 0 ? constraints.maxDepth : safePositiveInfinity2, withCrossShrink: !!constraints.withCrossShrink, }; return new _FrequencyArbitrary( warbs, sanitizedConstraints, getDepthContextFor(constraints.depthIdentifier), ); } constructor(warbs, constraints, context2) { super(); this.warbs = warbs; this.constraints = constraints; this.context = context2; let currentWeight = 0; this.cumulatedWeights = []; for (let idx = 0; idx !== warbs.length; ++idx) { currentWeight += warbs[idx].weight; safePush(this.cumulatedWeights, currentWeight); } this.totalWeight = currentWeight; } generate(mrng, biasFactor) { if (this.mustGenerateFirst()) { return this.safeGenerateForIndex(mrng, 0, biasFactor); } const selected = mrng.nextInt( this.computeNegDepthBenefit(), this.totalWeight - 1, ); for (let idx = 0; idx !== this.cumulatedWeights.length; ++idx) { if (selected < this.cumulatedWeights[idx]) { return this.safeGenerateForIndex(mrng, idx, biasFactor); } } throw new Error(`Unable to generate from fc.frequency`); } canShrinkWithoutContext(value) { return this.canShrinkWithoutContextIndex(value) !== -1; } shrink(value, context2) { if (context2 !== void 0) { const safeContext = context2; const selectedIndex = safeContext.selectedIndex; const originalBias = safeContext.originalBias; const originalArbitrary = this.warbs[selectedIndex].arbitrary; const originalShrinks = originalArbitrary .shrink(value, safeContext.originalContext) .map((v) => this.mapIntoValue(selectedIndex, v, null, originalBias)); if (safeContext.clonedMrngForFallbackFirst !== null) { if (safeContext.cachedGeneratedForFirst === void 0) { safeContext.cachedGeneratedForFirst = this.safeGenerateForIndex( safeContext.clonedMrngForFallbackFirst, 0, originalBias, ); } const valueFromFirst = safeContext.cachedGeneratedForFirst; return Stream.of(valueFromFirst).join(originalShrinks); } return originalShrinks; } const potentialSelectedIndex = this.canShrinkWithoutContextIndex(value); if (potentialSelectedIndex === -1) { return Stream.nil(); } return this.defaultShrinkForFirst(potentialSelectedIndex).join( this.warbs[potentialSelectedIndex].arbitrary .shrink(value, void 0) .map((v) => this.mapIntoValue(potentialSelectedIndex, v, null, void 0)), ); } defaultShrinkForFirst(selectedIndex) { ++this.context.depth; try { if ( !this.mustFallbackToFirstInShrink(selectedIndex) || this.warbs[0].fallbackValue === void 0 ) { return Stream.nil(); } } finally { --this.context.depth; } const rawShrinkValue = new Value( this.warbs[0].fallbackValue.default, void 0, ); return Stream.of(this.mapIntoValue(0, rawShrinkValue, null, void 0)); } canShrinkWithoutContextIndex(value) { if (this.mustGenerateFirst()) { return this.warbs[0].arbitrary.canShrinkWithoutContext(value) ? 0 : -1; } try { ++this.context.depth; for (let idx = 0; idx !== this.warbs.length; ++idx) { const warb = this.warbs[idx]; if ( warb.weight !== 0 && warb.arbitrary.canShrinkWithoutContext(value) ) { return idx; } } return -1; } finally { --this.context.depth; } } mapIntoValue(idx, value, clonedMrngForFallbackFirst, biasFactor) { const context2 = { selectedIndex: idx, originalBias: biasFactor, originalContext: value.context, clonedMrngForFallbackFirst, }; return new Value(value.value, context2); } safeGenerateForIndex(mrng, idx, biasFactor) { ++this.context.depth; try { const value = this.warbs[idx].arbitrary.generate(mrng, biasFactor); const clonedMrngForFallbackFirst = this.mustFallbackToFirstInShrink(idx) ? mrng.clone() : null; return this.mapIntoValue( idx, value, clonedMrngForFallbackFirst, biasFactor, ); } finally { --this.context.depth; } } mustGenerateFirst() { return this.constraints.maxDepth <= this.context.depth; } mustFallbackToFirstInShrink(idx) { return ( idx !== 0 && this.constraints.withCrossShrink && this.warbs[0].weight !== 0 ); } computeNegDepthBenefit() { const depthBias = this.constraints.depthBias; if (depthBias <= 0 || this.warbs[0].weight === 0) { return 0; } const depthBenefit = safeMathFloor5(safeMathPow(1 + depthBias, this.context.depth)) - 1; return ( -safeMathMin4(this.totalWeight * depthBenefit, safeMaxSafeInteger) || 0 ); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/oneof.js function isOneOfContraints(param) { return ( param != null && typeof param === 'object' && !('generate' in param) && !('arbitrary' in param) && !('weight' in param) ); } function toWeightedArbitrary(maybeWeightedArbitrary) { if (isArbitrary(maybeWeightedArbitrary)) { return { arbitrary: maybeWeightedArbitrary, weight: 1 }; } return maybeWeightedArbitrary; } function oneof(...args) { const constraints = args[0]; if (isOneOfContraints(constraints)) { const weightedArbs2 = safeMap(safeSlice(args, 1), toWeightedArbitrary); return FrequencyArbitrary.from(weightedArbs2, constraints, 'fc.oneof'); } const weightedArbs = safeMap(args, toWeightedArbitrary); return FrequencyArbitrary.from(weightedArbs, {}, 'fc.oneof'); } // ../../../node_modules/fast-check/lib/esm/arbitrary/nat.js var safeNumberIsInteger4 = Number.isInteger; function nat(arg) { const max = typeof arg === 'number' ? arg : arg && arg.max !== void 0 ? arg.max : 2147483647; if (max < 0) { throw new Error('fc.nat value should be greater than or equal to 0'); } if (!safeNumberIsInteger4(max)) { throw new Error('fc.nat maximum value should be an integer'); } return new IntegerArbitrary(0, max); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/IndexToMappedConstant.js function indexToMappedConstantMapperFor(entries) { return function indexToMappedConstantMapper(choiceIndex) { let idx = -1; let numSkips = 0; while (choiceIndex >= numSkips) { numSkips += entries[++idx].num; } return entries[idx].build(choiceIndex - numSkips + entries[idx].num); }; } function buildReverseMapping(entries) { const reverseMapping = { mapping: /* @__PURE__ */ new Map(), negativeZeroIndex: void 0, }; let choiceIndex = 0; for (let entryIdx = 0; entryIdx !== entries.length; ++entryIdx) { const entry = entries[entryIdx]; for (let idxInEntry = 0; idxInEntry !== entry.num; ++idxInEntry) { const value = entry.build(idxInEntry); if (value === 0 && 1 / value === Number.NEGATIVE_INFINITY) { reverseMapping.negativeZeroIndex = choiceIndex; } else { reverseMapping.mapping.set(value, choiceIndex); } ++choiceIndex; } } return reverseMapping; } function indexToMappedConstantUnmapperFor(entries) { let reverseMapping = null; return function indexToMappedConstantUnmapper(value) { if (reverseMapping === null) { reverseMapping = buildReverseMapping(entries); } const choiceIndex = Object.is(value, -0) ? reverseMapping.negativeZeroIndex : reverseMapping.mapping.get(value); if (choiceIndex === void 0) { throw new Error( 'Unknown value encountered cannot be built using this mapToConstant', ); } return choiceIndex; }; } // ../../../node_modules/fast-check/lib/esm/arbitrary/mapToConstant.js function computeNumChoices(options) { if (options.length === 0) throw new Error(`fc.mapToConstant expects at least one option`); let numChoices = 0; for (let idx = 0; idx !== options.length; ++idx) { if (options[idx].num < 0) throw new Error( `fc.mapToConstant expects all options to have a number of entries greater or equal to zero`, ); numChoices += options[idx].num; } if (numChoices === 0) throw new Error( `fc.mapToConstant expects at least one choice among options`, ); return numChoices; } function mapToConstant(...entries) { const numChoices = computeNumChoices(entries); return nat({ max: numChoices - 1 }).map( indexToMappedConstantMapperFor(entries), indexToMappedConstantUnmapperFor(entries), ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/CharacterRangeArbitraryBuilder.js var safeStringFromCharCode = String.fromCharCode; var lowerCaseMapper = { num: 26, build: (v) => safeStringFromCharCode(v + 97) }; var upperCaseMapper = { num: 26, build: (v) => safeStringFromCharCode(v + 65) }; var numericMapper = { num: 10, build: (v) => safeStringFromCharCode(v + 48) }; function percentCharArbMapper(c) { const encoded = SencodeURIComponent(c); return c !== encoded ? encoded : `%${safeNumberToString(safeCharCodeAt(c, 0), 16)}`; } function percentCharArbUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported'); } const decoded = decodeURIComponent(value); return decoded; } var percentCharArb = fullUnicode().map( percentCharArbMapper, percentCharArbUnmapper, ); var buildLowerAlphaArbitrary = (others) => mapToConstant(lowerCaseMapper, { num: others.length, build: (v) => others[v], }); var buildLowerAlphaNumericArbitrary = (others) => mapToConstant(lowerCaseMapper, numericMapper, { num: others.length, build: (v) => others[v], }); var buildAlphaNumericArbitrary = (others) => mapToConstant(lowerCaseMapper, upperCaseMapper, numericMapper, { num: others.length, build: (v) => others[v], }); var buildAlphaNumericPercentArbitrary = (others) => oneof( { weight: 10, arbitrary: buildAlphaNumericArbitrary(others) }, { weight: 1, arbitrary: percentCharArb }, ); // ../../../node_modules/fast-check/lib/esm/arbitrary/option.js function option(arb, constraints = {}) { const freq = constraints.freq == null ? 5 : constraints.freq; const nilValue = safeHasOwnProperty(constraints, 'nil') ? constraints.nil : null; const nilArb = constant(nilValue); const weightedArbs = [ { arbitrary: nilArb, weight: 1, fallbackValue: { default: nilValue } }, { arbitrary: arb, weight: freq }, ]; const frequencyConstraints = { withCrossShrink: true, depthSize: constraints.depthSize, maxDepth: constraints.maxDepth, depthIdentifier: constraints.depthIdentifier, }; return FrequencyArbitrary.from( weightedArbs, frequencyConstraints, 'fc.option', ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/PatternsToString.js function patternsToStringMapper(tab) { return safeJoin(tab, ''); } function patternsToStringUnmapperFor(patternsArb, constraints) { return function patternsToStringUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported value'); } const minLength = constraints.minLength !== void 0 ? constraints.minLength : 0; const maxLength = constraints.maxLength !== void 0 ? constraints.maxLength : MaxLengthUpperBound; if (value.length === 0) { if (minLength > 0) { throw new Error('Unable to unmap received string'); } return []; } const stack = [{ endIndexChunks: 0, nextStartIndex: 1, chunks: [] }]; while (stack.length > 0) { const last = safePop(stack); for (let index = last.nextStartIndex; index <= value.length; ++index) { const chunk = safeSubstring(value, last.endIndexChunks, index); if (patternsArb.canShrinkWithoutContext(chunk)) { const newChunks = [...last.chunks, chunk]; if (index === value.length) { if (newChunks.length < minLength || newChunks.length > maxLength) { break; } return newChunks; } safePush(stack, { endIndexChunks: last.endIndexChunks, nextStartIndex: index + 1, chunks: last.chunks, }); safePush(stack, { endIndexChunks: index, nextStartIndex: index + 1, chunks: newChunks, }); break; } } } throw new Error('Unable to unmap received string'); }; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/SlicesForStringBuilder.js var dangerousStrings = [ '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', '__proto__', 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', 'apply', 'arguments', 'bind', 'call', 'caller', 'length', 'name', 'prototype', 'key', 'ref', ]; function computeCandidateString(dangerous, charArbitrary, stringSplitter) { let candidate; try { candidate = stringSplitter(dangerous); } catch (err) { return void 0; } for (const entry of candidate) { if (!charArbitrary.canShrinkWithoutContext(entry)) { return void 0; } } return candidate; } function createSlicesForString(charArbitrary, stringSplitter) { const slicesForString = []; for (const dangerous of dangerousStrings) { const candidate = computeCandidateString( dangerous, charArbitrary, stringSplitter, ); if (candidate !== void 0) { safePush(slicesForString, candidate); } } return slicesForString; } // ../../../node_modules/fast-check/lib/esm/arbitrary/stringOf.js var safeObjectAssign4 = Object.assign; function stringOf(charArb, constraints = {}) { const unmapper = patternsToStringUnmapperFor(charArb, constraints); const experimentalCustomSlices = createSlicesForString(charArb, unmapper); const enrichedConstraints = safeObjectAssign4( safeObjectAssign4({}, constraints), { experimentalCustomSlices, }, ); return array(charArb, enrichedConstraints).map( patternsToStringMapper, unmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/InvalidSubdomainLabelFiIter.js function filterInvalidSubdomainLabel(subdomainLabel2) { if (subdomainLabel2.length > 63) { return false; } return ( subdomainLabel2.length < 4 || subdomainLabel2[0] !== 'x' || subdomainLabel2[1] !== 'n' || subdomainLabel2[2] !== '-' || subdomainLabel2[3] !== '-' ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/AdapterArbitrary.js var AdaptedValue = Symbol('adapted-value'); function toAdapterValue(rawValue, adapter2) { const adapted = adapter2(rawValue.value_); if (!adapted.adapted) { return rawValue; } return new Value(adapted.value, AdaptedValue); } var AdapterArbitrary = class extends Arbitrary { constructor(sourceArb, adapter2) { super(); this.sourceArb = sourceArb; this.adapter = adapter2; this.adaptValue = (rawValue) => toAdapterValue(rawValue, adapter2); } generate(mrng, biasFactor) { const rawValue = this.sourceArb.generate(mrng, biasFactor); return this.adaptValue(rawValue); } canShrinkWithoutContext(value) { return ( this.sourceArb.canShrinkWithoutContext(value) && !this.adapter(value).adapted ); } shrink(value, context2) { if (context2 === AdaptedValue) { if (!this.sourceArb.canShrinkWithoutContext(value)) { return Stream.nil(); } return this.sourceArb.shrink(value, void 0).map(this.adaptValue); } return this.sourceArb.shrink(value, context2).map(this.adaptValue); } }; function adapter(sourceArb, adapter2) { return new AdapterArbitrary(sourceArb, adapter2); } // ../../../node_modules/fast-check/lib/esm/arbitrary/domain.js function toSubdomainLabelMapper([f, d]) { return d === null ? f : `${f}${d[0]}${d[1]}`; } function toSubdomainLabelUnmapper(value) { if (typeof value !== 'string' || value.length === 0) { throw new Error('Unsupported'); } if (value.length === 1) { return [value[0], null]; } return [ value[0], [safeSubstring(value, 1, value.length - 1), value[value.length - 1]], ]; } function subdomainLabel(size) { const alphaNumericArb = buildLowerAlphaNumericArbitrary([]); const alphaNumericHyphenArb = buildLowerAlphaNumericArbitrary(['-']); return tuple( alphaNumericArb, option( tuple( stringOf(alphaNumericHyphenArb, { size, maxLength: 61 }), alphaNumericArb, ), ), ) .map(toSubdomainLabelMapper, toSubdomainLabelUnmapper) .filter(filterInvalidSubdomainLabel); } function labelsMapper(elements) { return `${safeJoin(elements[0], '.')}.${elements[1]}`; } function labelsUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported type'); } const lastDotIndex = value.lastIndexOf('.'); return [ safeSplit(safeSubstring(value, 0, lastDotIndex), '.'), safeSubstring(value, lastDotIndex + 1), ]; } function labelsAdapter(labels) { const [subDomains, suffix] = labels; let lengthNotIncludingIndex = suffix.length; for (let index = 0; index !== subDomains.length; ++index) { lengthNotIncludingIndex += 1 + subDomains[index].length; if (lengthNotIncludingIndex > 255) { return { adapted: true, value: [safeSlice(subDomains, 0, index), suffix], }; } } return { adapted: false, value: labels }; } function domain(constraints = {}) { const resolvedSize = resolveSize(constraints.size); const resolvedSizeMinusOne = relativeSizeToSize('-1', resolvedSize); const alphaNumericArb = buildLowerAlphaArbitrary([]); const publicSuffixArb = stringOf(alphaNumericArb, { minLength: 2, maxLength: 63, size: resolvedSizeMinusOne, }); return adapter( tuple( array(subdomainLabel(resolvedSize), { size: resolvedSizeMinusOne, minLength: 1, maxLength: 127, }), publicSuffixArb, ), labelsAdapter, ).map(labelsMapper, labelsUnmapper); } // ../../../node_modules/fast-check/lib/esm/arbitrary/emailAddress.js function dotAdapter(a) { let currentLength = a[0].length; for (let index = 1; index !== a.length; ++index) { currentLength += 1 + a[index].length; if (currentLength > 64) { return { adapted: true, value: safeSlice(a, 0, index) }; } } return { adapted: false, value: a }; } function dotMapper(a) { return safeJoin(a, '.'); } function dotUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported'); } return safeSplit(value, '.'); } function atMapper(data) { return `${data[0]}@${data[1]}`; } function atUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported'); } return safeSplit(value, '@', 2); } function emailAddress(constraints = {}) { const others = [ '!', '#', '$', '%', '&', "'", '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~', ]; const atextArb = buildLowerAlphaNumericArbitrary(others); const localPartArb = adapter( array( stringOf(atextArb, { minLength: 1, maxLength: 64, size: constraints.size, }), { minLength: 1, maxLength: 32, size: constraints.size }, ), dotAdapter, ).map(dotMapper, dotUnmapper); return tuple(localPartArb, domain({ size: constraints.size })).map( atMapper, atUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/ArrayInt64.js var Zero64 = { sign: 1, data: [0, 0] }; var Unit64 = { sign: 1, data: [0, 1] }; function isZero64(a) { return a.data[0] === 0 && a.data[1] === 0; } function isStrictlyNegative64(a) { return a.sign === -1 && !isZero64(a); } function isStrictlyPositive64(a) { return a.sign === 1 && !isZero64(a); } function isEqual64(a, b) { if (a.data[0] === b.data[0] && a.data[1] === b.data[1]) { return a.sign === b.sign || (a.data[0] === 0 && a.data[1] === 0); } return false; } function isStrictlySmaller64Internal(a, b) { return a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]); } function isStrictlySmaller64(a, b) { if (a.sign === b.sign) { return a.sign === 1 ? isStrictlySmaller64Internal(a.data, b.data) : isStrictlySmaller64Internal(b.data, a.data); } return a.sign === -1 && (!isZero64(a) || !isZero64(b)); } function clone64(a) { return { sign: a.sign, data: [a.data[0], a.data[1]] }; } function substract64DataInternal(a, b) { let reminderLow = 0; let low = a[1] - b[1]; if (low < 0) { reminderLow = 1; low = low >>> 0; } return [a[0] - b[0] - reminderLow, low]; } function substract64Internal(a, b) { if (a.sign === 1 && b.sign === -1) { const low = a.data[1] + b.data[1]; const high = a.data[0] + b.data[0] + (low > 4294967295 ? 1 : 0); return { sign: 1, data: [high >>> 0, low >>> 0] }; } return { sign: 1, data: a.sign === 1 ? substract64DataInternal(a.data, b.data) : substract64DataInternal(b.data, a.data), }; } function substract64(arrayIntA, arrayIntB) { if (isStrictlySmaller64(arrayIntA, arrayIntB)) { const out = substract64Internal(arrayIntB, arrayIntA); out.sign = -1; return out; } return substract64Internal(arrayIntA, arrayIntB); } function negative64(arrayIntA) { return { sign: -arrayIntA.sign, data: [arrayIntA.data[0], arrayIntA.data[1]], }; } function add64(arrayIntA, arrayIntB) { if (isZero64(arrayIntB)) { if (isZero64(arrayIntA)) { return clone64(Zero64); } return clone64(arrayIntA); } return substract64(arrayIntA, negative64(arrayIntB)); } function halve64(a) { return { sign: a.sign, data: [ Math.floor(a.data[0] / 2), (a.data[0] % 2 === 1 ? 2147483648 : 0) + Math.floor(a.data[1] / 2), ], }; } function logLike64(a) { return { sign: a.sign, data: [ 0, Math.floor(Math.log(a.data[0] * 4294967296 + a.data[1]) / Math.log(2)), ], }; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/ArrayInt64Arbitrary.js var ArrayInt64Arbitrary = class _ArrayInt64Arbitrary extends Arbitrary { constructor(min, max) { super(); this.min = min; this.max = max; this.biasedRanges = null; } generate(mrng, biasFactor) { const range = this.computeGenerateRange(mrng, biasFactor); const uncheckedValue = mrng.nextArrayInt(range.min, range.max); if (uncheckedValue.data.length === 1) { uncheckedValue.data.unshift(0); } return new Value(uncheckedValue, void 0); } computeGenerateRange(mrng, biasFactor) { if (biasFactor === void 0 || mrng.nextInt(1, biasFactor) !== 1) { return { min: this.min, max: this.max }; } const ranges = this.retrieveBiasedRanges(); if (ranges.length === 1) { return ranges[0]; } const id = mrng.nextInt(-2 * (ranges.length - 1), ranges.length - 2); return id < 0 ? ranges[0] : ranges[id + 1]; } canShrinkWithoutContext(value) { const unsafeValue = value; return ( typeof value === 'object' && value !== null && (unsafeValue.sign === -1 || unsafeValue.sign === 1) && Array.isArray(unsafeValue.data) && unsafeValue.data.length === 2 && ((isStrictlySmaller64(this.min, unsafeValue) && isStrictlySmaller64(unsafeValue, this.max)) || isEqual64(this.min, unsafeValue) || isEqual64(this.max, unsafeValue)) ); } shrinkArrayInt64(value, target, tryTargetAsap) { const realGap = substract64(value, target); function* shrinkGen() { let previous = tryTargetAsap ? void 0 : target; const gap = tryTargetAsap ? realGap : halve64(realGap); for ( let toremove = gap; !isZero64(toremove); toremove = halve64(toremove) ) { const next = substract64(value, toremove); yield new Value(next, previous); previous = next; } } return stream(shrinkGen()); } shrink(current, context2) { if (!_ArrayInt64Arbitrary.isValidContext(current, context2)) { const target = this.defaultTarget(); return this.shrinkArrayInt64(current, target, true); } if (this.isLastChanceTry(current, context2)) { return Stream.of(new Value(context2, void 0)); } return this.shrinkArrayInt64(current, context2, false); } defaultTarget() { if (!isStrictlyPositive64(this.min) && !isStrictlyNegative64(this.max)) { return Zero64; } return isStrictlyNegative64(this.min) ? this.max : this.min; } isLastChanceTry(current, context2) { if (isZero64(current)) { return false; } if (current.sign === 1) { return ( isEqual64(current, add64(context2, Unit64)) && isStrictlyPositive64(substract64(current, this.min)) ); } else { return ( isEqual64(current, substract64(context2, Unit64)) && isStrictlyNegative64(substract64(current, this.max)) ); } } static isValidContext(_current, context2) { if (context2 === void 0) { return false; } if ( typeof context2 !== 'object' || context2 === null || !('sign' in context2) || !('data' in context2) ) { throw new Error( `Invalid context type passed to ArrayInt64Arbitrary (#1)`, ); } return true; } retrieveBiasedRanges() { if (this.biasedRanges != null) { return this.biasedRanges; } if (isEqual64(this.min, this.max)) { this.biasedRanges = [{ min: this.min, max: this.max }]; return this.biasedRanges; } const minStrictlySmallerZero = isStrictlyNegative64(this.min); const maxStrictlyGreaterZero = isStrictlyPositive64(this.max); if (minStrictlySmallerZero && maxStrictlyGreaterZero) { const logMin = logLike64(this.min); const logMax = logLike64(this.max); this.biasedRanges = [ { min: logMin, max: logMax }, { min: substract64(this.max, logMax), max: this.max }, { min: this.min, max: substract64(this.min, logMin) }, ]; } else { const logGap = logLike64(substract64(this.max, this.min)); const arbCloseToMin = { min: this.min, max: add64(this.min, logGap) }; const arbCloseToMax = { min: substract64(this.max, logGap), max: this.max, }; this.biasedRanges = minStrictlySmallerZero ? [arbCloseToMax, arbCloseToMin] : [arbCloseToMin, arbCloseToMax]; } return this.biasedRanges; } }; function arrayInt64(min, max) { const arb = new ArrayInt64Arbitrary(min, max); return arb; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/DoubleHelpers.js var safeNegativeInfinity2 = Number.NEGATIVE_INFINITY; var safePositiveInfinity3 = Number.POSITIVE_INFINITY; var safeEpsilon = Number.EPSILON; var INDEX_POSITIVE_INFINITY = { sign: 1, data: [2146435072, 0] }; var INDEX_NEGATIVE_INFINITY = { sign: -1, data: [2146435072, 1] }; var f64 = new Float64Array(1); var u32 = new Uint32Array(f64.buffer, f64.byteOffset); function bitCastDoubleToUInt64(f) { f64[0] = f; return [u32[1], u32[0]]; } function decomposeDouble(d) { const { 0: hi, 1: lo } = bitCastDoubleToUInt64(d); const signBit = hi >>> 31; const exponentBits = (hi >>> 20) & 2047; const significandBits = (hi & 1048575) * 4294967296 + lo; const exponent = exponentBits === 0 ? -1022 : exponentBits - 1023; let significand = exponentBits === 0 ? 0 : 1; significand += significandBits / 2 ** 52; significand *= signBit === 0 ? 1 : -1; return { exponent, significand }; } function positiveNumberToInt64(n) { return [~~(n / 4294967296), n >>> 0]; } function indexInDoubleFromDecomp(exponent, significand) { if (exponent === -1022) { const rescaledSignificand2 = significand * 2 ** 52; return positiveNumberToInt64(rescaledSignificand2); } const rescaledSignificand = (significand - 1) * 2 ** 52; const exponentOnlyHigh = (exponent + 1023) * 2 ** 20; const index = positiveNumberToInt64(rescaledSignificand); index[0] += exponentOnlyHigh; return index; } function doubleToIndex(d) { if (d === safePositiveInfinity3) { return clone64(INDEX_POSITIVE_INFINITY); } if (d === safeNegativeInfinity2) { return clone64(INDEX_NEGATIVE_INFINITY); } const decomp = decomposeDouble(d); const exponent = decomp.exponent; const significand = decomp.significand; if (d > 0 || (d === 0 && 1 / d === safePositiveInfinity3)) { return { sign: 1, data: indexInDoubleFromDecomp(exponent, significand) }; } else { const indexOpposite = indexInDoubleFromDecomp(exponent, -significand); if (indexOpposite[1] === 4294967295) { indexOpposite[0] += 1; indexOpposite[1] = 0; } else { indexOpposite[1] += 1; } return { sign: -1, data: indexOpposite }; } } function indexToDouble(index) { if (index.sign === -1) { const indexOpposite = { sign: 1, data: [index.data[0], index.data[1]] }; if (indexOpposite.data[1] === 0) { indexOpposite.data[0] -= 1; indexOpposite.data[1] = 4294967295; } else { indexOpposite.data[1] -= 1; } return -indexToDouble(indexOpposite); } if (isEqual64(index, INDEX_POSITIVE_INFINITY)) { return safePositiveInfinity3; } if (index.data[0] < 2097152) { return (index.data[0] * 4294967296 + index.data[1]) * 2 ** -1074; } const postIndexHigh = index.data[0] - 2097152; const exponent = -1021 + (postIndexHigh >> 20); const significand = 1 + ((postIndexHigh & 1048575) * 2 ** 32 + index.data[1]) * safeEpsilon; return significand * 2 ** exponent; } // ../../../node_modules/fast-check/lib/esm/arbitrary/double.js var safeNumberIsNaN5 = Number.isNaN; var safeNegativeInfinity3 = Number.NEGATIVE_INFINITY; var safePositiveInfinity4 = Number.POSITIVE_INFINITY; var safeMaxValue = Number.MAX_VALUE; var safeNaN2 = Number.NaN; function safeDoubleToIndex(d, constraintsLabel) { if (safeNumberIsNaN5(d)) { throw new Error( 'fc.double constraints.' + constraintsLabel + ' must be a 64-bit float', ); } return doubleToIndex(d); } function unmapperDoubleToIndex(value) { if (typeof value !== 'number') throw new Error('Unsupported type'); return doubleToIndex(value); } function double(constraints = {}) { const { noDefaultInfinity = false, noNaN = false, minExcluded = false, maxExcluded = false, min = noDefaultInfinity ? -safeMaxValue : safeNegativeInfinity3, max = noDefaultInfinity ? safeMaxValue : safePositiveInfinity4, } = constraints; const minIndexRaw = safeDoubleToIndex(min, 'min'); const minIndex = minExcluded ? add64(minIndexRaw, Unit64) : minIndexRaw; const maxIndexRaw = safeDoubleToIndex(max, 'max'); const maxIndex = maxExcluded ? substract64(maxIndexRaw, Unit64) : maxIndexRaw; if (isStrictlySmaller64(maxIndex, minIndex)) { throw new Error( 'fc.double constraints.min must be smaller or equal to constraints.max', ); } if (noNaN) { return arrayInt64(minIndex, maxIndex).map( indexToDouble, unmapperDoubleToIndex, ); } const positiveMaxIdx = isStrictlyPositive64(maxIndex); const minIndexWithNaN = positiveMaxIdx ? minIndex : substract64(minIndex, Unit64); const maxIndexWithNaN = positiveMaxIdx ? add64(maxIndex, Unit64) : maxIndex; return arrayInt64(minIndexWithNaN, maxIndexWithNaN).map( (index) => { if ( isStrictlySmaller64(maxIndex, index) || isStrictlySmaller64(index, minIndex) ) return safeNaN2; else return indexToDouble(index); }, (value) => { if (typeof value !== 'number') throw new Error('Unsupported type'); if (safeNumberIsNaN5(value)) return !isEqual64(maxIndex, maxIndexWithNaN) ? maxIndexWithNaN : minIndexWithNaN; return doubleToIndex(value); }, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/FloatHelpers.js var safeNegativeInfinity4 = Number.NEGATIVE_INFINITY; var safePositiveInfinity5 = Number.POSITIVE_INFINITY; var MIN_VALUE_32 = 2 ** -126 * 2 ** -23; var MAX_VALUE_32 = 2 ** 127 * (1 + (2 ** 23 - 1) / 2 ** 23); var EPSILON_32 = 2 ** -23; var INDEX_POSITIVE_INFINITY2 = 2139095040; var INDEX_NEGATIVE_INFINITY2 = -2139095041; var f32 = new Float32Array(1); var u322 = new Uint32Array(f32.buffer, f32.byteOffset); function bitCastFloatToUInt32(f) { f32[0] = f; return u322[0]; } function decomposeFloat(f) { const bits = bitCastFloatToUInt32(f); const signBit = bits >>> 31; const exponentBits = (bits >>> 23) & 255; const significandBits = bits & 8388607; const exponent = exponentBits === 0 ? -126 : exponentBits - 127; let significand = exponentBits === 0 ? 0 : 1; significand += significandBits / 2 ** 23; significand *= signBit === 0 ? 1 : -1; return { exponent, significand }; } function indexInFloatFromDecomp(exponent, significand) { if (exponent === -126) { return significand * 8388608; } return (exponent + 127) * 8388608 + (significand - 1) * 8388608; } function floatToIndex(f) { if (f === safePositiveInfinity5) { return INDEX_POSITIVE_INFINITY2; } if (f === safeNegativeInfinity4) { return INDEX_NEGATIVE_INFINITY2; } const decomp = decomposeFloat(f); const exponent = decomp.exponent; const significand = decomp.significand; if (f > 0 || (f === 0 && 1 / f === safePositiveInfinity5)) { return indexInFloatFromDecomp(exponent, significand); } else { return -indexInFloatFromDecomp(exponent, -significand) - 1; } } function indexToFloat(index) { if (index < 0) { return -indexToFloat(-index - 1); } if (index === INDEX_POSITIVE_INFINITY2) { return safePositiveInfinity5; } if (index < 16777216) { return index * 2 ** -149; } const postIndex = index - 16777216; const exponent = -125 + (postIndex >> 23); const significand = 1 + (postIndex & 8388607) / 8388608; return significand * 2 ** exponent; } // ../../../node_modules/fast-check/lib/esm/arbitrary/float.js var safeNumberIsNaN6 = Number.isNaN; var safeMathFround = Math.fround; var safeNegativeInfinity5 = Number.NEGATIVE_INFINITY; var safePositiveInfinity6 = Number.POSITIVE_INFINITY; var safeNaN3 = Number.NaN; function safeFloatToIndex(f, constraintsLabel) { const conversionTrick = 'you can convert any double to a 32-bit float by using `Math.fround(myDouble)`'; const errorMessage = 'fc.float constraints.' + constraintsLabel + ' must be a 32-bit float - ' + conversionTrick; if (safeNumberIsNaN6(f) || safeMathFround(f) !== f) { throw new Error(errorMessage); } return floatToIndex(f); } function unmapperFloatToIndex(value) { if (typeof value !== 'number') throw new Error('Unsupported type'); return floatToIndex(value); } function float(constraints = {}) { const { noDefaultInfinity = false, noNaN = false, minExcluded = false, maxExcluded = false, min = noDefaultInfinity ? -MAX_VALUE_32 : safeNegativeInfinity5, max = noDefaultInfinity ? MAX_VALUE_32 : safePositiveInfinity6, } = constraints; const minIndexRaw = safeFloatToIndex(min, 'min'); const minIndex = minExcluded ? minIndexRaw + 1 : minIndexRaw; const maxIndexRaw = safeFloatToIndex(max, 'max'); const maxIndex = maxExcluded ? maxIndexRaw - 1 : maxIndexRaw; if (minIndex > maxIndex) { throw new Error( 'fc.float constraints.min must be smaller or equal to constraints.max', ); } if (noNaN) { return integer({ min: minIndex, max: maxIndex }).map( indexToFloat, unmapperFloatToIndex, ); } const minIndexWithNaN = maxIndex > 0 ? minIndex : minIndex - 1; const maxIndexWithNaN = maxIndex > 0 ? maxIndex + 1 : maxIndex; return integer({ min: minIndexWithNaN, max: maxIndexWithNaN }).map( (index) => { if (index > maxIndex || index < minIndex) return safeNaN3; else return indexToFloat(index); }, (value) => { if (typeof value !== 'number') throw new Error('Unsupported type'); if (safeNumberIsNaN6(value)) return maxIndex !== maxIndexWithNaN ? maxIndexWithNaN : minIndexWithNaN; return floatToIndex(value); }, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/TextEscaper.js function escapeForTemplateString(originalText) { return originalText.replace(/([$`\\])/g, '\\$1').replace(/\r/g, '\\r'); } function escapeForMultilineComments(originalText) { return originalText.replace(/\*\//g, '*\\/'); } // ../../../node_modules/fast-check/lib/esm/utils/hash.js var crc32Table = [ 0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918e3, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117, ]; function hash(repr) { let crc = 4294967295; for (let idx = 0; idx < repr.length; ++idx) { const c = safeCharCodeAt(repr, idx); if (c < 128) { crc = crc32Table[(crc & 255) ^ c] ^ (crc >> 8); } else if (c < 2048) { crc = crc32Table[(crc & 255) ^ (192 | ((c >> 6) & 31))] ^ (crc >> 8); crc = crc32Table[(crc & 255) ^ (128 | (c & 63))] ^ (crc >> 8); } else if (c >= 55296 && c < 57344) { const cNext = safeCharCodeAt(repr, ++idx); if (c >= 56320 || cNext < 56320 || cNext > 57343 || Number.isNaN(cNext)) { idx -= 1; crc = crc32Table[(crc & 255) ^ 239] ^ (crc >> 8); crc = crc32Table[(crc & 255) ^ 191] ^ (crc >> 8); crc = crc32Table[(crc & 255) ^ 189] ^ (crc >> 8); } else { const c1 = (c & 1023) + 64; const c2 = cNext & 1023; crc = crc32Table[(crc & 255) ^ (240 | ((c1 >> 8) & 7))] ^ (crc >> 8); crc = crc32Table[(crc & 255) ^ (128 | ((c1 >> 2) & 63))] ^ (crc >> 8); crc = crc32Table[(crc & 255) ^ (128 | ((c2 >> 6) & 15) | ((c1 & 3) << 4))] ^ (crc >> 8); crc = crc32Table[(crc & 255) ^ (128 | (c2 & 63))] ^ (crc >> 8); } } else { crc = crc32Table[(crc & 255) ^ (224 | ((c >> 12) & 15))] ^ (crc >> 8); crc = crc32Table[(crc & 255) ^ (128 | ((c >> 6) & 63))] ^ (crc >> 8); crc = crc32Table[(crc & 255) ^ (128 | (c & 63))] ^ (crc >> 8); } } return (crc | 0) + 2147483648; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/CompareFunctionArbitraryBuilder.js var safeObjectAssign5 = Object.assign; var safeObjectKeys2 = Object.keys; function buildCompareFunctionArbitrary(cmp) { return tuple( integer().noShrink(), integer({ min: 1, max: 4294967295 }).noShrink(), ).map(([seed, hashEnvSize]) => { const producer = () => { const recorded = {}; const f = (a, b) => { const reprA = stringify(a); const reprB = stringify(b); const hA = hash(`${seed}${reprA}`) % hashEnvSize; const hB = hash(`${seed}${reprB}`) % hashEnvSize; const val = cmp(hA, hB); recorded[`[${reprA},${reprB}]`] = val; return val; }; return safeObjectAssign5(f, { toString: () => { const seenValues = safeObjectKeys2(recorded) .sort() .map((k) => `${k} => ${stringify(recorded[k])}`) .map((line) => `/* ${escapeForMultilineComments(line)} */`); return `function(a, b) { // With hash and stringify coming from fast-check${ seenValues.length !== 0 ? ` ${safeJoin(seenValues, '\n ')}` : '' } const cmp = ${cmp}; const hA = hash('${seed}' + stringify(a)) % ${hashEnvSize}; const hB = hash('${seed}' + stringify(b)) % ${hashEnvSize}; return cmp(hA, hB); }`; }, [cloneMethod]: producer, }); }; return producer(); }); } // ../../../node_modules/fast-check/lib/esm/arbitrary/compareBooleanFunc.js var safeObjectAssign6 = Object.assign; function compareBooleanFunc() { return buildCompareFunctionArbitrary( safeObjectAssign6((hA, hB) => hA < hB, { toString() { return '(hA, hB) => hA < hB'; }, }), ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/compareFunc.js var safeObjectAssign7 = Object.assign; function compareFunc() { return buildCompareFunctionArbitrary( safeObjectAssign7((hA, hB) => hA - hB, { toString() { return '(hA, hB) => hA - hB'; }, }), ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/func.js var safeObjectDefineProperties = Object.defineProperties; var safeObjectKeys3 = Object.keys; function func(arb) { return tuple(array(arb, { minLength: 1 }), integer().noShrink()).map( ([outs, seed]) => { const producer = () => { const recorded = {}; const f = (...args) => { const repr = stringify(args); const val = outs[hash(`${seed}${repr}`) % outs.length]; recorded[repr] = val; return hasCloneMethod(val) ? val[cloneMethod]() : val; }; function prettyPrint2(stringifiedOuts) { const seenValues = safeMap( safeMap( safeSort(safeObjectKeys3(recorded)), (k) => `${k} => ${stringify(recorded[k])}`, ), (line) => `/* ${escapeForMultilineComments(line)} */`, ); return `function(...args) { // With hash and stringify coming from fast-check${ seenValues.length !== 0 ? ` ${seenValues.join('\n ')}` : '' } const outs = ${stringifiedOuts}; return outs[hash('${seed}' + stringify(args)) % outs.length]; }`; } return safeObjectDefineProperties(f, { toString: { value: () => prettyPrint2(stringify(outs)) }, [toStringMethod]: { value: () => prettyPrint2(stringify(outs)) }, [asyncToStringMethod]: { value: async () => prettyPrint2(await asyncStringify(outs)), }, [cloneMethod]: { value: producer, configurable: true }, }); }; return producer(); }, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/maxSafeInteger.js var safeMinSafeInteger = Number.MIN_SAFE_INTEGER; var safeMaxSafeInteger2 = Number.MAX_SAFE_INTEGER; function maxSafeInteger() { return new IntegerArbitrary(safeMinSafeInteger, safeMaxSafeInteger2); } // ../../../node_modules/fast-check/lib/esm/arbitrary/maxSafeNat.js var safeMaxSafeInteger3 = Number.MAX_SAFE_INTEGER; function maxSafeNat() { return new IntegerArbitrary(0, safeMaxSafeInteger3); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/NatToStringifiedNat.js var safeNumberParseInt = Number.parseInt; function natToStringifiedNatMapper(options) { const [style, v] = options; switch (style) { case 'oct': return `0${safeNumberToString(v, 8)}`; case 'hex': return `0x${safeNumberToString(v, 16)}`; case 'dec': default: return `${v}`; } } function tryParseStringifiedNat(stringValue, radix) { const parsedNat = safeNumberParseInt(stringValue, radix); if (safeNumberToString(parsedNat, radix) !== stringValue) { throw new Error('Invalid value'); } return parsedNat; } function natToStringifiedNatUnmapper(value) { if (typeof value !== 'string') { throw new Error('Invalid type'); } if (value.length >= 2 && value[0] === '0') { if (value[1] === 'x') { return ['hex', tryParseStringifiedNat(safeSubstring(value, 2), 16)]; } return ['oct', tryParseStringifiedNat(safeSubstring(value, 1), 8)]; } return ['dec', tryParseStringifiedNat(value, 10)]; } // ../../../node_modules/fast-check/lib/esm/arbitrary/ipV4.js function dotJoinerMapper(data) { return safeJoin(data, '.'); } function dotJoinerUnmapper(value) { if (typeof value !== 'string') { throw new Error('Invalid type'); } return safeMap(safeSplit(value, '.'), (v) => tryParseStringifiedNat(v, 10)); } function ipV4() { return tuple(nat(255), nat(255), nat(255), nat(255)).map( dotJoinerMapper, dotJoinerUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/StringifiedNatArbitraryBuilder.js function buildStringifiedNatArbitrary(maxValue) { return tuple(constantFrom('dec', 'oct', 'hex'), nat(maxValue)).map( natToStringifiedNatMapper, natToStringifiedNatUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/ipV4Extended.js function dotJoinerMapper2(data) { return safeJoin(data, '.'); } function dotJoinerUnmapper2(value) { if (typeof value !== 'string') { throw new Error('Invalid type'); } return safeSplit(value, '.'); } function ipV4Extended() { return oneof( tuple( buildStringifiedNatArbitrary(255), buildStringifiedNatArbitrary(255), buildStringifiedNatArbitrary(255), buildStringifiedNatArbitrary(255), ).map(dotJoinerMapper2, dotJoinerUnmapper2), tuple( buildStringifiedNatArbitrary(255), buildStringifiedNatArbitrary(255), buildStringifiedNatArbitrary(65535), ).map(dotJoinerMapper2, dotJoinerUnmapper2), tuple( buildStringifiedNatArbitrary(255), buildStringifiedNatArbitrary(16777215), ).map(dotJoinerMapper2, dotJoinerUnmapper2), buildStringifiedNatArbitrary(4294967295), ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/CodePointsToString.js function codePointsToStringMapper(tab) { return safeJoin(tab, ''); } function codePointsToStringUnmapper(value) { if (typeof value !== 'string') { throw new Error('Cannot unmap the passed value'); } return [...value]; } // ../../../node_modules/fast-check/lib/esm/arbitrary/hexaString.js var safeObjectAssign8 = Object.assign; function hexaString(constraints = {}) { const charArbitrary = hexa(); const experimentalCustomSlices = createSlicesForString( charArbitrary, codePointsToStringUnmapper, ); const enrichedConstraints = safeObjectAssign8( safeObjectAssign8({}, constraints), { experimentalCustomSlices, }, ); return array(charArbitrary, enrichedConstraints).map( codePointsToStringMapper, codePointsToStringUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/EntitiesToIPv6.js function readBh(value) { if (value.length === 0) return []; else return safeSplit(value, ':'); } function extractEhAndL(value) { const valueSplits = safeSplit(value, ':'); if ( valueSplits.length >= 2 && valueSplits[valueSplits.length - 1].length <= 4 ) { return [ safeSlice(valueSplits, 0, valueSplits.length - 2), `${valueSplits[valueSplits.length - 2]}:${valueSplits[valueSplits.length - 1]}`, ]; } return [ safeSlice(valueSplits, 0, valueSplits.length - 1), valueSplits[valueSplits.length - 1], ]; } function fullySpecifiedMapper(data) { return `${safeJoin(data[0], ':')}:${data[1]}`; } function fullySpecifiedUnmapper(value) { if (typeof value !== 'string') throw new Error('Invalid type'); return extractEhAndL(value); } function onlyTrailingMapper(data) { return `::${safeJoin(data[0], ':')}:${data[1]}`; } function onlyTrailingUnmapper(value) { if (typeof value !== 'string') throw new Error('Invalid type'); if (!safeStartsWith(value, '::')) throw new Error('Invalid value'); return extractEhAndL(safeSubstring(value, 2)); } function multiTrailingMapper(data) { return `${safeJoin(data[0], ':')}::${safeJoin(data[1], ':')}:${data[2]}`; } function multiTrailingUnmapper(value) { if (typeof value !== 'string') throw new Error('Invalid type'); const [bhString, trailingString] = safeSplit(value, '::', 2); const [eh, l] = extractEhAndL(trailingString); return [readBh(bhString), eh, l]; } function multiTrailingMapperOne(data) { return multiTrailingMapper([data[0], [data[1]], data[2]]); } function multiTrailingUnmapperOne(value) { const out = multiTrailingUnmapper(value); return [out[0], safeJoin(out[1], ':'), out[2]]; } function singleTrailingMapper(data) { return `${safeJoin(data[0], ':')}::${data[1]}`; } function singleTrailingUnmapper(value) { if (typeof value !== 'string') throw new Error('Invalid type'); const [bhString, trailing] = safeSplit(value, '::', 2); return [readBh(bhString), trailing]; } function noTrailingMapper(data) { return `${safeJoin(data[0], ':')}::`; } function noTrailingUnmapper(value) { if (typeof value !== 'string') throw new Error('Invalid type'); if (!safeEndsWith(value, '::')) throw new Error('Invalid value'); return [readBh(safeSubstring(value, 0, value.length - 2))]; } // ../../../node_modules/fast-check/lib/esm/arbitrary/ipV6.js function h16sTol32Mapper([a, b]) { return `${a}:${b}`; } function h16sTol32Unmapper(value) { if (typeof value !== 'string') throw new Error('Invalid type'); if (!value.includes(':')) throw new Error('Invalid value'); return value.split(':', 2); } function ipV6() { const h16Arb = hexaString({ minLength: 1, maxLength: 4, size: 'max' }); const ls32Arb = oneof( tuple(h16Arb, h16Arb).map(h16sTol32Mapper, h16sTol32Unmapper), ipV4(), ); return oneof( tuple( array(h16Arb, { minLength: 6, maxLength: 6, size: 'max' }), ls32Arb, ).map(fullySpecifiedMapper, fullySpecifiedUnmapper), tuple( array(h16Arb, { minLength: 5, maxLength: 5, size: 'max' }), ls32Arb, ).map(onlyTrailingMapper, onlyTrailingUnmapper), tuple( array(h16Arb, { minLength: 0, maxLength: 1, size: 'max' }), array(h16Arb, { minLength: 4, maxLength: 4, size: 'max' }), ls32Arb, ).map(multiTrailingMapper, multiTrailingUnmapper), tuple( array(h16Arb, { minLength: 0, maxLength: 2, size: 'max' }), array(h16Arb, { minLength: 3, maxLength: 3, size: 'max' }), ls32Arb, ).map(multiTrailingMapper, multiTrailingUnmapper), tuple( array(h16Arb, { minLength: 0, maxLength: 3, size: 'max' }), array(h16Arb, { minLength: 2, maxLength: 2, size: 'max' }), ls32Arb, ).map(multiTrailingMapper, multiTrailingUnmapper), tuple( array(h16Arb, { minLength: 0, maxLength: 4, size: 'max' }), h16Arb, ls32Arb, ).map(multiTrailingMapperOne, multiTrailingUnmapperOne), tuple( array(h16Arb, { minLength: 0, maxLength: 5, size: 'max' }), ls32Arb, ).map(singleTrailingMapper, singleTrailingUnmapper), tuple( array(h16Arb, { minLength: 0, maxLength: 6, size: 'max' }), h16Arb, ).map(singleTrailingMapper, singleTrailingUnmapper), tuple(array(h16Arb, { minLength: 0, maxLength: 7, size: 'max' })).map( noTrailingMapper, noTrailingUnmapper, ), ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/LazyArbitrary.js var LazyArbitrary = class extends Arbitrary { constructor(name) { super(); this.name = name; this.underlying = null; } generate(mrng, biasFactor) { if (!this.underlying) { throw new Error( `Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`, ); } return this.underlying.generate(mrng, biasFactor); } canShrinkWithoutContext(value) { if (!this.underlying) { throw new Error( `Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`, ); } return this.underlying.canShrinkWithoutContext(value); } shrink(value, context2) { if (!this.underlying) { throw new Error( `Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`, ); } return this.underlying.shrink(value, context2); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/letrec.js var safeObjectCreate2 = Object.create; function letrec(builder) { const lazyArbs = safeObjectCreate2(null); const tie = (key) => { if (!safeHasOwnProperty(lazyArbs, key)) { lazyArbs[key] = new LazyArbitrary(String(key)); } return lazyArbs[key]; }; const strictArbs = builder(tie); for (const key in strictArbs) { if (!safeHasOwnProperty(strictArbs, key)) { continue; } const lazyAtKey = lazyArbs[key]; const lazyArb = lazyAtKey !== void 0 ? lazyAtKey : new LazyArbitrary(key); lazyArb.underlying = strictArbs[key]; lazyArbs[key] = lazyArb; } return strictArbs; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/WordsToLorem.js function wordsToJoinedStringMapper(words) { return safeJoin( safeMap(words, (w) => w[w.length - 1] === ',' ? safeSubstring(w, 0, w.length - 1) : w, ), ' ', ); } function wordsToJoinedStringUnmapperFor(wordsArbitrary) { return function wordsToJoinedStringUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported type'); } const words = []; for (const candidate of safeSplit(value, ' ')) { if (wordsArbitrary.canShrinkWithoutContext(candidate)) safePush(words, candidate); else if (wordsArbitrary.canShrinkWithoutContext(candidate + ',')) safePush(words, candidate + ','); else throw new Error('Unsupported word'); } return words; }; } function wordsToSentenceMapper(words) { let sentence = safeJoin(words, ' '); if (sentence[sentence.length - 1] === ',') { sentence = safeSubstring(sentence, 0, sentence.length - 1); } return safeToUpperCase(sentence[0]) + safeSubstring(sentence, 1) + '.'; } function wordsToSentenceUnmapperFor(wordsArbitrary) { return function wordsToSentenceUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported type'); } if ( value.length < 2 || value[value.length - 1] !== '.' || value[value.length - 2] === ',' || safeToUpperCase(safeToLowerCase(value[0])) !== value[0] ) { throw new Error('Unsupported value'); } const adaptedValue = safeToLowerCase(value[0]) + safeSubstring(value, 1, value.length - 1); const words = []; const candidates = safeSplit(adaptedValue, ' '); for (let idx = 0; idx !== candidates.length; ++idx) { const candidate = candidates[idx]; if (wordsArbitrary.canShrinkWithoutContext(candidate)) safePush(words, candidate); else if ( idx === candidates.length - 1 && wordsArbitrary.canShrinkWithoutContext(candidate + ',') ) safePush(words, candidate + ','); else throw new Error('Unsupported word'); } return words; }; } function sentencesToParagraphMapper(sentences) { return safeJoin(sentences, ' '); } function sentencesToParagraphUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported type'); } const sentences = safeSplit(value, '. '); for (let idx = 0; idx < sentences.length - 1; ++idx) { sentences[idx] += '.'; } return sentences; } // ../../../node_modules/fast-check/lib/esm/arbitrary/lorem.js var h = (v, w) => { return { arbitrary: constant(v), weight: w }; }; function loremWord() { return oneof( h('non', 6), h('adipiscing', 5), h('ligula', 5), h('enim', 5), h('pellentesque', 5), h('in', 5), h('augue', 5), h('et', 5), h('nulla', 5), h('lorem', 4), h('sit', 4), h('sed', 4), h('diam', 4), h('fermentum', 4), h('ut', 4), h('eu', 4), h('aliquam', 4), h('mauris', 4), h('vitae', 4), h('felis', 4), h('ipsum', 3), h('dolor', 3), h('amet,', 3), h('elit', 3), h('euismod', 3), h('mi', 3), h('orci', 3), h('erat', 3), h('praesent', 3), h('egestas', 3), h('leo', 3), h('vel', 3), h('sapien', 3), h('integer', 3), h('curabitur', 3), h('convallis', 3), h('purus', 3), h('risus', 2), h('suspendisse', 2), h('lectus', 2), h('nec,', 2), h('ultricies', 2), h('sed,', 2), h('cras', 2), h('elementum', 2), h('ultrices', 2), h('maecenas', 2), h('massa,', 2), h('varius', 2), h('a,', 2), h('semper', 2), h('proin', 2), h('nec', 2), h('nisl', 2), h('amet', 2), h('duis', 2), h('congue', 2), h('libero', 2), h('vestibulum', 2), h('pede', 2), h('blandit', 2), h('sodales', 2), h('ante', 2), h('nibh', 2), h('ac', 2), h('aenean', 2), h('massa', 2), h('suscipit', 2), h('sollicitudin', 2), h('fusce', 2), h('tempus', 2), h('aliquam,', 2), h('nunc', 2), h('ullamcorper', 2), h('rhoncus', 2), h('metus', 2), h('faucibus,', 2), h('justo', 2), h('magna', 2), h('at', 2), h('tincidunt', 2), h('consectetur', 1), h('tortor,', 1), h('dignissim', 1), h('congue,', 1), h('non,', 1), h('porttitor,', 1), h('nonummy', 1), h('molestie,', 1), h('est', 1), h('eleifend', 1), h('mi,', 1), h('arcu', 1), h('scelerisque', 1), h('vitae,', 1), h('consequat', 1), h('in,', 1), h('pretium', 1), h('volutpat', 1), h('pharetra', 1), h('tempor', 1), h('bibendum', 1), h('odio', 1), h('dui', 1), h('primis', 1), h('faucibus', 1), h('luctus', 1), h('posuere', 1), h('cubilia', 1), h('curae,', 1), h('hendrerit', 1), h('velit', 1), h('mauris,', 1), h('gravida', 1), h('ornare', 1), h('ut,', 1), h('pulvinar', 1), h('varius,', 1), h('turpis', 1), h('nibh,', 1), h('eros', 1), h('id', 1), h('aliquet', 1), h('quis', 1), h('lobortis', 1), h('consectetuer', 1), h('morbi', 1), h('vehicula', 1), h('tortor', 1), h('tellus,', 1), h('id,', 1), h('eu,', 1), h('quam', 1), h('feugiat,', 1), h('posuere,', 1), h('iaculis', 1), h('lectus,', 1), h('tristique', 1), h('mollis,', 1), h('nisl,', 1), h('vulputate', 1), h('sem', 1), h('vivamus', 1), h('placerat', 1), h('imperdiet', 1), h('cursus', 1), h('rutrum', 1), h('iaculis,', 1), h('augue,', 1), h('lacus', 1), ); } function lorem(constraints = {}) { const { maxCount, mode = 'words', size } = constraints; if (maxCount !== void 0 && maxCount < 1) { throw new Error(`lorem has to produce at least one word/sentence`); } const wordArbitrary = loremWord(); if (mode === 'sentences') { const sentence = array(wordArbitrary, { minLength: 1, size: 'small' }).map( wordsToSentenceMapper, wordsToSentenceUnmapperFor(wordArbitrary), ); return array(sentence, { minLength: 1, maxLength: maxCount, size }).map( sentencesToParagraphMapper, sentencesToParagraphUnmapper, ); } else { return array(wordArbitrary, { minLength: 1, maxLength: maxCount, size, }).map( wordsToJoinedStringMapper, wordsToJoinedStringUnmapperFor(wordArbitrary), ); } } // ../../../node_modules/fast-check/lib/esm/arbitrary/memo.js var contextRemainingDepth = 10; function memo(builder) { const previous = {}; return (maxDepth) => { const n = maxDepth !== void 0 ? maxDepth : contextRemainingDepth; if (!safeHasOwnProperty(previous, n)) { const prev = contextRemainingDepth; contextRemainingDepth = n - 1; previous[n] = builder(n); contextRemainingDepth = prev; } return previous[n]; }; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/ToggleFlags.js function countToggledBits(n) { let count = 0; while (n > SBigInt(0)) { if (n & SBigInt(1)) ++count; n >>= SBigInt(1); } return count; } function computeNextFlags(flags, nextSize) { const allowedMask = (SBigInt(1) << SBigInt(nextSize)) - SBigInt(1); const preservedFlags = flags & allowedMask; let numMissingFlags = countToggledBits(flags - preservedFlags); let nFlags = preservedFlags; for ( let mask = SBigInt(1); mask <= allowedMask && numMissingFlags !== 0; mask <<= SBigInt(1) ) { if (!(nFlags & mask)) { nFlags |= mask; --numMissingFlags; } } return nFlags; } function computeTogglePositions(chars, toggleCase) { const positions = []; for (let idx = chars.length - 1; idx !== -1; --idx) { if (toggleCase(chars[idx]) !== chars[idx]) safePush(positions, idx); } return positions; } function computeFlagsFromChars(untoggledChars, toggledChars, togglePositions) { let flags = SBigInt(0); for ( let idx = 0, mask = SBigInt(1); idx !== togglePositions.length; ++idx, mask <<= SBigInt(1) ) { if ( untoggledChars[togglePositions[idx]] !== toggledChars[togglePositions[idx]] ) { flags |= mask; } } return flags; } function applyFlagsOnChars(chars, flags, togglePositions, toggleCase) { for ( let idx = 0, mask = SBigInt(1); idx !== togglePositions.length; ++idx, mask <<= SBigInt(1) ) { if (flags & mask) chars[togglePositions[idx]] = toggleCase(chars[togglePositions[idx]]); } } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/MixedCaseArbitrary.js var MixedCaseArbitrary = class extends Arbitrary { constructor(stringArb, toggleCase, untoggleAll) { super(); this.stringArb = stringArb; this.toggleCase = toggleCase; this.untoggleAll = untoggleAll; } buildContextFor(rawStringValue, flagsValue) { return { rawString: rawStringValue.value, rawStringContext: rawStringValue.context, flags: flagsValue.value, flagsContext: flagsValue.context, }; } generate(mrng, biasFactor) { const rawStringValue = this.stringArb.generate(mrng, biasFactor); const chars = [...rawStringValue.value]; const togglePositions = computeTogglePositions(chars, this.toggleCase); const flagsArb = bigUintN(togglePositions.length); const flagsValue = flagsArb.generate(mrng, void 0); applyFlagsOnChars( chars, flagsValue.value, togglePositions, this.toggleCase, ); return new Value( safeJoin(chars, ''), this.buildContextFor(rawStringValue, flagsValue), ); } canShrinkWithoutContext(value) { if (typeof value !== 'string') { return false; } return this.untoggleAll !== void 0 ? this.stringArb.canShrinkWithoutContext(this.untoggleAll(value)) : this.stringArb.canShrinkWithoutContext(value); } shrink(value, context2) { let contextSafe; if (context2 !== void 0) { contextSafe = context2; } else { if (this.untoggleAll !== void 0) { const untoggledValue = this.untoggleAll(value); const valueChars = [...value]; const untoggledValueChars = [...untoggledValue]; const togglePositions = computeTogglePositions( untoggledValueChars, this.toggleCase, ); contextSafe = { rawString: untoggledValue, rawStringContext: void 0, flags: computeFlagsFromChars( untoggledValueChars, valueChars, togglePositions, ), flagsContext: void 0, }; } else { contextSafe = { rawString: value, rawStringContext: void 0, flags: SBigInt(0), flagsContext: void 0, }; } } const rawString = contextSafe.rawString; const flags = contextSafe.flags; return this.stringArb .shrink(rawString, contextSafe.rawStringContext) .map((nRawStringValue) => { const nChars = [...nRawStringValue.value]; const nTogglePositions = computeTogglePositions( nChars, this.toggleCase, ); const nFlags = computeNextFlags(flags, nTogglePositions.length); applyFlagsOnChars(nChars, nFlags, nTogglePositions, this.toggleCase); return new Value( safeJoin(nChars, ''), this.buildContextFor(nRawStringValue, new Value(nFlags, void 0)), ); }) .join( makeLazy(() => { const chars = [...rawString]; const togglePositions = computeTogglePositions( chars, this.toggleCase, ); return bigUintN(togglePositions.length) .shrink(flags, contextSafe.flagsContext) .map((nFlagsValue) => { const nChars = safeSlice(chars); applyFlagsOnChars( nChars, nFlagsValue.value, togglePositions, this.toggleCase, ); return new Value( safeJoin(nChars, ''), this.buildContextFor( new Value(rawString, contextSafe.rawStringContext), nFlagsValue, ), ); }); }), ); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/mixedCase.js function defaultToggleCase(rawChar) { const upper = safeToUpperCase(rawChar); if (upper !== rawChar) return upper; return safeToLowerCase(rawChar); } function mixedCase(stringArb, constraints) { if (typeof SBigInt === 'undefined') { throw new SError(`mixedCase requires BigInt support`); } const toggleCase = (constraints && constraints.toggleCase) || defaultToggleCase; const untoggleAll = constraints && constraints.untoggleAll; return new MixedCaseArbitrary(stringArb, toggleCase, untoggleAll); } // ../../../node_modules/fast-check/lib/esm/arbitrary/float32Array.js function toTypedMapper(data) { return SFloat32Array.from(data); } function fromTypedUnmapper(value) { if (!(value instanceof SFloat32Array)) throw new Error('Unexpected type'); return [...value]; } function float32Array(constraints = {}) { return array(float(constraints), constraints).map( toTypedMapper, fromTypedUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/float64Array.js function toTypedMapper2(data) { return SFloat64Array.from(data); } function fromTypedUnmapper2(value) { if (!(value instanceof SFloat64Array)) throw new Error('Unexpected type'); return [...value]; } function float64Array(constraints = {}) { return array(double(constraints), constraints).map( toTypedMapper2, fromTypedUnmapper2, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/TypedIntArrayArbitraryBuilder.js var __rest = function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === 'function') for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if ( e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]) ) t[p[i]] = s[p[i]]; } return t; }; function typedIntArrayArbitraryArbitraryBuilder( constraints, defaultMin, defaultMax, TypedArrayClass, arbitraryBuilder, ) { const generatorName = TypedArrayClass.name; const { min = defaultMin, max = defaultMax } = constraints, arrayConstraints = __rest(constraints, ['min', 'max']); if (min > max) { throw new Error( `Invalid range passed to ${generatorName}: min must be lower than or equal to max`, ); } if (min < defaultMin) { throw new Error( `Invalid min value passed to ${generatorName}: min must be greater than or equal to ${defaultMin}`, ); } if (max > defaultMax) { throw new Error( `Invalid max value passed to ${generatorName}: max must be lower than or equal to ${defaultMax}`, ); } return array(arbitraryBuilder({ min, max }), arrayConstraints).map( (data) => TypedArrayClass.from(data), (value) => { if (!(value instanceof TypedArrayClass)) throw new Error('Invalid type'); return [...value]; }, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/int16Array.js function int16Array(constraints = {}) { return typedIntArrayArbitraryArbitraryBuilder( constraints, -32768, 32767, SInt16Array, integer, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/int32Array.js function int32Array(constraints = {}) { return typedIntArrayArbitraryArbitraryBuilder( constraints, -2147483648, 2147483647, SInt32Array, integer, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/int8Array.js function int8Array(constraints = {}) { return typedIntArrayArbitraryArbitraryBuilder( constraints, -128, 127, SInt8Array, integer, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/uint16Array.js function uint16Array(constraints = {}) { return typedIntArrayArbitraryArbitraryBuilder( constraints, 0, 65535, SUint16Array, integer, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/uint32Array.js function uint32Array(constraints = {}) { return typedIntArrayArbitraryArbitraryBuilder( constraints, 0, 4294967295, SUint32Array, integer, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/uint8Array.js function uint8Array(constraints = {}) { return typedIntArrayArbitraryArbitraryBuilder( constraints, 0, 255, SUint8Array, integer, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/uint8ClampedArray.js function uint8ClampedArray(constraints = {}) { return typedIntArrayArbitraryArbitraryBuilder( constraints, 0, 255, SUint8ClampedArray, integer, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/WithShrinkFromOtherArbitrary.js function isSafeContext(context2) { return context2 !== void 0; } function toGeneratorValue(value) { if (value.hasToBeCloned) { return new Value( value.value_, { generatorContext: value.context }, () => value.value, ); } return new Value(value.value_, { generatorContext: value.context }); } function toShrinkerValue(value) { if (value.hasToBeCloned) { return new Value( value.value_, { shrinkerContext: value.context }, () => value.value, ); } return new Value(value.value_, { shrinkerContext: value.context }); } var WithShrinkFromOtherArbitrary = class extends Arbitrary { constructor(generatorArbitrary, shrinkerArbitrary) { super(); this.generatorArbitrary = generatorArbitrary; this.shrinkerArbitrary = shrinkerArbitrary; } generate(mrng, biasFactor) { return toGeneratorValue(this.generatorArbitrary.generate(mrng, biasFactor)); } canShrinkWithoutContext(value) { return this.shrinkerArbitrary.canShrinkWithoutContext(value); } shrink(value, context2) { if (!isSafeContext(context2)) { return this.shrinkerArbitrary.shrink(value, void 0).map(toShrinkerValue); } if ('generatorContext' in context2) { return this.generatorArbitrary .shrink(value, context2.generatorContext) .map(toGeneratorValue); } return this.shrinkerArbitrary .shrink(value, context2.shrinkerContext) .map(toShrinkerValue); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/RestrictedIntegerArbitraryBuilder.js function restrictedIntegerArbitraryBuilder(min, maxGenerated, max) { const generatorArbitrary = integer({ min, max: maxGenerated }); if (maxGenerated === max) { return generatorArbitrary; } const shrinkerArbitrary = integer({ min, max }); return new WithShrinkFromOtherArbitrary( generatorArbitrary, shrinkerArbitrary, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/sparseArray.js var safeMathMin5 = Math.min; var safeMathMax3 = Math.max; var safeArrayIsArray3 = SArray.isArray; var safeObjectEntries2 = Object.entries; function extractMaxIndex(indexesAndValues) { let maxIndex = -1; for (let index = 0; index !== indexesAndValues.length; ++index) { maxIndex = safeMathMax3(maxIndex, indexesAndValues[index][0]); } return maxIndex; } function arrayFromItems(length, indexesAndValues) { const array2 = SArray(length); for (let index = 0; index !== indexesAndValues.length; ++index) { const it = indexesAndValues[index]; if (it[0] < length) array2[it[0]] = it[1]; } return array2; } function sparseArray(arb, constraints = {}) { const { size, minNumElements = 0, maxLength = MaxLengthUpperBound, maxNumElements = maxLength, noTrailingHole, depthIdentifier, } = constraints; const maxGeneratedNumElements = maxGeneratedLengthFromSizeForArbitrary( size, minNumElements, maxNumElements, constraints.maxNumElements !== void 0, ); const maxGeneratedLength = maxGeneratedLengthFromSizeForArbitrary( size, maxGeneratedNumElements, maxLength, constraints.maxLength !== void 0, ); if (minNumElements > maxLength) { throw new Error( `The minimal number of non-hole elements cannot be higher than the maximal length of the array`, ); } if (minNumElements > maxNumElements) { throw new Error( `The minimal number of non-hole elements cannot be higher than the maximal number of non-holes`, ); } const resultedMaxNumElements = safeMathMin5(maxNumElements, maxLength); const resultedSizeMaxNumElements = constraints.maxNumElements !== void 0 || size !== void 0 ? size : '='; const maxGeneratedIndexAuthorized = safeMathMax3(maxGeneratedLength - 1, 0); const maxIndexAuthorized = safeMathMax3(maxLength - 1, 0); const sparseArrayNoTrailingHole = uniqueArray( tuple( restrictedIntegerArbitraryBuilder( 0, maxGeneratedIndexAuthorized, maxIndexAuthorized, ), arb, ), { size: resultedSizeMaxNumElements, minLength: minNumElements, maxLength: resultedMaxNumElements, selector: (item) => item[0], depthIdentifier, }, ).map( (items) => { const lastIndex = extractMaxIndex(items); return arrayFromItems(lastIndex + 1, items); }, (value) => { if (!safeArrayIsArray3(value)) { throw new Error('Not supported entry type'); } if ( noTrailingHole && value.length !== 0 && !(value.length - 1 in value) ) { throw new Error('No trailing hole'); } return safeMap(safeObjectEntries2(value), (entry) => [ Number(entry[0]), entry[1], ]); }, ); if (noTrailingHole || maxLength === minNumElements) { return sparseArrayNoTrailingHole; } return tuple( sparseArrayNoTrailingHole, restrictedIntegerArbitraryBuilder( minNumElements, maxGeneratedLength, maxLength, ), ).map( (data) => { const sparse = data[0]; const targetLength = data[1]; if (sparse.length >= targetLength) { return sparse; } const longerSparse = safeSlice(sparse); longerSparse.length = targetLength; return longerSparse; }, (value) => { if (!safeArrayIsArray3(value)) { throw new Error('Not supported entry type'); } return [value, value.length]; }, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/ArrayToMap.js function arrayToMapMapper(data) { return new Map(data); } function arrayToMapUnmapper(value) { if (typeof value !== 'object' || value === null) { throw new Error( 'Incompatible instance received: should be a non-null object', ); } if (!('constructor' in value) || value.constructor !== Map) { throw new Error( 'Incompatible instance received: should be of exact type Map', ); } return Array.from(value); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/ArrayToSet.js function arrayToSetMapper(data) { return new Set(data); } function arrayToSetUnmapper(value) { if (typeof value !== 'object' || value === null) { throw new Error( 'Incompatible instance received: should be a non-null object', ); } if (!('constructor' in value) || value.constructor !== Set) { throw new Error( 'Incompatible instance received: should be of exact type Set', ); } return Array.from(value); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/AnyArbitraryBuilder.js function mapOf(ka, va, maxKeys, size, depthIdentifier) { return uniqueArray(tuple(ka, va), { maxLength: maxKeys, size, comparator: 'SameValueZero', selector: (t) => t[0], depthIdentifier, }).map(arrayToMapMapper, arrayToMapUnmapper); } function dictOf(ka, va, maxKeys, size, depthIdentifier, withNullPrototype) { return dictionary(ka, va, { maxKeys, noNullPrototype: !withNullPrototype, size, depthIdentifier, }); } function setOf(va, maxKeys, size, depthIdentifier) { return uniqueArray(va, { maxLength: maxKeys, size, comparator: 'SameValueZero', depthIdentifier, }).map(arrayToSetMapper, arrayToSetUnmapper); } function typedArray(constraints) { return oneof( int8Array(constraints), uint8Array(constraints), uint8ClampedArray(constraints), int16Array(constraints), uint16Array(constraints), int32Array(constraints), uint32Array(constraints), float32Array(constraints), float64Array(constraints), ); } function anyArbitraryBuilder(constraints) { const arbitrariesForBase = constraints.values; const depthSize = constraints.depthSize; const depthIdentifier = createDepthIdentifier(); const maxDepth = constraints.maxDepth; const maxKeys = constraints.maxKeys; const size = constraints.size; const baseArb = oneof( ...arbitrariesForBase, ...(constraints.withBigInt ? [bigInt()] : []), ...(constraints.withDate ? [date()] : []), ); return letrec((tie) => ({ anything: oneof( { maxDepth, depthSize, depthIdentifier }, baseArb, tie('array'), tie('object'), ...(constraints.withMap ? [tie('map')] : []), ...(constraints.withSet ? [tie('set')] : []), ...(constraints.withObjectString ? [tie('anything').map((o) => stringify(o))] : []), ...(constraints.withTypedArray ? [typedArray({ maxLength: maxKeys, size })] : []), ...(constraints.withSparseArray ? [ sparseArray(tie('anything'), { maxNumElements: maxKeys, size, depthIdentifier, }), ] : []), ), keys: constraints.withObjectString ? oneof( { arbitrary: constraints.key, weight: 10 }, { arbitrary: tie('anything').map((o) => stringify(o)), weight: 1 }, ) : constraints.key, array: array(tie('anything'), { maxLength: maxKeys, size, depthIdentifier, }), set: setOf(tie('anything'), maxKeys, size, depthIdentifier), map: oneof( mapOf(tie('keys'), tie('anything'), maxKeys, size, depthIdentifier), mapOf(tie('anything'), tie('anything'), maxKeys, size, depthIdentifier), ), object: dictOf( tie('keys'), tie('anything'), maxKeys, size, depthIdentifier, constraints.withNullPrototype, ), })).anything; } // ../../../node_modules/fast-check/lib/esm/arbitrary/string.js var safeObjectAssign9 = Object.assign; function string(constraints = {}) { const charArbitrary = char(); const experimentalCustomSlices = createSlicesForString( charArbitrary, codePointsToStringUnmapper, ); const enrichedConstraints = safeObjectAssign9( safeObjectAssign9({}, constraints), { experimentalCustomSlices, }, ); return array(charArbitrary, enrichedConstraints).map( codePointsToStringMapper, codePointsToStringUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/UnboxedToBoxed.js function unboxedToBoxedMapper(value) { switch (typeof value) { case 'boolean': return new SBoolean(value); case 'number': return new SNumber(value); case 'string': return new SString(value); default: return value; } } function unboxedToBoxedUnmapper(value) { if ( typeof value !== 'object' || value === null || !('constructor' in value) ) { return value; } return value.constructor === SBoolean || value.constructor === SNumber || value.constructor === SString ? value.valueOf() : value; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/BoxedArbitraryBuilder.js function boxedArbitraryBuilder(arb) { return arb.map(unboxedToBoxedMapper, unboxedToBoxedUnmapper); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/QualifiedObjectConstraints.js function defaultValues(constraints) { return [ boolean(), maxSafeInteger(), double(), string(constraints), oneof(string(constraints), constant(null), constant(void 0)), ]; } function boxArbitraries(arbs) { return arbs.map((arb) => boxedArbitraryBuilder(arb)); } function boxArbitrariesIfNeeded(arbs, boxEnabled) { return boxEnabled ? boxArbitraries(arbs).concat(arbs) : arbs; } function toQualifiedObjectConstraints(settings = {}) { function orDefault(optionalValue, defaultValue) { return optionalValue !== void 0 ? optionalValue : defaultValue; } const valueConstraints = { size: settings.size }; return { key: orDefault(settings.key, string(valueConstraints)), values: boxArbitrariesIfNeeded( orDefault(settings.values, defaultValues(valueConstraints)), orDefault(settings.withBoxedValues, false), ), depthSize: settings.depthSize, maxDepth: settings.maxDepth, maxKeys: settings.maxKeys, size: settings.size, withSet: orDefault(settings.withSet, false), withMap: orDefault(settings.withMap, false), withObjectString: orDefault(settings.withObjectString, false), withNullPrototype: orDefault(settings.withNullPrototype, false), withBigInt: orDefault(settings.withBigInt, false), withDate: orDefault(settings.withDate, false), withTypedArray: orDefault(settings.withTypedArray, false), withSparseArray: orDefault(settings.withSparseArray, false), }; } // ../../../node_modules/fast-check/lib/esm/arbitrary/object.js function objectInternal(constraints) { return dictionary(constraints.key, anyArbitraryBuilder(constraints), { maxKeys: constraints.maxKeys, noNullPrototype: !constraints.withNullPrototype, size: constraints.size, }); } function object(constraints) { return objectInternal(toQualifiedObjectConstraints(constraints)); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/JsonConstraintsBuilder.js function jsonConstraintsBuilder(stringArbitrary, constraints) { const { depthSize, maxDepth } = constraints; const key = stringArbitrary; const values = [ boolean(), double({ noDefaultInfinity: true, noNaN: true }), stringArbitrary, constant(null), ]; return { key, values, depthSize, maxDepth }; } // ../../../node_modules/fast-check/lib/esm/arbitrary/anything.js function anything(constraints) { return anyArbitraryBuilder(toQualifiedObjectConstraints(constraints)); } // ../../../node_modules/fast-check/lib/esm/arbitrary/jsonValue.js function jsonValue(constraints = {}) { return anything(jsonConstraintsBuilder(string(), constraints)); } // ../../../node_modules/fast-check/lib/esm/arbitrary/json.js function json(constraints = {}) { const arb = jsonValue(constraints); return arb.map(JSON.stringify); } // ../../../node_modules/fast-check/lib/esm/arbitrary/unicodeString.js var safeObjectAssign10 = Object.assign; function unicodeString(constraints = {}) { const charArbitrary = unicode(); const experimentalCustomSlices = createSlicesForString( charArbitrary, codePointsToStringUnmapper, ); const enrichedConstraints = safeObjectAssign10( safeObjectAssign10({}, constraints), { experimentalCustomSlices, }, ); return array(charArbitrary, enrichedConstraints).map( codePointsToStringMapper, codePointsToStringUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/unicodeJsonValue.js function unicodeJsonValue(constraints = {}) { return anything(jsonConstraintsBuilder(unicodeString(), constraints)); } // ../../../node_modules/fast-check/lib/esm/arbitrary/unicodeJson.js function unicodeJson(constraints = {}) { const arb = unicodeJsonValue(constraints); return arb.map(JSON.stringify); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/EnumerableKeysExtractor.js var safeObjectKeys4 = Object.keys; var safeObjectGetOwnPropertySymbols3 = Object.getOwnPropertySymbols; var safeObjectGetOwnPropertyDescriptor3 = Object.getOwnPropertyDescriptor; function extractEnumerableKeys(instance) { const keys = safeObjectKeys4(instance); const symbols = safeObjectGetOwnPropertySymbols3(instance); for (let index = 0; index !== symbols.length; ++index) { const symbol = symbols[index]; const descriptor = safeObjectGetOwnPropertyDescriptor3(instance, symbol); if (descriptor && descriptor.enumerable) { keys.push(symbol); } } return keys; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/ValuesAndSeparateKeysToObject.js var safeObjectCreate3 = Object.create; var safeObjectDefineProperty4 = Object.defineProperty; var safeObjectGetOwnPropertyDescriptor4 = Object.getOwnPropertyDescriptor; var safeObjectGetOwnPropertyNames2 = Object.getOwnPropertyNames; var safeObjectGetOwnPropertySymbols4 = Object.getOwnPropertySymbols; function buildValuesAndSeparateKeysToObjectMapper(keys, noKeyValue2) { return function valuesAndSeparateKeysToObjectMapper(definition) { const obj = definition[1] ? safeObjectCreate3(null) : {}; for (let idx = 0; idx !== keys.length; ++idx) { const valueWrapper = definition[0][idx]; if (valueWrapper !== noKeyValue2) { safeObjectDefineProperty4(obj, keys[idx], { value: valueWrapper, configurable: true, enumerable: true, writable: true, }); } } return obj; }; } function buildValuesAndSeparateKeysToObjectUnmapper(keys, noKeyValue2) { return function valuesAndSeparateKeysToObjectUnmapper(value) { if (typeof value !== 'object' || value === null) { throw new Error( 'Incompatible instance received: should be a non-null object', ); } const hasNullPrototype = Object.getPrototypeOf(value) === null; const hasObjectPrototype = 'constructor' in value && value.constructor === Object; if (!hasNullPrototype && !hasObjectPrototype) { throw new Error( 'Incompatible instance received: should be of exact type Object', ); } let extractedPropertiesCount = 0; const extractedValues = []; for (let idx = 0; idx !== keys.length; ++idx) { const descriptor = safeObjectGetOwnPropertyDescriptor4(value, keys[idx]); if (descriptor !== void 0) { if ( !descriptor.configurable || !descriptor.enumerable || !descriptor.writable ) { throw new Error( 'Incompatible instance received: should contain only c/e/w properties', ); } if (descriptor.get !== void 0 || descriptor.set !== void 0) { throw new Error( 'Incompatible instance received: should contain only no get/set properties', ); } ++extractedPropertiesCount; safePush(extractedValues, descriptor.value); } else { safePush(extractedValues, noKeyValue2); } } const namePropertiesCount = safeObjectGetOwnPropertyNames2(value).length; const symbolPropertiesCount = safeObjectGetOwnPropertySymbols4(value).length; if ( extractedPropertiesCount !== namePropertiesCount + symbolPropertiesCount ) { throw new Error( 'Incompatible instance received: should not contain extra properties', ); } return [extractedValues, hasNullPrototype]; }; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/PartialRecordArbitraryBuilder.js var noKeyValue = Symbol('no-key'); function buildPartialRecordArbitrary( recordModel, requiredKeys, noNullPrototype, ) { const keys = extractEnumerableKeys(recordModel); const arbs = []; for (let index = 0; index !== keys.length; ++index) { const k = keys[index]; const requiredArbitrary = recordModel[k]; if (requiredKeys === void 0 || safeIndexOf(requiredKeys, k) !== -1) { safePush(arbs, requiredArbitrary); } else { safePush(arbs, option(requiredArbitrary, { nil: noKeyValue })); } } return tuple( tuple(...arbs), noNullPrototype ? constant(false) : boolean(), ).map( buildValuesAndSeparateKeysToObjectMapper(keys, noKeyValue), buildValuesAndSeparateKeysToObjectUnmapper(keys, noKeyValue), ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/record.js function record(recordModel, constraints) { const noNullPrototype = constraints === void 0 || constraints.noNullPrototype === void 0 || constraints.noNullPrototype; if (constraints == null) { return buildPartialRecordArbitrary(recordModel, void 0, noNullPrototype); } if ('withDeletedKeys' in constraints && 'requiredKeys' in constraints) { throw new Error( `requiredKeys and withDeletedKeys cannot be used together in fc.record`, ); } const requireDeletedKeys = ('requiredKeys' in constraints && constraints.requiredKeys !== void 0) || ('withDeletedKeys' in constraints && !!constraints.withDeletedKeys); if (!requireDeletedKeys) { return buildPartialRecordArbitrary(recordModel, void 0, noNullPrototype); } const requiredKeys = ('requiredKeys' in constraints ? constraints.requiredKeys : void 0) || []; for (let idx = 0; idx !== requiredKeys.length; ++idx) { const descriptor = Object.getOwnPropertyDescriptor( recordModel, requiredKeys[idx], ); if (descriptor === void 0) { throw new Error( `requiredKeys cannot reference keys that have not been defined in recordModel`, ); } if (!descriptor.enumerable) { throw new Error( `requiredKeys cannot reference keys that have are enumerable in recordModel`, ); } } return buildPartialRecordArbitrary( recordModel, requiredKeys, noNullPrototype, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/StreamArbitrary.js var safeObjectDefineProperties2 = Object.defineProperties; function prettyPrint(seenValuesStrings) { return `Stream(${safeJoin(seenValuesStrings, ',')}\u2026)`; } var StreamArbitrary = class extends Arbitrary { constructor(arb) { super(); this.arb = arb; } generate(mrng, biasFactor) { const appliedBiasFactor = biasFactor !== void 0 && mrng.nextInt(1, biasFactor) === 1 ? biasFactor : void 0; const enrichedProducer = () => { const seenValues = []; const g = function* (arb, clonedMrng) { while (true) { const value = arb.generate(clonedMrng, appliedBiasFactor).value; safePush(seenValues, value); yield value; } }; const s = new Stream(g(this.arb, mrng.clone())); return safeObjectDefineProperties2(s, { toString: { value: () => prettyPrint(seenValues.map(stringify)) }, [toStringMethod]: { value: () => prettyPrint(seenValues.map(stringify)), }, [asyncToStringMethod]: { value: async () => prettyPrint(await Promise.all(seenValues.map(asyncStringify))), }, [cloneMethod]: { value: enrichedProducer, enumerable: true }, }); }; return new Value(enrichedProducer(), void 0); } canShrinkWithoutContext(value) { return false; } shrink(_value, _context) { return Stream.nil(); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/infiniteStream.js function infiniteStream(arb) { return new StreamArbitrary(arb); } // ../../../node_modules/fast-check/lib/esm/arbitrary/asciiString.js var safeObjectAssign11 = Object.assign; function asciiString(constraints = {}) { const charArbitrary = ascii(); const experimentalCustomSlices = createSlicesForString( charArbitrary, codePointsToStringUnmapper, ); const enrichedConstraints = safeObjectAssign11( safeObjectAssign11({}, constraints), { experimentalCustomSlices, }, ); return array(charArbitrary, enrichedConstraints).map( codePointsToStringMapper, codePointsToStringUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/StringToBase64.js function stringToBase64Mapper(s) { switch (s.length % 4) { case 0: return s; case 3: return `${s}=`; case 2: return `${s}==`; default: return safeSubstring(s, 1); } } function stringToBase64Unmapper(value) { if (typeof value !== 'string' || value.length % 4 !== 0) { throw new Error('Invalid string received'); } const lastTrailingIndex = value.indexOf('='); if (lastTrailingIndex === -1) { return value; } const numTrailings = value.length - lastTrailingIndex; if (numTrailings > 2) { throw new Error('Cannot unmap the passed value'); } return safeSubstring(value, 0, lastTrailingIndex); } // ../../../node_modules/fast-check/lib/esm/arbitrary/base64String.js function base64String(constraints = {}) { const { minLength: unscaledMinLength = 0, maxLength: unscaledMaxLength = MaxLengthUpperBound, size, } = constraints; const minLength = unscaledMinLength + 3 - ((unscaledMinLength + 3) % 4); const maxLength = unscaledMaxLength - (unscaledMaxLength % 4); const requestedSize = constraints.maxLength === void 0 && size === void 0 ? '=' : size; if (minLength > maxLength) throw new Error( 'Minimal length should be inferior or equal to maximal length', ); if (minLength % 4 !== 0) throw new Error('Minimal length of base64 strings must be a multiple of 4'); if (maxLength % 4 !== 0) throw new Error('Maximal length of base64 strings must be a multiple of 4'); const charArbitrary = base64(); const experimentalCustomSlices = createSlicesForString( charArbitrary, codePointsToStringUnmapper, ); const enrichedConstraints = { minLength, maxLength, size: requestedSize, experimentalCustomSlices, }; return array(charArbitrary, enrichedConstraints) .map(codePointsToStringMapper, codePointsToStringUnmapper) .map(stringToBase64Mapper, stringToBase64Unmapper); } // ../../../node_modules/fast-check/lib/esm/arbitrary/fullUnicodeString.js var safeObjectAssign12 = Object.assign; function fullUnicodeString(constraints = {}) { const charArbitrary = fullUnicode(); const experimentalCustomSlices = createSlicesForString( charArbitrary, codePointsToStringUnmapper, ); const enrichedConstraints = safeObjectAssign12( safeObjectAssign12({}, constraints), { experimentalCustomSlices, }, ); return array(charArbitrary, enrichedConstraints).map( codePointsToStringMapper, codePointsToStringUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/CharsToString.js function charsToStringMapper(tab) { return safeJoin(tab, ''); } function charsToStringUnmapper(value) { if (typeof value !== 'string') { throw new Error('Cannot unmap the passed value'); } return safeSplit(value, ''); } // ../../../node_modules/fast-check/lib/esm/arbitrary/string16bits.js var safeObjectAssign13 = Object.assign; function string16bits(constraints = {}) { const charArbitrary = char16bits(); const experimentalCustomSlices = createSlicesForString( charArbitrary, charsToStringUnmapper, ); const enrichedConstraints = safeObjectAssign13( safeObjectAssign13({}, constraints), { experimentalCustomSlices, }, ); return array(charArbitrary, enrichedConstraints).map( charsToStringMapper, charsToStringUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/IsSubarrayOf.js function isSubarrayOf(source, small) { const countMap = /* @__PURE__ */ new Map(); let countMinusZero = 0; for (const sourceEntry of source) { if (Object.is(sourceEntry, -0)) { ++countMinusZero; } else { const oldCount = countMap.get(sourceEntry) || 0; countMap.set(sourceEntry, oldCount + 1); } } for (let index = 0; index !== small.length; ++index) { if (!(index in small)) { return false; } const smallEntry = small[index]; if (Object.is(smallEntry, -0)) { if (countMinusZero === 0) return false; --countMinusZero; } else { const oldCount = countMap.get(smallEntry) || 0; if (oldCount === 0) return false; countMap.set(smallEntry, oldCount - 1); } } return true; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/SubarrayArbitrary.js var safeMathFloor6 = Math.floor; var safeMathLog4 = Math.log; var safeArrayIsArray4 = Array.isArray; var SubarrayArbitrary = class extends Arbitrary { constructor(originalArray, isOrdered, minLength, maxLength) { super(); this.originalArray = originalArray; this.isOrdered = isOrdered; this.minLength = minLength; this.maxLength = maxLength; if (minLength < 0 || minLength > originalArray.length) throw new Error( 'fc.*{s|S}ubarrayOf expects the minimal length to be between 0 and the size of the original array', ); if (maxLength < 0 || maxLength > originalArray.length) throw new Error( 'fc.*{s|S}ubarrayOf expects the maximal length to be between 0 and the size of the original array', ); if (minLength > maxLength) throw new Error( 'fc.*{s|S}ubarrayOf expects the minimal length to be inferior or equal to the maximal length', ); this.lengthArb = new IntegerArbitrary(minLength, maxLength); this.biasedLengthArb = minLength !== maxLength ? new IntegerArbitrary( minLength, minLength + safeMathFloor6( safeMathLog4(maxLength - minLength) / safeMathLog4(2), ), ) : this.lengthArb; } generate(mrng, biasFactor) { const lengthArb = biasFactor !== void 0 && mrng.nextInt(1, biasFactor) === 1 ? this.biasedLengthArb : this.lengthArb; const size = lengthArb.generate(mrng, void 0); const sizeValue = size.value; const remainingElements = safeMap(this.originalArray, (_v, idx) => idx); const ids = []; for (let index = 0; index !== sizeValue; ++index) { const selectedIdIndex = mrng.nextInt(0, remainingElements.length - 1); safePush(ids, remainingElements[selectedIdIndex]); safeSplice(remainingElements, selectedIdIndex, 1); } if (this.isOrdered) { safeSort(ids, (a, b) => a - b); } return new Value( safeMap(ids, (i) => this.originalArray[i]), size.context, ); } canShrinkWithoutContext(value) { if (!safeArrayIsArray4(value)) { return false; } if (!this.lengthArb.canShrinkWithoutContext(value.length)) { return false; } return isSubarrayOf(this.originalArray, value); } shrink(value, context2) { if (value.length === 0) { return Stream.nil(); } return this.lengthArb .shrink(value.length, context2) .map((newSize) => { return new Value( safeSlice(value, value.length - newSize.value), newSize.context, ); }) .join( value.length > this.minLength ? makeLazy(() => this.shrink(safeSlice(value, 1), void 0) .filter( (newValue) => this.minLength <= newValue.value.length + 1, ) .map( (newValue) => new Value([value[0], ...newValue.value], void 0), ), ) : Stream.nil(), ); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/subarray.js function subarray(originalArray, constraints = {}) { const { minLength = 0, maxLength = originalArray.length } = constraints; return new SubarrayArbitrary(originalArray, true, minLength, maxLength); } // ../../../node_modules/fast-check/lib/esm/arbitrary/shuffledSubarray.js function shuffledSubarray(originalArray, constraints = {}) { const { minLength = 0, maxLength = originalArray.length } = constraints; return new SubarrayArbitrary(originalArray, false, minLength, maxLength); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/UintToBase32String.js var encodeSymbolLookupTable = { 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F', 16: 'G', 17: 'H', 18: 'J', 19: 'K', 20: 'M', 21: 'N', 22: 'P', 23: 'Q', 24: 'R', 25: 'S', 26: 'T', 27: 'V', 28: 'W', 29: 'X', 30: 'Y', 31: 'Z', }; var decodeSymbolLookupTable = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, G: 16, H: 17, J: 18, K: 19, M: 20, N: 21, P: 22, Q: 23, R: 24, S: 25, T: 26, V: 27, W: 28, X: 29, Y: 30, Z: 31, }; function encodeSymbol(symbol) { return symbol < 10 ? SString(symbol) : encodeSymbolLookupTable[symbol]; } function pad(value, paddingLength) { let extraPadding = ''; while (value.length + extraPadding.length < paddingLength) { extraPadding += '0'; } return extraPadding + value; } function smallUintToBase32StringMapper(num) { let base32Str = ''; for (let remaining = num; remaining !== 0; ) { const next = remaining >> 5; const current = remaining - (next << 5); base32Str = encodeSymbol(current) + base32Str; remaining = next; } return base32Str; } function uintToBase32StringMapper(num, paddingLength) { const head = ~~(num / 1073741824); const tail = num & 1073741823; return ( pad(smallUintToBase32StringMapper(head), paddingLength - 6) + pad(smallUintToBase32StringMapper(tail), 6) ); } function paddedUintToBase32StringMapper(paddingLength) { return function padded(num) { return uintToBase32StringMapper(num, paddingLength); }; } function uintToBase32StringUnmapper(value) { if (typeof value !== 'string') { throw new SError('Unsupported type'); } let accumulated = 0; let power = 1; for (let index = value.length - 1; index >= 0; --index) { const char2 = value[index]; const numericForChar = decodeSymbolLookupTable[char2]; if (numericForChar === void 0) { throw new SError('Unsupported type'); } accumulated += numericForChar * power; power *= 32; } return accumulated; } // ../../../node_modules/fast-check/lib/esm/arbitrary/ulid.js var padded10Mapper = paddedUintToBase32StringMapper(10); var padded8Mapper = paddedUintToBase32StringMapper(8); function ulidMapper(parts) { return ( padded10Mapper(parts[0]) + padded8Mapper(parts[1]) + padded8Mapper(parts[2]) ); } function ulidUnmapper(value) { if (typeof value !== 'string' || value.length !== 26) { throw new Error('Unsupported type'); } return [ uintToBase32StringUnmapper(value.slice(0, 10)), uintToBase32StringUnmapper(value.slice(10, 18)), uintToBase32StringUnmapper(value.slice(18)), ]; } function ulid() { const timestampPartArbitrary = integer({ min: 0, max: 281474976710655 }); const randomnessPartOneArbitrary = integer({ min: 0, max: 1099511627775 }); const randomnessPartTwoArbitrary = integer({ min: 0, max: 1099511627775 }); return tuple( timestampPartArbitrary, randomnessPartOneArbitrary, randomnessPartTwoArbitrary, ).map(ulidMapper, ulidUnmapper); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/NumberToPaddedEight.js function numberToPaddedEightMapper(n) { return safePadStart(safeNumberToString(n, 16), 8, '0'); } function numberToPaddedEightUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported type'); } if (value.length !== 8) { throw new Error('Unsupported value: invalid length'); } const n = parseInt(value, 16); if (value !== numberToPaddedEightMapper(n)) { throw new Error('Unsupported value: invalid content'); } return n; } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/PaddedNumberArbitraryBuilder.js function buildPaddedNumberArbitrary(min, max) { return integer({ min, max }).map( numberToPaddedEightMapper, numberToPaddedEightUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/PaddedEightsToUuid.js function paddedEightsToUuidMapper(t) { return `${t[0]}-${safeSubstring(t[1], 4)}-${safeSubstring(t[1], 0, 4)}-${safeSubstring(t[2], 0, 4)}-${safeSubstring(t[2], 4)}${t[3]}`; } var UuidRegex = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/; function paddedEightsToUuidUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported type'); } const m = UuidRegex.exec(value); if (m === null) { throw new Error('Unsupported type'); } return [ m[1], m[3] + m[2], m[4] + safeSubstring(m[5], 0, 4), safeSubstring(m[5], 4), ]; } // ../../../node_modules/fast-check/lib/esm/arbitrary/uuid.js function uuid() { const padded = buildPaddedNumberArbitrary(0, 4294967295); const secondPadded = buildPaddedNumberArbitrary(268435456, 1610612735); const thirdPadded = buildPaddedNumberArbitrary(2147483648, 3221225471); return tuple(padded, secondPadded, thirdPadded, padded).map( paddedEightsToUuidMapper, paddedEightsToUuidUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/uuidV.js function uuidV(versionNumber) { const padded = buildPaddedNumberArbitrary(0, 4294967295); const offsetSecond = versionNumber * 268435456; const secondPadded = buildPaddedNumberArbitrary( offsetSecond, offsetSecond + 268435455, ); const thirdPadded = buildPaddedNumberArbitrary(2147483648, 3221225471); return tuple(padded, secondPadded, thirdPadded, padded).map( paddedEightsToUuidMapper, paddedEightsToUuidUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/webAuthority.js function hostUserInfo(size) { const others = [ '-', '.', '_', '~', '!', '$', '&', "'", '(', ')', '*', '+', ',', ';', '=', ':', ]; return stringOf(buildAlphaNumericPercentArbitrary(others), { size }); } function userHostPortMapper([u, h2, p]) { return (u === null ? '' : `${u}@`) + h2 + (p === null ? '' : `:${p}`); } function userHostPortUnmapper(value) { if (typeof value !== 'string') { throw new Error('Unsupported'); } const atPosition = value.indexOf('@'); const user = atPosition !== -1 ? value.substring(0, atPosition) : null; const portRegex = /:(\d+)$/; const m = portRegex.exec(value); const port = m !== null ? Number(m[1]) : null; const host = m !== null ? value.substring(atPosition + 1, value.length - m[1].length - 1) : value.substring(atPosition + 1); return [user, host, port]; } function bracketedMapper(s) { return `[${s}]`; } function bracketedUnmapper(value) { if ( typeof value !== 'string' || value[0] !== '[' || value[value.length - 1] !== ']' ) { throw new Error('Unsupported'); } return value.substring(1, value.length - 1); } function webAuthority(constraints) { const c = constraints || {}; const size = c.size; const hostnameArbs = [ domain({ size }), ...(c.withIPv4 === true ? [ipV4()] : []), ...(c.withIPv6 === true ? [ipV6().map(bracketedMapper, bracketedUnmapper)] : []), ...(c.withIPv4Extended === true ? [ipV4Extended()] : []), ]; return tuple( c.withUserInfo === true ? option(hostUserInfo(size)) : constant(null), oneof(...hostnameArbs), c.withPort === true ? option(nat(65535)) : constant(null), ).map(userHostPortMapper, userHostPortUnmapper); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/UriQueryOrFragmentArbitraryBuilder.js function buildUriQueryOrFragmentArbitrary(size) { const others = [ '-', '.', '_', '~', '!', '$', '&', "'", '(', ')', '*', '+', ',', ';', '=', ':', '@', '/', '?', ]; return stringOf(buildAlphaNumericPercentArbitrary(others), { size }); } // ../../../node_modules/fast-check/lib/esm/arbitrary/webFragments.js function webFragments(constraints = {}) { return buildUriQueryOrFragmentArbitrary(constraints.size); } // ../../../node_modules/fast-check/lib/esm/arbitrary/webSegment.js function webSegment(constraints = {}) { const others = [ '-', '.', '_', '~', '!', '$', '&', "'", '(', ')', '*', '+', ',', ';', '=', ':', '@', ]; return stringOf(buildAlphaNumericPercentArbitrary(others), { size: constraints.size, }); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/SegmentsToPath.js function segmentsToPathMapper(segments) { return safeJoin( safeMap(segments, (v) => `/${v}`), '', ); } function segmentsToPathUnmapper(value) { if (typeof value !== 'string') { throw new Error('Incompatible value received: type'); } if (value.length !== 0 && value[0] !== '/') { throw new Error('Incompatible value received: start'); } return safeSplice(safeSplit(value, '/'), 1); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/builders/UriPathArbitraryBuilder.js function sqrtSize(size) { switch (size) { case 'xsmall': return ['xsmall', 'xsmall']; case 'small': return ['small', 'xsmall']; case 'medium': return ['small', 'small']; case 'large': return ['medium', 'small']; case 'xlarge': return ['medium', 'medium']; } } function buildUriPathArbitrary(resolvedSize) { const [segmentSize, numSegmentSize] = sqrtSize(resolvedSize); return array(webSegment({ size: segmentSize }), { size: numSegmentSize }).map( segmentsToPathMapper, segmentsToPathUnmapper, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/webPath.js function webPath(constraints) { const c = constraints || {}; const resolvedSize = resolveSize(c.size); return buildUriPathArbitrary(resolvedSize); } // ../../../node_modules/fast-check/lib/esm/arbitrary/webQueryParameters.js function webQueryParameters(constraints = {}) { return buildUriQueryOrFragmentArbitrary(constraints.size); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/mappers/PartsToUrl.js function partsToUrlMapper(data) { const [scheme, authority, path] = data; const query = data[3] === null ? '' : `?${data[3]}`; const fragments = data[4] === null ? '' : `#${data[4]}`; return `${scheme}://${authority}${path}${query}${fragments}`; } var UrlSplitRegex = /^([[A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(\?[A-Za-z0-9\-._~!$&'()*+,;=:@/?%]*)?(#[A-Za-z0-9\-._~!$&'()*+,;=:@/?%]*)?$/; function partsToUrlUnmapper(value) { if (typeof value !== 'string') { throw new Error('Incompatible value received: type'); } const m = UrlSplitRegex.exec(value); if (m === null) { throw new Error('Incompatible value received'); } const scheme = m[1]; const authority = m[2]; const path = m[3]; const query = m[4]; const fragments = m[5]; return [ scheme, authority, path, query !== void 0 ? query.substring(1) : null, fragments !== void 0 ? fragments.substring(1) : null, ]; } // ../../../node_modules/fast-check/lib/esm/arbitrary/webUrl.js var safeObjectAssign14 = Object.assign; function webUrl(constraints) { const c = constraints || {}; const resolvedSize = resolveSize(c.size); const resolvedAuthoritySettingsSize = c.authoritySettings !== void 0 && c.authoritySettings.size !== void 0 ? relativeSizeToSize(c.authoritySettings.size, resolvedSize) : resolvedSize; const resolvedAuthoritySettings = safeObjectAssign14( safeObjectAssign14({}, c.authoritySettings), { size: resolvedAuthoritySettingsSize, }, ); const validSchemes = c.validSchemes || ['http', 'https']; const schemeArb = constantFrom(...validSchemes); const authorityArb = webAuthority(resolvedAuthoritySettings); return tuple( schemeArb, authorityArb, webPath({ size: resolvedSize }), c.withQueryParameters === true ? option(webQueryParameters({ size: resolvedSize })) : constant(null), c.withFragments === true ? option(webFragments({ size: resolvedSize })) : constant(null), ).map(partsToUrlMapper, partsToUrlUnmapper); } // ../../../node_modules/fast-check/lib/esm/check/model/commands/CommandsIterable.js var CommandsIterable = class _CommandsIterable { constructor(commands2, metadataForReplay) { this.commands = commands2; this.metadataForReplay = metadataForReplay; } [Symbol.iterator]() { return this.commands[Symbol.iterator](); } [cloneMethod]() { return new _CommandsIterable( this.commands.map((c) => c.clone()), this.metadataForReplay, ); } toString() { const serializedCommands = this.commands .filter((c) => c.hasRan) .map((c) => c.toString()) .join(','); const metadata = this.metadataForReplay(); return metadata.length !== 0 ? `${serializedCommands} /*${metadata}*/` : serializedCommands; } }; // ../../../node_modules/fast-check/lib/esm/check/model/commands/CommandWrapper.js var CommandWrapper = class _CommandWrapper { constructor(cmd) { this.cmd = cmd; this.hasRan = false; if (hasToStringMethod(cmd)) { const method = cmd[toStringMethod]; this[toStringMethod] = function toStringMethod2() { return method.call(cmd); }; } if (hasAsyncToStringMethod(cmd)) { const method = cmd[asyncToStringMethod]; this[asyncToStringMethod] = function asyncToStringMethod2() { return method.call(cmd); }; } } check(m) { return this.cmd.check(m); } run(m, r) { this.hasRan = true; return this.cmd.run(m, r); } clone() { if (hasCloneMethod(this.cmd)) return new _CommandWrapper(this.cmd[cloneMethod]()); return new _CommandWrapper(this.cmd); } toString() { return this.cmd.toString(); } }; // ../../../node_modules/fast-check/lib/esm/check/model/ReplayPath.js var ReplayPath = class { static parse(replayPathStr) { const [serializedCount, serializedChanges] = replayPathStr.split(':'); const counts = this.parseCounts(serializedCount); const changes = this.parseChanges(serializedChanges); return this.parseOccurences(counts, changes); } static stringify(replayPath) { const occurences = this.countOccurences(replayPath); const serializedCount = this.stringifyCounts(occurences); const serializedChanges = this.stringifyChanges(occurences); return `${serializedCount}:${serializedChanges}`; } static intToB64(n) { if (n < 26) return String.fromCharCode(n + 65); if (n < 52) return String.fromCharCode(n + 97 - 26); if (n < 62) return String.fromCharCode(n + 48 - 52); return String.fromCharCode(n === 62 ? 43 : 47); } static b64ToInt(c) { if (c >= 'a') return c.charCodeAt(0) - 97 + 26; if (c >= 'A') return c.charCodeAt(0) - 65; if (c >= '0') return c.charCodeAt(0) - 48 + 52; return c === '+' ? 62 : 63; } static countOccurences(replayPath) { return replayPath.reduce((counts, cur) => { if ( counts.length === 0 || counts[counts.length - 1].count === 64 || counts[counts.length - 1].value !== cur ) counts.push({ value: cur, count: 1 }); else counts[counts.length - 1].count += 1; return counts; }, []); } static parseOccurences(counts, changes) { const replayPath = []; for (let idx = 0; idx !== counts.length; ++idx) { const count = counts[idx]; const value = changes[idx]; for (let num = 0; num !== count; ++num) replayPath.push(value); } return replayPath; } static stringifyChanges(occurences) { let serializedChanges = ''; for (let idx = 0; idx < occurences.length; idx += 6) { const changesInt = occurences .slice(idx, idx + 6) .reduceRight((prev, cur) => prev * 2 + (cur.value ? 1 : 0), 0); serializedChanges += this.intToB64(changesInt); } return serializedChanges; } static parseChanges(serializedChanges) { const changesInt = serializedChanges.split('').map((c) => this.b64ToInt(c)); const changes = []; for (let idx = 0; idx !== changesInt.length; ++idx) { let current = changesInt[idx]; for (let n = 0; n !== 6; ++n, current >>= 1) { changes.push(current % 2 === 1); } } return changes; } static stringifyCounts(occurences) { return occurences.map(({ count }) => this.intToB64(count - 1)).join(''); } static parseCounts(serializedCount) { return serializedCount.split('').map((c) => this.b64ToInt(c) + 1); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/CommandsArbitrary.js var CommandsArbitrary = class extends Arbitrary { constructor( commandArbs, maxGeneratedCommands, maxCommands, sourceReplayPath, disableReplayLog, ) { super(); this.sourceReplayPath = sourceReplayPath; this.disableReplayLog = disableReplayLog; this.oneCommandArb = oneof(...commandArbs).map( (c) => new CommandWrapper(c), ); this.lengthArb = restrictedIntegerArbitraryBuilder( 0, maxGeneratedCommands, maxCommands, ); this.replayPath = []; this.replayPathPosition = 0; } metadataForReplay() { return this.disableReplayLog ? '' : `replayPath=${JSON.stringify(ReplayPath.stringify(this.replayPath))}`; } buildValueFor(items, shrunkOnce) { const commands2 = items.map((item) => item.value_); const context2 = { shrunkOnce, items }; return new Value( new CommandsIterable(commands2, () => this.metadataForReplay()), context2, ); } generate(mrng) { const size = this.lengthArb.generate(mrng, void 0); const sizeValue = size.value; const items = Array(sizeValue); for (let idx = 0; idx !== sizeValue; ++idx) { const item = this.oneCommandArb.generate(mrng, void 0); items[idx] = item; } this.replayPathPosition = 0; return this.buildValueFor(items, false); } canShrinkWithoutContext(value) { return false; } filterOnExecution(itemsRaw) { const items = []; for (const c of itemsRaw) { if (c.value_.hasRan) { this.replayPath.push(true); items.push(c); } else this.replayPath.push(false); } return items; } filterOnReplay(itemsRaw) { return itemsRaw.filter((c, idx) => { const state = this.replayPath[this.replayPathPosition + idx]; if (state === void 0) throw new Error(`Too short replayPath`); if (!state && c.value_.hasRan) throw new Error(`Mismatch between replayPath and real execution`); return state; }); } filterForShrinkImpl(itemsRaw) { if (this.replayPathPosition === 0) { this.replayPath = this.sourceReplayPath !== null ? ReplayPath.parse(this.sourceReplayPath) : []; } const items = this.replayPathPosition < this.replayPath.length ? this.filterOnReplay(itemsRaw) : this.filterOnExecution(itemsRaw); this.replayPathPosition += itemsRaw.length; return items; } shrink(_value, context2) { if (context2 === void 0) { return Stream.nil(); } const safeContext = context2; const shrunkOnce = safeContext.shrunkOnce; const itemsRaw = safeContext.items; const items = this.filterForShrinkImpl(itemsRaw); if (items.length === 0) { return Stream.nil(); } const rootShrink = shrunkOnce ? Stream.nil() : new Stream([[]][Symbol.iterator]()); const nextShrinks = []; for (let numToKeep = 0; numToKeep !== items.length; ++numToKeep) { nextShrinks.push( makeLazy(() => { const fixedStart = items.slice(0, numToKeep); return this.lengthArb .shrink(items.length - 1 - numToKeep, void 0) .map((l) => fixedStart.concat(items.slice(items.length - (l.value + 1))), ); }), ); } for (let itemAt = 0; itemAt !== items.length; ++itemAt) { nextShrinks.push( makeLazy(() => this.oneCommandArb .shrink(items[itemAt].value_, items[itemAt].context) .map((v) => items.slice(0, itemAt).concat([v], items.slice(itemAt + 1)), ), ), ); } return rootShrink.join(...nextShrinks).map((shrinkables) => { return this.buildValueFor( shrinkables.map((c) => new Value(c.value_.clone(), c.context)), true, ); }); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/commands.js function commands(commandArbs, constraints = {}) { const { size, maxCommands = MaxLengthUpperBound, disableReplayLog = false, replayPath = null, } = constraints; const specifiedMaxCommands = constraints.maxCommands !== void 0; const maxGeneratedCommands = maxGeneratedLengthFromSizeForArbitrary( size, 0, maxCommands, specifiedMaxCommands, ); return new CommandsArbitrary( commandArbs, maxGeneratedCommands, maxCommands, replayPath, disableReplayLog, ); } // ../../../node_modules/fast-check/lib/esm/check/model/commands/ScheduledCommand.js var ScheduledCommand = class { constructor(s, cmd) { this.s = s; this.cmd = cmd; } async check(m) { let error = null; let checkPassed = false; const status = await this.s.scheduleSequence([ { label: `check@${this.cmd.toString()}`, builder: async () => { try { checkPassed = await Promise.resolve(this.cmd.check(m)); } catch (err) { error = err; throw err; } }, }, ]).task; if (status.faulty) { throw error; } return checkPassed; } async run(m, r) { let error = null; const status = await this.s.scheduleSequence([ { label: `run@${this.cmd.toString()}`, builder: async () => { try { await this.cmd.run(m, r); } catch (err) { error = err; throw err; } }, }, ]).task; if (status.faulty) { throw error; } } }; var scheduleCommands = function* (s, cmds) { for (const cmd of cmds) { yield new ScheduledCommand(s, cmd); } }; // ../../../node_modules/fast-check/lib/esm/check/model/ModelRunner.js var genericModelRun = (s, cmds, initialValue, runCmd, then) => { return s.then((o) => { const { model, real } = o; let state = initialValue; for (const c of cmds) { state = then(state, () => { return runCmd(c, model, real); }); } return state; }); }; var internalModelRun = (s, cmds) => { const then = (_p, c) => c(); const setupProducer = { then: (fun) => { fun(s()); return void 0; }, }; const runSync = (cmd, m, r) => { if (cmd.check(m)) cmd.run(m, r); return void 0; }; return genericModelRun(setupProducer, cmds, void 0, runSync, then); }; var isAsyncSetup = (s) => { return typeof s.then === 'function'; }; var internalAsyncModelRun = async ( s, cmds, defaultPromise = Promise.resolve(), ) => { const then = (p, c) => p.then(c); const setupProducer = { then: (fun) => { const out = s(); if (isAsyncSetup(out)) return out.then(fun); else return fun(out); }, }; const runAsync = async (cmd, m, r) => { if (await cmd.check(m)) await cmd.run(m, r); }; return await genericModelRun( setupProducer, cmds, defaultPromise, runAsync, then, ); }; function modelRun(s, cmds) { internalModelRun(s, cmds); } async function asyncModelRun(s, cmds) { await internalAsyncModelRun(s, cmds); } async function scheduledModelRun(scheduler2, s, cmds) { const scheduledCommands = scheduleCommands(scheduler2, cmds); const out = internalAsyncModelRun( s, scheduledCommands, scheduler2.schedule(Promise.resolve(), 'startModel'), ); await scheduler2.waitFor(out); await scheduler2.waitAll(); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/implementations/SchedulerImplem.js var defaultSchedulerAct = (f) => f(); var SchedulerImplem = class _SchedulerImplem { constructor(act, taskSelector) { this.act = act; this.taskSelector = taskSelector; this.lastTaskId = 0; this.sourceTaskSelector = taskSelector.clone(); this.scheduledTasks = []; this.triggeredTasks = []; this.scheduledWatchers = []; } static buildLog(reportItem) { return `[task\${${reportItem.taskId}}] ${reportItem.label.length !== 0 ? `${reportItem.schedulingType}::${reportItem.label}` : reportItem.schedulingType} ${reportItem.status}${reportItem.outputValue !== void 0 ? ` with value ${escapeForTemplateString(reportItem.outputValue)}` : ''}`; } log(schedulingType, taskId, label, metadata, status, data) { this.triggeredTasks.push({ status, schedulingType, taskId, label, metadata, outputValue: data !== void 0 ? stringify(data) : void 0, }); } scheduleInternal( schedulingType, label, task, metadata, customAct, thenTaskToBeAwaited, ) { let trigger = null; const taskId = ++this.lastTaskId; const scheduledPromise = new Promise((resolve, reject) => { trigger = () => { (thenTaskToBeAwaited ? task.then(() => thenTaskToBeAwaited()) : task ).then( (data) => { this.log(schedulingType, taskId, label, metadata, 'resolved', data); return resolve(data); }, (err) => { this.log(schedulingType, taskId, label, metadata, 'rejected', err); return reject(err); }, ); }; }); this.scheduledTasks.push({ original: task, scheduled: scheduledPromise, trigger, schedulingType, taskId, label, metadata, customAct, }); if (this.scheduledWatchers.length !== 0) { this.scheduledWatchers[0](); } return scheduledPromise; } schedule(task, label, metadata, customAct) { return this.scheduleInternal( 'promise', label || '', task, metadata, customAct || defaultSchedulerAct, ); } scheduleFunction(asyncFunction, customAct) { return (...args) => this.scheduleInternal( 'function', `${asyncFunction.name}(${args.map(stringify).join(',')})`, asyncFunction(...args), void 0, customAct || defaultSchedulerAct, ); } scheduleSequence(sequenceBuilders, customAct) { const status = { done: false, faulty: false }; const dummyResolvedPromise = { then: (f) => f() }; let resolveSequenceTask = () => {}; const sequenceTask = new Promise( (resolve) => (resolveSequenceTask = resolve), ); sequenceBuilders .reduce((previouslyScheduled, item) => { const [builder, label, metadata] = typeof item === 'function' ? [item, item.name, void 0] : [item.builder, item.label, item.metadata]; return previouslyScheduled.then(() => { const scheduled = this.scheduleInternal( 'sequence', label, dummyResolvedPromise, metadata, customAct || defaultSchedulerAct, () => builder(), ); scheduled.catch(() => { status.faulty = true; resolveSequenceTask(); }); return scheduled; }); }, dummyResolvedPromise) .then( () => { status.done = true; resolveSequenceTask(); }, () => {}, ); return Object.assign(status, { task: Promise.resolve(sequenceTask).then(() => { return { done: status.done, faulty: status.faulty }; }), }); } count() { return this.scheduledTasks.length; } internalWaitOne() { if (this.scheduledTasks.length === 0) { throw new Error('No task scheduled'); } const taskIndex = this.taskSelector.nextTaskIndex(this.scheduledTasks); const [scheduledTask] = this.scheduledTasks.splice(taskIndex, 1); return scheduledTask.customAct(async () => { scheduledTask.trigger(); try { await scheduledTask.scheduled; } catch (_err) {} }); } async waitOne(customAct) { const waitAct = customAct || defaultSchedulerAct; await this.act(() => waitAct(async () => await this.internalWaitOne())); } async waitAll(customAct) { while (this.scheduledTasks.length > 0) { await this.waitOne(customAct); } } async waitFor(unscheduledTask, customAct) { let taskResolved = false; let awaiterPromise = null; const awaiter = async () => { while (!taskResolved && this.scheduledTasks.length > 0) { await this.waitOne(customAct); } awaiterPromise = null; }; const handleNotified = () => { if (awaiterPromise !== null) { return; } awaiterPromise = Promise.resolve().then(awaiter); }; const clearAndReplaceWatcher = () => { const handleNotifiedIndex = this.scheduledWatchers.indexOf(handleNotified); if (handleNotifiedIndex !== -1) { this.scheduledWatchers.splice(handleNotifiedIndex, 1); } if (handleNotifiedIndex === 0 && this.scheduledWatchers.length !== 0) { this.scheduledWatchers[0](); } }; const rewrappedTask = unscheduledTask.then( (ret) => { taskResolved = true; if (awaiterPromise === null) { clearAndReplaceWatcher(); return ret; } return awaiterPromise.then(() => { clearAndReplaceWatcher(); return ret; }); }, (err) => { taskResolved = true; if (awaiterPromise === null) { clearAndReplaceWatcher(); throw err; } return awaiterPromise.then(() => { clearAndReplaceWatcher(); throw err; }); }, ); if (this.scheduledTasks.length > 0 && this.scheduledWatchers.length === 0) { handleNotified(); } this.scheduledWatchers.push(handleNotified); return rewrappedTask; } report() { return [ ...this.triggeredTasks, ...this.scheduledTasks.map((t) => ({ status: 'pending', schedulingType: t.schedulingType, taskId: t.taskId, label: t.label, metadata: t.metadata, })), ]; } toString() { return ( 'schedulerFor()`\n' + this.report() .map(_SchedulerImplem.buildLog) .map((log) => `-> ${log}`) .join('\n') + '`' ); } [cloneMethod]() { return new _SchedulerImplem(this.act, this.sourceTaskSelector); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/BuildSchedulerFor.js function buildNextTaskIndex(ordering) { let numTasks = 0; return { clone: () => buildNextTaskIndex(ordering), nextTaskIndex: (scheduledTasks) => { if (ordering.length <= numTasks) { throw new Error( `Invalid schedulerFor defined: too many tasks have been scheduled`, ); } const taskIndex = scheduledTasks.findIndex( (t) => t.taskId === ordering[numTasks], ); if (taskIndex === -1) { throw new Error( `Invalid schedulerFor defined: unable to find next task`, ); } ++numTasks; return taskIndex; }, }; } function buildSchedulerFor(act, ordering) { return new SchedulerImplem(act, buildNextTaskIndex(ordering)); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/SchedulerArbitrary.js function buildNextTaskIndex2(mrng) { const clonedMrng = mrng.clone(); return { clone: () => buildNextTaskIndex2(clonedMrng), nextTaskIndex: (scheduledTasks) => { return mrng.nextInt(0, scheduledTasks.length - 1); }, }; } var SchedulerArbitrary = class extends Arbitrary { constructor(act) { super(); this.act = act; } generate(mrng, _biasFactor) { return new Value( new SchedulerImplem(this.act, buildNextTaskIndex2(mrng.clone())), void 0, ); } canShrinkWithoutContext(value) { return false; } shrink(_value, _context) { return Stream.nil(); } }; // ../../../node_modules/fast-check/lib/esm/arbitrary/scheduler.js function scheduler(constraints) { const { act = (f) => f() } = constraints || {}; return new SchedulerArbitrary(act); } function schedulerFor(customOrderingOrConstraints, constraintsOrUndefined) { const { act = (f) => f() } = Array.isArray(customOrderingOrConstraints) ? constraintsOrUndefined || {} : customOrderingOrConstraints || {}; if (Array.isArray(customOrderingOrConstraints)) { return buildSchedulerFor(act, customOrderingOrConstraints); } return function (_strs, ...ordering) { return buildSchedulerFor(act, ordering); }; } // ../../../node_modules/fast-check/lib/esm/arbitrary/bigInt64Array.js function bigInt64Array(constraints = {}) { return typedIntArrayArbitraryArbitraryBuilder( constraints, SBigInt('-9223372036854775808'), SBigInt('9223372036854775807'), SBigInt64Array, bigInt, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/bigUint64Array.js function bigUint64Array(constraints = {}) { return typedIntArrayArbitraryArbitraryBuilder( constraints, SBigInt(0), SBigInt('18446744073709551615'), SBigUint64Array, bigInt, ); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/SanitizeRegexAst.js function raiseUnsupportedASTNode(astNode) { return new Error(`Unsupported AST node! Received: ${stringify(astNode)}`); } function addMissingDotStarTraversalAddMissing(astNode, isFirst, isLast) { if (!isFirst && !isLast) { return astNode; } const traversalResults = { hasStart: false, hasEnd: false }; const revampedNode = addMissingDotStarTraversal( astNode, isFirst, isLast, traversalResults, ); const missingStart = isFirst && !traversalResults.hasStart; const missingEnd = isLast && !traversalResults.hasEnd; if (!missingStart && !missingEnd) { return revampedNode; } const expressions = []; if (missingStart) { expressions.push({ type: 'Assertion', kind: '^' }); expressions.push({ type: 'Repetition', quantifier: { type: 'Quantifier', kind: '*', greedy: true }, expression: { type: 'Char', kind: 'meta', symbol: '.', value: '.', codePoint: Number.NaN, }, }); } expressions.push(revampedNode); if (missingEnd) { expressions.push({ type: 'Repetition', quantifier: { type: 'Quantifier', kind: '*', greedy: true }, expression: { type: 'Char', kind: 'meta', symbol: '.', value: '.', codePoint: Number.NaN, }, }); expressions.push({ type: 'Assertion', kind: '$' }); } return { type: 'Group', capturing: false, expression: { type: 'Alternative', expressions }, }; } function addMissingDotStarTraversal( astNode, isFirst, isLast, traversalResults, ) { switch (astNode.type) { case 'Char': return astNode; case 'Repetition': return astNode; case 'Quantifier': throw new Error( `Wrongly defined AST tree, Quantifier nodes not supposed to be scanned!`, ); case 'Alternative': traversalResults.hasStart = true; traversalResults.hasEnd = true; return Object.assign(Object.assign({}, astNode), { expressions: astNode.expressions.map((node, index) => addMissingDotStarTraversalAddMissing( node, isFirst && index === 0, isLast && index === astNode.expressions.length - 1, ), ), }); case 'CharacterClass': return astNode; case 'ClassRange': return astNode; case 'Group': { return Object.assign(Object.assign({}, astNode), { expression: addMissingDotStarTraversal( astNode.expression, isFirst, isLast, traversalResults, ), }); } case 'Disjunction': { traversalResults.hasStart = true; traversalResults.hasEnd = true; return Object.assign(Object.assign({}, astNode), { left: astNode.left !== null ? addMissingDotStarTraversalAddMissing( astNode.left, isFirst, isLast, ) : null, right: astNode.right !== null ? addMissingDotStarTraversalAddMissing( astNode.right, isFirst, isLast, ) : null, }); } case 'Assertion': { if (astNode.kind === '^' || astNode.kind === 'Lookahead') { traversalResults.hasStart = true; return astNode; } else if (astNode.kind === '$' || astNode.kind === 'Lookbehind') { traversalResults.hasEnd = true; return astNode; } else { throw new Error( `Assertions of kind ${astNode.kind} not implemented yet!`, ); } } case 'Backreference': return astNode; default: throw raiseUnsupportedASTNode(astNode); } } function addMissingDotStar(astNode) { return addMissingDotStarTraversalAddMissing(astNode, true, true); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/ReadRegex.js function charSizeAt(text, pos) { return text[pos] >= '\uD800' && text[pos] <= '\uDBFF' && text[pos + 1] >= '\uDC00' && text[pos + 1] <= '\uDFFF' ? 2 : 1; } function isHexaDigit(char2) { return ( (char2 >= '0' && char2 <= '9') || (char2 >= 'a' && char2 <= 'f') || (char2 >= 'A' && char2 <= 'F') ); } function isDigit(char2) { return char2 >= '0' && char2 <= '9'; } function squaredBracketBlockContentEndFrom(text, from) { for (let index = from; index !== text.length; ++index) { const char2 = text[index]; if (char2 === '\\') { index += 1; } else if (char2 === ']') { return index; } } throw new Error(`Missing closing ']'`); } function parenthesisBlockContentEndFrom(text, from) { let numExtraOpened = 0; for (let index = from; index !== text.length; ++index) { const char2 = text[index]; if (char2 === '\\') { index += 1; } else if (char2 === ')') { if (numExtraOpened === 0) { return index; } numExtraOpened -= 1; } else if (char2 === '[') { index = squaredBracketBlockContentEndFrom(text, index); } else if (char2 === '(') { numExtraOpened += 1; } } throw new Error(`Missing closing ')'`); } function curlyBracketBlockContentEndFrom(text, from) { let foundComma = false; for (let index = from; index !== text.length; ++index) { const char2 = text[index]; if (isDigit(char2)) { } else if (from === index) { return -1; } else if (char2 === ',') { if (foundComma) { return -1; } foundComma = true; } else if (char2 === '}') { return index; } else { return -1; } } return -1; } var TokenizerBlockMode; (function (TokenizerBlockMode2) { TokenizerBlockMode2[(TokenizerBlockMode2['Full'] = 0)] = 'Full'; TokenizerBlockMode2[(TokenizerBlockMode2['Character'] = 1)] = 'Character'; })(TokenizerBlockMode || (TokenizerBlockMode = {})); function blockEndFrom(text, from, unicodeMode, mode) { switch (text[from]) { case '[': { if (mode === TokenizerBlockMode.Character) { return from + 1; } return squaredBracketBlockContentEndFrom(text, from + 1) + 1; } case '{': { if (mode === TokenizerBlockMode.Character) { return from + 1; } const foundEnd = curlyBracketBlockContentEndFrom(text, from + 1); if (foundEnd === -1) { return from + 1; } return foundEnd + 1; } case '(': { if (mode === TokenizerBlockMode.Character) { return from + 1; } return parenthesisBlockContentEndFrom(text, from + 1) + 1; } case ']': case '}': case ')': return from + 1; case '\\': { const next1 = text[from + 1]; switch (next1) { case 'x': if (isHexaDigit(text[from + 2]) && isHexaDigit(text[from + 3])) { return from + 4; } throw new Error( `Unexpected token '${text.substring(from, from + 4)}' found`, ); case 'u': if (text[from + 2] === '{') { if (!unicodeMode) { return from + 2; } if (text[from + 4] === '}') { if (isHexaDigit(text[from + 3])) { return from + 5; } throw new Error( `Unexpected token '${text.substring(from, from + 5)}' found`, ); } if (text[from + 5] === '}') { if (isHexaDigit(text[from + 3]) && isHexaDigit(text[from + 4])) { return from + 6; } throw new Error( `Unexpected token '${text.substring(from, from + 6)}' found`, ); } if (text[from + 6] === '}') { if ( isHexaDigit(text[from + 3]) && isHexaDigit(text[from + 4]) && isHexaDigit(text[from + 5]) ) { return from + 7; } throw new Error( `Unexpected token '${text.substring(from, from + 7)}' found`, ); } if (text[from + 7] === '}') { if ( isHexaDigit(text[from + 3]) && isHexaDigit(text[from + 4]) && isHexaDigit(text[from + 5]) && isHexaDigit(text[from + 6]) ) { return from + 8; } throw new Error( `Unexpected token '${text.substring(from, from + 8)}' found`, ); } if ( text[from + 8] === '}' && isHexaDigit(text[from + 3]) && isHexaDigit(text[from + 4]) && isHexaDigit(text[from + 5]) && isHexaDigit(text[from + 6]) && isHexaDigit(text[from + 7]) ) { return from + 9; } throw new Error( `Unexpected token '${text.substring(from, from + 9)}' found`, ); } if ( isHexaDigit(text[from + 2]) && isHexaDigit(text[from + 3]) && isHexaDigit(text[from + 4]) && isHexaDigit(text[from + 5]) ) { return from + 6; } throw new Error( `Unexpected token '${text.substring(from, from + 6)}' found`, ); case 'p': case 'P': { if (!unicodeMode) { return from + 2; } let subIndex = from + 2; for ( ; subIndex < text.length && text[subIndex] !== '}'; subIndex += text[subIndex] === '\\' ? 2 : 1 ) {} if (text[subIndex] !== '}') { throw new Error(`Invalid \\P definition`); } return subIndex + 1; } case 'k': { let subIndex = from + 2; for ( ; subIndex < text.length && text[subIndex] !== '>'; ++subIndex ) {} if (text[subIndex] !== '>') { if (!unicodeMode) { return from + 2; } throw new Error(`Invalid \\k definition`); } return subIndex + 1; } default: { if (isDigit(next1)) { const maxIndex = unicodeMode ? text.length : Math.min(from + 4, text.length); let subIndex = from + 2; for ( ; subIndex < maxIndex && isDigit(text[subIndex]); ++subIndex ) {} return subIndex; } const charSize = unicodeMode ? charSizeAt(text, from + 1) : 1; return from + charSize + 1; } } } default: { const charSize = unicodeMode ? charSizeAt(text, from) : 1; return from + charSize; } } } function readFrom(text, from, unicodeMode, mode) { const to = blockEndFrom(text, from, unicodeMode, mode); return text.substring(from, to); } // ../../../node_modules/fast-check/lib/esm/arbitrary/_internals/helpers/TokenizeRegex.js var safeStringFromCodePoint = String.fromCodePoint; function safePop2(tokens) { const previous = tokens.pop(); if (previous === void 0) { throw new Error( 'Unable to extract token preceeding the currently parsed one', ); } return previous; } function isDigit2(char2) { return char2 >= '0' && char2 <= '9'; } function simpleChar(char2, escaped) { return { type: 'Char', kind: 'simple', symbol: char2, value: char2, codePoint: char2.codePointAt(0) || -1, escaped, }; } function metaEscapedChar(block, symbol) { return { type: 'Char', kind: 'meta', symbol, value: block, codePoint: symbol.codePointAt(0) || -1, }; } function toSingleToken(tokens, allowEmpty) { if (tokens.length > 1) { return { type: 'Alternative', expressions: tokens, }; } if (!allowEmpty && tokens.length === 0) { throw new Error(`Unsupported no token`); } return tokens[0]; } function blockToCharToken(block) { if (block[0] === '\\') { const next = block[1]; switch (next) { case 'x': { const allDigits = block.substring(2); const codePoint = Number.parseInt(allDigits, 16); const symbol = safeStringFromCodePoint(codePoint); return { type: 'Char', kind: 'hex', symbol, value: block, codePoint }; } case 'u': { if (block === '\\u') { return simpleChar('u', true); } const allDigits = block[2] === '{' ? block.substring(3, block.length - 1) : block.substring(2); const codePoint = Number.parseInt(allDigits, 16); const symbol = safeStringFromCodePoint(codePoint); return { type: 'Char', kind: 'unicode', symbol, value: block, codePoint, }; } case '0': { return metaEscapedChar(block, '\0'); } case 'n': { return metaEscapedChar(block, '\n'); } case 'f': { return metaEscapedChar(block, '\f'); } case 'r': { return metaEscapedChar(block, '\r'); } case 't': { return metaEscapedChar(block, ' '); } case 'v': { return metaEscapedChar(block, '\v'); } case 'w': case 'W': case 'd': case 'D': case 's': case 'S': case 'b': case 'B': { return { type: 'Char', kind: 'meta', symbol: void 0, value: block, codePoint: Number.NaN, }; } default: { if (isDigit2(next)) { const allDigits = block.substring(1); const codePoint = Number(allDigits); const symbol = safeStringFromCodePoint(codePoint); return { type: 'Char', kind: 'decimal', symbol, value: block, codePoint, }; } if (block.length > 2 && (next === 'p' || next === 'P')) { throw new Error(`UnicodeProperty not implemented yet!`); } const char2 = block.substring(1); return simpleChar(char2, true); } } } return simpleChar(block); } function pushTokens(tokens, regexSource, unicodeMode, groups) { let disjunctions = null; for ( let index = 0, block = readFrom( regexSource, index, unicodeMode, TokenizerBlockMode.Full, ); index !== regexSource.length; index += block.length, block = readFrom(regexSource, index, unicodeMode, TokenizerBlockMode.Full) ) { const firstInBlock = block[0]; switch (firstInBlock) { case '|': { if (disjunctions === null) { disjunctions = []; } disjunctions.push(toSingleToken(tokens.splice(0), true) || null); break; } case '.': { tokens.push({ type: 'Char', kind: 'meta', symbol: block, value: block, codePoint: Number.NaN, }); break; } case '*': case '+': { const previous = safePop2(tokens); tokens.push({ type: 'Repetition', expression: previous, quantifier: { type: 'Quantifier', kind: firstInBlock, greedy: true }, }); break; } case '?': { const previous = safePop2(tokens); if (previous.type === 'Repetition') { previous.quantifier.greedy = false; tokens.push(previous); } else { tokens.push({ type: 'Repetition', expression: previous, quantifier: { type: 'Quantifier', kind: firstInBlock, greedy: true, }, }); } break; } case '{': { if (block === '{') { tokens.push(simpleChar(block)); break; } const previous = safePop2(tokens); const quantifierText = block.substring(1, block.length - 1); const quantifierTokens = quantifierText.split(','); const from = Number(quantifierTokens[0]); const to = quantifierTokens.length === 1 ? from : quantifierTokens[1].length !== 0 ? Number(quantifierTokens[1]) : void 0; tokens.push({ type: 'Repetition', expression: previous, quantifier: { type: 'Quantifier', kind: 'Range', greedy: true, from, to, }, }); break; } case '[': { const blockContent = block.substring(1, block.length - 1); const subTokens = []; let negative = void 0; let previousWasSimpleDash = false; for ( let subIndex = 0, subBlock = readFrom( blockContent, subIndex, unicodeMode, TokenizerBlockMode.Character, ); subIndex !== blockContent.length; subIndex += subBlock.length, subBlock = readFrom( blockContent, subIndex, unicodeMode, TokenizerBlockMode.Character, ) ) { if (subIndex === 0 && subBlock === '^') { negative = true; continue; } const newToken = blockToCharToken(subBlock); if (subBlock === '-') { subTokens.push(newToken); previousWasSimpleDash = true; } else { const operand1Token = subTokens.length >= 2 ? subTokens[subTokens.length - 2] : void 0; if ( previousWasSimpleDash && operand1Token !== void 0 && operand1Token.type === 'Char' ) { subTokens.pop(); subTokens.pop(); subTokens.push({ type: 'ClassRange', from: operand1Token, to: newToken, }); } else { subTokens.push(newToken); } previousWasSimpleDash = false; } } tokens.push({ type: 'CharacterClass', expressions: subTokens, negative, }); break; } case '(': { const blockContent = block.substring(1, block.length - 1); const subTokens = []; if (blockContent[0] === '?') { if (blockContent[1] === ':') { pushTokens( subTokens, blockContent.substring(2), unicodeMode, groups, ); tokens.push({ type: 'Group', capturing: false, expression: toSingleToken(subTokens), }); } else if (blockContent[1] === '=' || blockContent[1] === '!') { pushTokens( subTokens, blockContent.substring(2), unicodeMode, groups, ); tokens.push({ type: 'Assertion', kind: 'Lookahead', negative: blockContent[1] === '!' ? true : void 0, assertion: toSingleToken(subTokens), }); } else if ( blockContent[1] === '<' && (blockContent[2] === '=' || blockContent[2] === '!') ) { pushTokens( subTokens, blockContent.substring(3), unicodeMode, groups, ); tokens.push({ type: 'Assertion', kind: 'Lookbehind', negative: blockContent[2] === '!' ? true : void 0, assertion: toSingleToken(subTokens), }); } else { const chunks = blockContent.split('>'); if (chunks.length < 2 || chunks[0][1] !== '<') { throw new Error( `Unsupported regex content found at ${JSON.stringify(block)}`, ); } const groupIndex = ++groups.lastIndex; const nameRaw = chunks[0].substring(2); groups.named.set(nameRaw, groupIndex); pushTokens( subTokens, chunks.slice(1).join('>'), unicodeMode, groups, ); tokens.push({ type: 'Group', capturing: true, nameRaw, name: nameRaw, number: groupIndex, expression: toSingleToken(subTokens), }); } } else { const groupIndex = ++groups.lastIndex; pushTokens(subTokens, blockContent, unicodeMode, groups); tokens.push({ type: 'Group', capturing: true, number: groupIndex, expression: toSingleToken(subTokens), }); } break; } default: { if (block === '^') { tokens.push({ type: 'Assertion', kind: block }); } else if (block === '$') { tokens.push({ type: 'Assertion', kind: block }); } else if (block[0] === '\\' && isDigit2(block[1])) { const reference = Number(block.substring(1)); if (unicodeMode || reference <= groups.lastIndex) { tokens.push({ type: 'Backreference', kind: 'number', number: reference, reference, }); } else { tokens.push(blockToCharToken(block)); } } else if ( block[0] === '\\' && block[1] === 'k' && block.length !== 2 ) { const referenceRaw = block.substring(3, block.length - 1); tokens.push({ type: 'Backreference', kind: 'name', number: groups.named.get(referenceRaw) || 0, referenceRaw, reference: referenceRaw, }); } else { tokens.push(blockToCharToken(block)); } break; } } } if (disjunctions !== null) { disjunctions.push(toSingleToken(tokens.splice(0), true) || null); let currentDisjunction = { type: 'Disjunction', left: disjunctions[0], right: disjunctions[1], }; for (let index = 2; index < disjunctions.length; ++index) { currentDisjunction = { type: 'Disjunction', left: currentDisjunction, right: disjunctions[index], }; } tokens.push(currentDisjunction); } } function tokenizeRegex(regex) { const unicodeMode = safeIndexOf([...regex.flags], 'u') !== -1; const regexSource = regex.source; const tokens = []; pushTokens(tokens, regexSource, unicodeMode, { lastIndex: 0, named: /* @__PURE__ */ new Map(), }); return toSingleToken(tokens); } // ../../../node_modules/fast-check/lib/esm/arbitrary/stringMatching.js var safeStringFromCodePoint2 = String.fromCodePoint; var wordChars = [ ...'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_', ]; var digitChars = [...'0123456789']; var spaceChars = [...' \r\n\v\f']; var newLineChars = [...'\r\n']; var terminatorChars = [...'']; var newLineAndTerminatorChars = [...newLineChars, ...terminatorChars]; var defaultChar = char(); function raiseUnsupportedASTNode2(astNode) { return new SError(`Unsupported AST node! Received: ${stringify(astNode)}`); } function toMatchingArbitrary(astNode, constraints, flags) { switch (astNode.type) { case 'Char': { if (astNode.kind === 'meta') { switch (astNode.value) { case '\\w': { return constantFrom(...wordChars); } case '\\W': { return defaultChar.filter((c) => safeIndexOf(wordChars, c) === -1); } case '\\d': { return constantFrom(...digitChars); } case '\\D': { return defaultChar.filter((c) => safeIndexOf(digitChars, c) === -1); } case '\\s': { return constantFrom(...spaceChars); } case '\\S': { return defaultChar.filter((c) => safeIndexOf(spaceChars, c) === -1); } case '\\b': case '\\B': { throw new SError( `Meta character ${astNode.value} not implemented yet!`, ); } case '.': { const forbiddenChars = flags.dotAll ? terminatorChars : newLineAndTerminatorChars; return defaultChar.filter( (c) => safeIndexOf(forbiddenChars, c) === -1, ); } } } if (astNode.symbol === void 0) { throw new SError( `Unexpected undefined symbol received for non-meta Char! Received: ${stringify(astNode)}`, ); } return constant(astNode.symbol); } case 'Repetition': { const node = toMatchingArbitrary(astNode.expression, constraints, flags); switch (astNode.quantifier.kind) { case '*': { return stringOf(node, constraints); } case '+': { return stringOf( node, Object.assign(Object.assign({}, constraints), { minLength: 1 }), ); } case '?': { return stringOf( node, Object.assign(Object.assign({}, constraints), { minLength: 0, maxLength: 1, }), ); } case 'Range': { return stringOf( node, Object.assign(Object.assign({}, constraints), { minLength: astNode.quantifier.from, maxLength: astNode.quantifier.to, }), ); } default: { throw raiseUnsupportedASTNode2(astNode.quantifier); } } } case 'Quantifier': { throw new SError( `Wrongly defined AST tree, Quantifier nodes not supposed to be scanned!`, ); } case 'Alternative': { return tuple( ...safeMap(astNode.expressions, (n) => toMatchingArbitrary(n, constraints, flags), ), ).map((vs) => safeJoin(vs, '')); } case 'CharacterClass': if (astNode.negative) { const childrenArbitraries = safeMap(astNode.expressions, (n) => toMatchingArbitrary(n, constraints, flags), ); return defaultChar.filter((c) => safeEvery( childrenArbitraries, (arb) => !arb.canShrinkWithoutContext(c), ), ); } return oneof( ...safeMap(astNode.expressions, (n) => toMatchingArbitrary(n, constraints, flags), ), ); case 'ClassRange': { const min = astNode.from.codePoint; const max = astNode.to.codePoint; return integer({ min, max }).map( (n) => safeStringFromCodePoint2(n), (c) => { if (typeof c !== 'string') throw new SError('Invalid type'); if ([...c].length !== 1) throw new SError('Invalid length'); return c.codePointAt(0); }, ); } case 'Group': { return toMatchingArbitrary(astNode.expression, constraints, flags); } case 'Disjunction': { const left = astNode.left !== null ? toMatchingArbitrary(astNode.left, constraints, flags) : constant(''); const right = astNode.right !== null ? toMatchingArbitrary(astNode.right, constraints, flags) : constant(''); return oneof(left, right); } case 'Assertion': { if (astNode.kind === '^' || astNode.kind === '$') { if (flags.multiline) { if (astNode.kind === '^') { return oneof( constant(''), tuple(stringOf(defaultChar), constantFrom(...newLineChars)).map( (t) => `${t[0]}${t[1]}`, (value) => { if (typeof value !== 'string' || value.length === 0) throw new SError('Invalid type'); return [ value.substring(0, value.length - 1), value[value.length - 1], ]; }, ), ); } else { return oneof( constant(''), tuple(constantFrom(...newLineChars), stringOf(defaultChar)).map( (t) => `${t[0]}${t[1]}`, (value) => { if (typeof value !== 'string' || value.length === 0) throw new SError('Invalid type'); return [value[0], value.substring(1)]; }, ), ); } } return constant(''); } throw new SError( `Assertions of kind ${astNode.kind} not implemented yet!`, ); } case 'Backreference': { throw new SError(`Backreference nodes not implemented yet!`); } default: { throw raiseUnsupportedASTNode2(astNode); } } } function stringMatching(regex, constraints = {}) { for (const flag of regex.flags) { if ( flag !== 'd' && flag !== 'g' && flag !== 'm' && flag !== 's' && flag !== 'u' ) { throw new SError( `Unable to use "stringMatching" against a regex using the flag ${flag}`, ); } } const sanitizedConstraints = { size: constraints.size }; const flags = { multiline: regex.multiline, dotAll: regex.dotAll }; const regexRootToken = addMissingDotStar(tokenizeRegex(regex)); return toMatchingArbitrary(regexRootToken, sanitizedConstraints, flags); } // ../../../node_modules/fast-check/lib/esm/fast-check-default.js var __type2 = 'module'; var __version2 = '3.17.2'; var __commitHash2 = 'a377b81e6e8362ad7324cf65b75bc5e93d12af64'; // ../../../node_modules/fast-check/lib/esm/fast-check.js var fast_check_default = fast_check_default_exports; export { Arbitrary, ExecutionStatus, PreconditionFailure, Random, Stream, Value, VerbosityLevel, __commitHash2 as __commitHash, __type2 as __type, __version2 as __version, anything, array, ascii, asciiString, assert, asyncDefaultReportMessage, asyncModelRun, asyncProperty, asyncStringify, asyncToStringMethod, base64, base64String, bigInt, bigInt64Array, bigIntN, bigUint, bigUint64Array, bigUintN, boolean, char, char16bits, check, clone, cloneIfNeeded, cloneMethod, commands, compareBooleanFunc, compareFunc, configureGlobal, constant, constantFrom, context, createDepthIdentifier, date, fast_check_default as default, defaultReportMessage, dictionary, domain, double, emailAddress, falsy, float, float32Array, float64Array, fullUnicode, fullUnicodeString, func, gen, getDepthContextFor, hasAsyncToStringMethod, hasCloneMethod, hasToStringMethod, hash, hexa, hexaString, infiniteStream, int16Array, int32Array, int8Array, integer, ipV4, ipV4Extended, ipV6, json, jsonValue, letrec, lorem, mapToConstant, maxSafeInteger, maxSafeNat, memo, mixedCase, modelRun, nat, object, oneof, option, pre, property, readConfigureGlobal, record, resetConfigureGlobal, sample, scheduledModelRun, scheduler, schedulerFor, shuffledSubarray, sparseArray, statistics, stream, string, string16bits, stringMatching, stringOf, stringify, subarray, toStringMethod, tuple, uint16Array, uint32Array, uint8Array, uint8ClampedArray, ulid, unicode, unicodeJson, unicodeJsonValue, unicodeString, uniqueArray, uuid, uuidV, webAuthority, webFragments, webPath, webQueryParameters, webSegment, webUrl, }; ================================================ FILE: integration-tests/js-compute/fixtures/app/src/fastly-global.js ================================================ /// /* eslint-env serviceworker */ import { assert } from './assertions.js'; import { routes } from './routes.js'; import { sdkVersion } from 'fastly:experimental'; routes.set('/fastly/now', function () { assert(typeof fastly.now, 'function', 'typeof fastly.now'); assert(fastly.now.name, 'now', 'fastly.now.name'); assert(fastly.now.length, 0, 'fastly.now.length'); assert(typeof fastly.now(), 'number', `typeof fastly.now()`); assert(fastly.now() > Date.now(), true, `fastly.now() > Date.now()`); }); routes.set('/fastly/version', function () { assert(typeof fastly.sdkVersion, 'string', 'typeof fastly.sdkVersion'); assert( fastly.sdkVersion, sdkVersion, 'fastly.sdkVersion matches fastly:experimental#sdkVersion', ); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/fetch-errors.js ================================================ /// import { assertRejects } from './assertions.js'; import { routes } from './routes.js'; import { Backend } from 'fastly:backend'; import { allowDynamicBackends } from 'fastly:experimental'; routes.set('/fetch-errors', async () => { allowDynamicBackends(true); await assertRejects( async () => { await fetch('http://127.0.0.1'); }, DOMException, 'Connection refused', ); await assertRejects( async () => { await fetch('https://fastly.com/', { backend: new Backend({ name: 'b1', target: 'fastly.com:8080', }), }); }, DOMException, 'Connection refused', ); await assertRejects( async () => { await fetch('https://fastly.com', { backend: new Backend({ name: 'b3', target: 'fastly.com', useSSL: true, certificateHostname: 'google.com', }), }); }, DOMException, 'TLS certificate error', ); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/geoip.js ================================================ /* eslint-env serviceworker */ /* global fastly */ import { assert, assertThrows, strictEqual } from './assertions.js'; import { getGeolocationForIpAddress } from 'fastly:geolocation'; import { isRunningLocally, routes } from './routes.js'; routes.set('/fastly/getgeolocationforipaddress/interface', async function () { let actual = Reflect.getOwnPropertyDescriptor( fastly, 'getGeolocationForIpAddress', ); let expected = { writable: true, enumerable: true, configurable: true, value: fastly.getGeolocationForIpAddress, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(fastly, 'getGeolocationForIpAddress)`, ); assert( typeof fastly.getGeolocationForIpAddress, 'function', `typeof fastly.getGeolocationForIpAddress`, ); actual = Reflect.getOwnPropertyDescriptor( fastly.getGeolocationForIpAddress, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(fastly.getGeolocationForIpAddress, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( fastly.getGeolocationForIpAddress, 'name', ); expected = { value: 'getGeolocationForIpAddress', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(fastly.getGeolocationForIpAddress, 'name')`, ); }); routes.set( '/fastly/getgeolocationforipaddress/called-as-constructor', async () => { assertThrows( () => { new fastly.getGeolocationForIpAddress('1.2.3.4'); }, TypeError, `fastly.getGeolocationForIpAddress is not a constructor`, ); }, ); // https://tc39.es/ecma262/#sec-tostring routes.set( '/fastly/getgeolocationforipaddress/parameter-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const key = { toString() { throw sentinel; }, }; fastly.getGeolocationForIpAddress(key); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => { fastly.getGeolocationForIpAddress(Symbol()); }, Error, `can't convert symbol to string`, ); }, ); routes.set( '/fastly/getgeolocationforipaddress/parameter-not-supplied', async () => { assertThrows( () => { fastly.getGeolocationForIpAddress(); }, TypeError, `fastly.getGeolocationForIpAddress: At least 1 argument required, but only 0 passed`, ); }, ); routes.set( '/fastly/getgeolocationforipaddress/parameter-empty-string', async () => { assertThrows( () => { fastly.getGeolocationForIpAddress(''); }, Error, `Invalid address passed to fastly.getGeolocationForIpAddress`, ); }, ); let geoFields = [ 'as_name', 'as_number', 'area_code', 'city', 'conn_speed', 'conn_type', 'continent', 'country_code', 'country_code3', 'country_name', 'gmt_offset', 'latitude', 'longitude', 'metro_code', 'postal_code', 'proxy_description', 'proxy_type', 'region', 'utc_offset', ]; routes.set('/fastly/getgeolocationforipaddress/bad-ip', async () => { let geo = fastly.getGeolocationForIpAddress('0.0.0.0'); if (isRunningLocally()) { strictEqual( geo, null, `fastly.getGeolocationForIpAddress('0.0.0.0') == null`, ); } else { strictEqual(geo.as_name, '?'); } assertThrows(() => { fastly.getGeolocationForIpAddress('999.999.999.999'); }, Error); }); routes.set( '/fastly/getgeolocationforipaddress/parameter-ipv4-string', async () => { let geo = fastly.getGeolocationForIpAddress('151.101.1.1'); if (isRunningLocally()) { strictEqual(geo, null); } else { assert( Object.keys(geo), geoFields, `Object.keys(fastly.getGeolocationForIpAddress('151.101.1.1')) == geoFields`, ); } }, ); routes.set( '/fastly/getgeolocationforipaddress/parameter-compressed-ipv6-string', async () => { if (isRunningLocally()) { let geo = fastly.getGeolocationForIpAddress('2607:f0d0:1002:51::4'); assert( Object.keys(geo), geoFields, `Object.keys(fastly.getGeolocationForIpAddress('2607:f0d0:1002:51::4')) == geoFields`, ); } }, ); routes.set( '/fastly/getgeolocationforipaddress/parameter-shortened-ipv6-string', async () => { if (isRunningLocally()) { let geo = fastly.getGeolocationForIpAddress( '2607:f0d0:1002:0051:0:0:0:0004', ); assert( Object.keys(geo), geoFields, `Object.keys(fastly.getGeolocationForIpAddress('2607:f0d0:1002:0051:0:0:0:0004')) == geoFields`, ); } }, ); routes.set( '/fastly/getgeolocationforipaddress/parameter-expanded-ipv6-string', async () => { if (isRunningLocally()) { let geo = fastly.getGeolocationForIpAddress( '2607:f0d0:1002:0051:0000:0000:0000:0004', ); assert( Object.keys(geo), geoFields, `Object.keys(fastly.getGeolocationForIpAddress('2607:f0d0:1002:0051:0000:0000:0000:0004')) == geoFields`, ); } }, ); routes.set('/fastly/getgeolocationforipaddress/called-unbound', async () => { if (isRunningLocally()) { let geo = fastly.getGeolocationForIpAddress.call( undefined, '2607:f0d0:1002:0051:0000:0000:0000:0004', ); assert( Object.keys(geo), geoFields, `Object.keys(fastly.getGeolocationForIpAddress('2607:f0d0:1002:0051:0000:0000:0000:0004')) == geoFields`, ); } }); routes.set('/fastly:geolocation', async () => { assert( getGeolocationForIpAddress, fastly.getGeolocationForIpAddress, 'getGeolocationForIpAddress === fastly.getGeolocationForIpAddress', ); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/headers.js ================================================ /* eslint-env serviceworker */ import { routes } from './routes.js'; import { assert } from './assertions.js'; import { CacheOverride } from 'fastly:cache-override'; routes.set('/headers/construct', async () => { const headers = new Headers(); headers.set('foo', 'bar'); return new Response('check headers', { headers }); }); routes.set('/headers/getsetcookie', async () => { let response = await fetch( 'https://http-me.fastly.dev/meow?header=Set-Cookie:name1=value1', { backend: 'httpme', }, ); response.headers.append('Set-Cookie', 'name2=value2'); console.log( 'response.headers.getSetCookie()', response.headers.getSetCookie(), ); }); routes.set('/headers/from-response/set', async () => { const response = await fetch('https://http-me.fastly.dev/anything', { backend: 'httpme', cacheOverride: new CacheOverride('pass'), }); response.headers.set('cuStom', 'test'); return response; }); routes.set('/headers/from-response/delete-invalid', async () => { const response = await fetch('https://http-me.fastly.dev/anything', { backend: 'httpme', cacheOverride: new CacheOverride('pass'), }); response.headers.delete('none'); return response; }); routes.set('/headers/from-response/set-delete', async () => { const response = await fetch('https://http-me.fastly.dev/anything', { backend: 'httpme', cacheOverride: new CacheOverride('pass'), }); response.headers.set('custom', 'test'); response.headers.delete('access-control-allow-origin'); return response; }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/html-rewriter.js ================================================ /* eslint-env serviceworker */ import { routes } from './routes.js'; import { HTMLRewritingStream } from 'fastly:html-rewriter'; import { assert, assertThrows, assertRejects, strictEqual, } from './assertions.js'; routes.set('/html-rewriter/set-attribute', async () => { const toRewrite = 'Test

Hello, World!

'; const expected = 'Test

Hello, World!

'; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('h1', (e) => { e.setAttribute('class', 'a-rewritten-class'); e.setAttribute('id', 'a-rewritten-id'); e.setAttribute('custom-attr', 'custom-value'); }), ); let text = await new Response(body, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(text, expected); }); routes.set('/html-rewriter/get-attribute', async () => { const toRewrite = 'Test

Hello, World!

'; let classAttr, idAttr; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('h1', (e) => { classAttr = e.getAttribute('class'); idAttr = e.getAttribute('id'); }), ); await new Response(body, { headers: { 'Content-Type': 'text/html' } }).text(); strictEqual(classAttr, 'a-class'); strictEqual(idAttr, 'an-id'); }); routes.set('/html-rewriter/remove-attribute', async () => { const toRewrite = 'Test

Hello, World!

'; const expected = 'Test

Hello, World!

'; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('h1', (e) => { e.removeAttribute('class'); e.removeAttribute('id'); e.removeAttribute('custom-attr'); }), ); let text = await new Response(body, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(text, expected); }); routes.set('/html-rewriter/replace-with', async () => { const toRewrite = 'Test

Hello, World!

'; const expected = 'Test

Goodbye, World!

'; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('h1', (e) => { e.replaceWith('

Goodbye, World!

'); }), ); let text = await new Response(body, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(text, expected); }); routes.set('/html-rewriter/replace-children', async () => { const toRewrite = 'Test

Hello, World!

'; const expected = 'Test

Goodbye, World!

'; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('h1', (e) => { e.replaceChildren('Goodbye, World!'); }), ); let text = await new Response(body, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(text, expected); }); routes.set('/html-rewriter/insert', async () => { const toRewrite = 'Test

Hello, World!

'; const expected = 'TestBefore -

Prefix - Hello, World! - Suffix

- After'; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('h1', (e) => { e.before('Before - '); e.prepend('Prefix - '); e.append(' - Suffix'); e.after(' - After'); }), ); let text = await new Response(body, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(text, expected); }); routes.set('/html-rewriter/complex-selector', async () => { const toRewrite = "Test

Hello, World!

Hello again, World!

"; const expected = "Test

Hello, World!

Hello again, World!

"; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('div.a-class > h1[id^="an"]', (e) => { e.setAttribute('custom-attr', 'custom-value'); }), ); let text = await new Response(body, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(text, expected); }); routes.set('/html-rewriter/no-match-rewritten-content', async () => { const toRewrite = 'Test
'; const expected = 'Test

Hello, World!

'; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream() .onElement('div', (e) => { e.setAttribute('class', 'a-class'); e.append('

Hello, World!

'); }) .onElement('h1', (e) => { // should not be called, as h1 does not exist in original content e.setAttribute('custom-attr', 'custom-value'); }), ); let text = await new Response(body, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(text, expected); }); routes.set('/html-rewriter/multiple-handlers', async () => { const toRewrite = "Test

Hello, World!

Hello again, World!

"; const expected = 'Test

Hello, World!

Hello again, World!

'; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream() .onElement('div.a-class', (e) => { e.setAttribute('custom-attr', 'custom-value'); }) .onElement('h1', (e) => { e.setAttribute('another-attr', 'another-value'); }), ); let text = await new Response(body, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(text, expected); }); routes.set('/html-rewriter/invalid-selector', async () => { assertThrows(() => { new HTMLRewritingStream().onElement('div..a-class', (e) => { e.setAttribute('custom-attr', 'custom-value'); }); }, Error); }); routes.set('/html-rewriter/invalid-handler', async () => { assertThrows(() => { new HTMLRewritingStream().onElement( 'div.a-class', 'this is not a function', ); }, Error); }); routes.set('/html-rewriter/throw-in-handler', async () => { const toRewrite = "Test

Hello, World!

"; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('div.a-class', (e) => { throw new Error('This is an error from the handler'); }), ); assertRejects(async () => { await new Response(body, { headers: { 'Content-Type': 'text/html' }, }).text(); }, Error); }); routes.set('/html-rewriter/invalid-html', async () => { const toRewrite = 'This is not HTML content'; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('div.a-class', (e) => { e.setAttribute('custom-attr', 'custom-value'); }), ); assertRejects(async () => { await new Response(body, { headers: { 'Content-Type': 'text/plain' }, }).text(); }, Error); }); routes.set('/html-rewriter/insertion-order', async () => { const toRewrite = 'Test

Hello, World!

'; const expected = 'TestFirst - Before -

Prefix - Other Prefix - Hello, World! - Suffix - Other Suffix

- After - Last'; let body = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('h1', (e) => { e.before('First - '); e.before('Before - '); // The insertion position is maintained, so prepends are inserted in reverse order e.prepend('Other Prefix - '); e.prepend('Prefix - '); e.append(' - Suffix'); e.append(' - Other Suffix'); // The insertion position is maintained, so appends are inserted in reverse order e.after(' - Last'); e.after(' - After'); }), ); let text = await new Response(body, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(text, expected); }); routes.set('/html-rewriter/escape-html', async () => { const toRewrite = 'Test

Hello, World!

'; const expectedNoEscape = 'Test

Hello, Beautiful World!

'; const expectedEscape = 'Test

Hello, <strong>Beautiful</strong> World!

'; let bodyNoEscape = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('em', (e) => { e.before('Beautiful ', { escapeHTML: false }); }), ); let textNoEscape = await new Response(bodyNoEscape, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(textNoEscape, expectedNoEscape); let bodyEscape = new Response(toRewrite, { headers: { 'Content-Type': 'text/html' }, }).body.pipeThrough( new HTMLRewritingStream().onElement('em', (e) => { e.before('Beautiful ', { escapeHTML: true }); }), ); let textEscape = await new Response(bodyEscape, { headers: { 'Content-Type': 'text/html' }, }).text(); strictEqual(textEscape, expectedEscape); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/image-optimizer.js ================================================ /* eslint-env serviceworker */ import { routes } from './routes.js'; import { Region, Auto, BWAlgorithm, CropMode, Disable, Enable, Fit, Metadata, Optimize, Orient, Profile, ResizeFilter, optionsToQueryString, } from 'fastly:image-optimizer'; import { assert, assertThrows } from './assertions.js'; // Enums routes.set('/image-optimizer/options/region', () => { assert(optionsToQueryString({ region: Region.UsEast }), 'region=us_east'); assert(optionsToQueryString({ region: Region.Asia }), 'region=asia'); assertThrows(() => optionsToQueryString({ region: 'invalid' }), TypeError); assertThrows(() => optionsToQueryString({}), TypeError); }); routes.set('/image-optimizer/options/auto', () => { assert( optionsToQueryString({ region: Region.Asia, auto: Auto.AVIF }), 'region=asia&auto=avif', ); assert( optionsToQueryString({ region: Region.Asia, auto: Auto.WEBP }), 'region=asia&auto=webp', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, auto: 'invalid' }), TypeError, ); }); routes.set('/image-optimizer/options/bw', () => { assert( optionsToQueryString({ region: Region.EuCentral, bw: BWAlgorithm.Threshold, }), 'region=eu_central&bw=threshold', ); assert( optionsToQueryString({ region: Region.EuCentral, bw: BWAlgorithm.Atkinson, }), 'region=eu_central&bw=atkinson', ); assertThrows( () => optionsToQueryString({ region: Region.EuCentral, bw: 'invalid' }), TypeError, ); }); routes.set('/image-optimizer/options/crop-mode', () => { const qs = optionsToQueryString({ region: Region.UsWest, crop: { size: { absolute: { width: 100, height: 100 } }, mode: CropMode.Smart, }, }); assert(qs.includes('smart'), true); assertThrows( () => optionsToQueryString({ region: Region.UsWest, crop: { size: { absolute: { width: 100, height: 100 } }, mode: 'bad' }, }), TypeError, ); }); routes.set('/image-optimizer/options/disable', () => { assert( optionsToQueryString({ region: Region.Australia, disable: Disable.Upscale, }), 'region=australia&disable=upscale', ); assertThrows(() => optionsToQueryString({ region: Region.Australia, disable: 'invalid' }), ); }); routes.set('/image-optimizer/options/enable', () => { assert( optionsToQueryString({ region: Region.Australia, enable: Enable.Upscale }), 'region=australia&enable=upscale', ); assertThrows(() => optionsToQueryString({ region: Region.Australia, enable: 'invalid' }), ); }); routes.set('/image-optimizer/options/fit', () => { assert( optionsToQueryString({ region: Region.Australia, fit: Fit.Crop }), 'region=australia&fit=crop', ); assert( optionsToQueryString({ region: Region.Australia, fit: Fit.Cover }), 'region=australia&fit=cover', ); assertThrows(() => optionsToQueryString({ region: Region.Australia, fit: 'invalid' }), ); }); routes.set('/image-optimizer/options/metadata', () => { assert( optionsToQueryString({ region: Region.Australia, metadata: Metadata.C2PA }), 'region=australia&metadata=c2pa', ); assert( optionsToQueryString({ region: Region.Australia, metadata: Metadata.CopyrightAndC2PA, }), 'region=australia&metadata=copyright,c2pa', ); assertThrows(() => optionsToQueryString({ region: Region.Australia, metadata: 'invalid' }), ); }); routes.set('/image-optimizer/options/optimize', () => { assert( optionsToQueryString({ region: Region.Australia, optimize: Optimize.Low }), 'region=australia&optimize=low', ); assert( optionsToQueryString({ region: Region.Australia, optimize: Optimize.High }), 'region=australia&optimize=high', ); assertThrows(() => optionsToQueryString({ region: Region.Australia, optimize: 'invalid' }), ); }); routes.set('/image-optimizer/options/orient', () => { assert( optionsToQueryString({ region: Region.Australia, orient: Orient.Default }), 'region=australia&orient=1', ); assert( optionsToQueryString({ region: Region.Australia, orient: Orient.FlipHorizontalOrientRight, }), 'region=australia&orient=7', ); assertThrows(() => optionsToQueryString({ region: Region.Australia, orient: 'invalid' }), ); }); routes.set('/image-optimizer/options/profile', () => { assert( optionsToQueryString({ region: Region.Australia, profile: Profile.Baseline, }), 'region=australia&profile=baseline', ); assert( optionsToQueryString({ region: Region.Australia, profile: Profile.Main }), 'region=australia&profile=main', ); assertThrows(() => optionsToQueryString({ region: Region.Australia, profile: 'invalid' }), ); }); routes.set('/image-optimizer/options/resizeFilter', () => { assert( optionsToQueryString({ region: Region.Australia, resizeFilter: ResizeFilter.Bicubic, }), 'region=australia&resize-filter=bicubic', ); assert( optionsToQueryString({ region: Region.Australia, resizeFilter: ResizeFilter.Lanczos2, }), 'region=australia&resize-filter=lanczos2', ); assertThrows(() => optionsToQueryString({ region: Region.Australia, resizeFilter: 'invalid' }), ); }); // Other options routes.set('/image-optimizer/options/bgColor', () => { // Hex strings assert( optionsToQueryString({ region: Region.Asia, bgColor: '123456', }), 'region=asia&bg-color=123456', ); assert( optionsToQueryString({ region: Region.Asia, bgColor: 'a2345e', }), 'region=asia&bg-color=a2345e', ); assert( optionsToQueryString({ region: Region.Asia, bgColor: '123', }), 'region=asia&bg-color=123', ); assert( optionsToQueryString({ region: Region.Asia, bgColor: 'a2e', }), 'region=asia&bg-color=a2e', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, bgColor: '12', }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, bgColor: '12j', }), TypeError, ); // RGB(A) assert( optionsToQueryString({ region: Region.Asia, bgColor: { r: 255, g: 0, b: 128, }, }), 'region=asia&bg-color=255,0,128', ); assert( optionsToQueryString({ region: Region.Asia, bgColor: { r: 255, g: 0, b: 128, a: 0.5, }, }), 'region=asia&bg-color=255,0,128,0.500000', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, bgColor: { r: 12, b: 12, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, bgColor: { r: 12, b: 1212, g: 12, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, bgColor: 123123, }), TypeError, ); }); routes.set('/image-optimizer/options/blur', () => { assert( optionsToQueryString({ region: Region.Asia, blur: 0.5 }), 'region=asia&blur=0.500000', ); assert( optionsToQueryString({ region: Region.Asia, blur: 1000 }), 'region=asia&blur=1000.000000', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, blur: 1001 }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, blur: 0.4 }), TypeError, ); assert( optionsToQueryString({ region: Region.Asia, blur: '10%' }), 'region=asia&blur=10.000000p', ); assert( optionsToQueryString({ region: Region.Asia, blur: '0.5%' }), 'region=asia&blur=0.500000p', ); }); routes.set('/image-optimizer/options/brightness', () => { assert( optionsToQueryString({ region: Region.Asia, brightness: 0.5 }), 'region=asia&brightness=0.500000', ); assert( optionsToQueryString({ region: Region.Asia, brightness: 100 }), 'region=asia&brightness=100.000000', ); assert( optionsToQueryString({ region: Region.Asia, brightness: -100 }), 'region=asia&brightness=-100.000000', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, brightness: 1001 }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, brightness: -101 }), TypeError, ); }); routes.set('/image-optimizer/options/canvas', () => { assert( optionsToQueryString({ region: Region.Asia, canvas: { size: { absolute: { width: 100, height: '10%', }, }, }, }), 'region=asia&canvas=100,10.000000p', ); assert( optionsToQueryString({ region: Region.Asia, canvas: { size: { ratio: { width: 4, height: 3, }, }, }, }), 'region=asia&canvas=4.000000:3.000000', ); assert( optionsToQueryString({ region: Region.Asia, canvas: { size: { absolute: { width: 100, height: '10%', }, }, position: { x: 10, offsetY: 10, }, }, }), 'region=asia&canvas=100,10.000000p,x10,offset-y10.000000', ); assert( optionsToQueryString({ region: Region.Asia, canvas: { size: { ratio: { width: 4, height: 3, }, }, position: { offsetX: 10, y: '10%', }, }, }), 'region=asia&canvas=4.000000:3.000000,offset-x10.000000,y10.000000p', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, canvas: { position: { offsetX: 10, y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, canvas: { size: { ratio: { width: '4%', height: 3, }, }, position: { offsetX: 10, y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, canvas: { size: { ratio: { width: '4%', height: 3, }, }, position: { offsetX: 10, x: 100, y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, canvas: { size: { ratio: { width: '4%', height: 3, }, }, position: { y: '10%', }, }, }), TypeError, ); }); routes.set('/image-optimizer/options/crop', () => { assert( optionsToQueryString({ region: Region.Asia, crop: { size: { absolute: { width: 100, height: '10%', }, }, }, }), 'region=asia&crop=100,10.000000p', ); assert( optionsToQueryString({ region: Region.Asia, crop: { size: { ratio: { width: 4, height: 3, }, }, }, }), 'region=asia&crop=4.000000:3.000000', ); assert( optionsToQueryString({ region: Region.Asia, crop: { size: { absolute: { width: 100, height: '10%', }, }, position: { x: 10, offsetY: 10, }, }, }), 'region=asia&crop=100,10.000000p,x10,offset-y10.000000', ); assert( optionsToQueryString({ region: Region.Asia, crop: { size: { ratio: { width: 4, height: 3, }, }, position: { offsetX: 10, y: '10%', }, }, }), 'region=asia&crop=4.000000:3.000000,offset-x10.000000,y10.000000p', ); assert( optionsToQueryString({ region: Region.Asia, crop: { size: { ratio: { width: 4, height: 3, }, }, position: { offsetX: 10, y: '10%', }, mode: CropMode.Safe, }, }), 'region=asia&crop=4.000000:3.000000,offset-x10.000000,y10.000000p,safe', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, crop: { position: { offsetX: 10, y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, crop: { size: { ratio: { width: '4%', height: 3, }, }, position: { offsetX: 10, y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, crop: { size: { ratio: { width: '4%', height: 3, }, }, position: { offsetX: 10, x: 100, y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, crop: { size: { ratio: { width: '4%', height: 3, }, }, position: { y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, crop: { size: { ratio: { width: 4, height: 3, }, }, position: { offsetX: 10, y: '10%', }, mode: 'invalid', }, }), TypeError, ); }); routes.set('/image-optimizer/options/precrop', () => { assert( optionsToQueryString({ region: Region.Asia, precrop: { size: { absolute: { width: 100, height: '10%', }, }, }, }), 'region=asia&precrop=100,10.000000p', ); assert( optionsToQueryString({ region: Region.Asia, precrop: { size: { ratio: { width: 4, height: 3, }, }, }, }), 'region=asia&precrop=4.000000:3.000000', ); assert( optionsToQueryString({ region: Region.Asia, precrop: { size: { absolute: { width: 100, height: '10%', }, }, position: { x: 10, offsetY: 10, }, }, }), 'region=asia&precrop=100,10.000000p,x10,offset-y10.000000', ); assert( optionsToQueryString({ region: Region.Asia, precrop: { size: { ratio: { width: 4, height: 3, }, }, position: { offsetX: 10, y: '10%', }, }, }), 'region=asia&precrop=4.000000:3.000000,offset-x10.000000,y10.000000p', ); assert( optionsToQueryString({ region: Region.Asia, precrop: { size: { ratio: { width: 4, height: 3, }, }, position: { offsetX: 10, y: '10%', }, mode: CropMode.Safe, }, }), 'region=asia&precrop=4.000000:3.000000,offset-x10.000000,y10.000000p,safe', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, precrop: { position: { offsetX: 10, y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, precrop: { size: { ratio: { width: '4%', height: 3, }, }, position: { offsetX: 10, y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, precrop: { size: { ratio: { width: '4%', height: 3, }, }, position: { offsetX: 10, x: 100, y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, precrop: { size: { ratio: { width: '4%', height: 3, }, }, position: { y: '10%', }, }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, precrop: { size: { ratio: { width: 4, height: 3, }, }, position: { offsetX: 10, y: '10%', }, mode: 'invalid', }, }), TypeError, ); }); routes.set('/image-optimizer/options/dpr', () => { assert( optionsToQueryString({ region: Region.Asia, dpr: 1.5 }), 'region=asia&dpr=1.500000', ); assert( optionsToQueryString({ region: Region.Asia, dpr: 10 }), 'region=asia&dpr=10.000000', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, dpr: '1001' }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, dpr: 1001 }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, dpr: 0.5 }), TypeError, ); }); routes.set('/image-optimizer/options/frame', () => { assert( optionsToQueryString({ region: Region.Asia, frame: 1 }), 'region=asia&frame=1', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, frame: 2 }), TypeError, ); }); routes.set('/image-optimizer/options/height', () => { assert( optionsToQueryString({ region: Region.Asia, height: 1000 }), 'region=asia&height=1000', ); assert( optionsToQueryString({ region: Region.Asia, height: '10%' }), 'region=asia&height=10.000000p', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, height: '1001' }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, height: 100.5 }), TypeError, ); }); routes.set('/image-optimizer/options/level', () => { assert( optionsToQueryString({ region: Region.Asia, level: '1.1' }), 'region=asia&level=1.1', ); assert( optionsToQueryString({ region: Region.Asia, level: '5.1' }), 'region=asia&level=5.1', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, level: 5.1 }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, level: '7.1' }), TypeError, ); }); routes.set('/image-optimizer/options/pad', () => { assert( optionsToQueryString({ region: Region.Asia, pad: { top: 10, bottom: 20, left: '10%', right: '20%', }, }), 'region=asia&pad=10,20.000000p,20,10.000000p', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, pad: { top: 10, bottom: 20, left: '10', right: '20%', }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, pad: { top: 10, left: '10', right: '20%', }, }), TypeError, ); }); routes.set('/image-optimizer/options/quality', () => { assert( optionsToQueryString({ region: Region.Asia, quality: 1 }), 'region=asia&quality=1', ); assert( optionsToQueryString({ region: Region.Asia, quality: 100 }), 'region=asia&quality=100', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, quality: 1001 }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, quality: 1.5 }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, quality: 0.4 }), TypeError, ); }); routes.set('/image-optimizer/options/saturation', () => { assert( optionsToQueryString({ region: Region.Asia, saturation: 1 }), 'region=asia&saturation=1.000000', ); assert( optionsToQueryString({ region: Region.Asia, saturation: 100 }), 'region=asia&saturation=100.000000', ); assert( optionsToQueryString({ region: Region.Asia, saturation: -100 }), 'region=asia&saturation=-100.000000', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, saturation: 1001 }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, saturation: -101 }), TypeError, ); }); routes.set('/image-optimizer/options/sharpen', () => { assert( optionsToQueryString({ region: Region.Asia, sharpen: { amount: 10, radius: 10, threshold: 1, }, }), 'region=asia&sharpen=a10.000000,r10.000000,t1', ); assert( optionsToQueryString({ region: Region.Asia, sharpen: { amount: 0.1, radius: 0.5, threshold: 255, }, }), 'region=asia&sharpen=a0.100000,r0.500000,t255', ); assertThrows(() => { optionsToQueryString({ region: Region.Asia, sharpen: { amount: 0.1, radius: 0.5, threshold: 256, }, }); }, TypeError); assertThrows(() => { optionsToQueryString({ region: Region.Asia, sharpen: { amount: 0.1, radius: 0.4, threshold: 255, }, }); }, TypeError); assertThrows(() => { optionsToQueryString({ region: Region.Asia, sharpen: { amount: -1, radius: 0.5, threshold: 255, }, }); }, TypeError); assertThrows(() => { optionsToQueryString({ region: Region.Asia, sharpen: { amount: 1, radius: 1, }, }); }, TypeError); }); routes.set('/image-optimizer/options/trim', () => { assert( optionsToQueryString({ region: Region.Asia, trim: { top: 10, bottom: 20, left: '10%', right: '20%', }, }), 'region=asia&trim=10,20.000000p,20,10.000000p', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, trim: { top: 10, bottom: 20, left: '10', right: '20%', }, }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, trim: { top: 10, left: '10', right: '20%', }, }), TypeError, ); }); routes.set('/image-optimizer/options/viewbox', () => { assert( optionsToQueryString({ region: Region.Asia, viewbox: 1 }), 'region=asia&viewbox=1', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, viewbox: 2 }), TypeError, ); }); routes.set('/image-optimizer/options/width', () => { assert( optionsToQueryString({ region: Region.Asia, width: 1000 }), 'region=asia&width=1000', ); assert( optionsToQueryString({ region: Region.Asia, width: '10%' }), 'region=asia&width=10.000000p', ); assertThrows( () => optionsToQueryString({ region: Region.Asia, width: '1001' }), TypeError, ); assertThrows( () => optionsToQueryString({ region: Region.Asia, width: 100.5 }), TypeError, ); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/include-bytes.js ================================================ import { routes } from './routes.js'; import { assert } from './assertions.js'; import { includeBytes } from 'fastly:experimental'; let message; try { message = includeBytes('message.txt'); } catch {} const expected = [ 104, 101, 108, 108, 111, 32, 105, 110, 99, 108, 117, 100, 101, 66, 121, 116, 101, 115, 10, ]; routes.set('/includeBytes', () => { assert(Array.from(message), expected, `message === expected`); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/index.js ================================================ /// /* eslint-env serviceworker */ import { routes } from './routes.js'; import { env } from 'fastly:env'; import { enableDebugLogging } from 'fastly:experimental'; import './async-select.js'; import './btoa.js'; import './byob.js'; import './byte-repeater.js'; import './cache-override.js'; import './cache-core.js'; import './cache-simple.js'; import './client.js'; import './compute.js'; import './config-store.js'; import './crypto.js'; import './device.js'; import './dictionary.js'; import './early-hints.js'; import './edge-rate-limiter.js'; import './env.js'; import './fanout.js'; import './websocket.js'; import './fastly-global.js'; import './fetch-errors.js'; import './geoip.js'; import './headers.js'; import './html-rewriter.js'; import './include-bytes.js'; import './image-optimizer.js'; import './logger.js'; import './manual-framing-headers.js'; import './missing-backend.js'; import './multiple-set-cookie.js'; import './performance.js'; import './proxy-transform-stream.js'; import './random.js'; import './react-byob.js'; import './request-auto-decompress.js'; import './request-body-async-simple.js'; import './request-cache-key.js'; import './request-clone.js'; import './request-headers.js'; import './request-method.js'; import './response-json.js'; import './response-redirect.js'; import './response.js'; import './secret-store.js'; import './security.js'; import './server.js'; import './shielding.js'; import './tee.js'; import './timers.js'; import './urlsearchparams.js'; addEventListener('fetch', (event) => { event.respondWith(app(event)); }); if (env('FASTLY_DEBUG_LOGGING') === '1') { if (fastly.debugMessages) { const { debug: consoleDebug } = console; console.debug = function debug(...args) { fastly.debugLog(...args); consoleDebug(...args); }; } enableDebugLogging(true); } /** * @param {FetchEvent} event * @returns {Response} */ async function app(event) { const FASTLY_SERVICE_VERSION = env('FASTLY_SERVICE_VERSION') || 'local'; console.log(`FASTLY_SERVICE_VERSION: ${FASTLY_SERVICE_VERSION}`); const path = new URL(event.request.url).pathname; console.log(`path: ${path}`); let res; try { const routeHandler = routes.get(path); if (routeHandler) { res = (await routeHandler(event)) || new Response('ok'); } else { try { return (res = new Response(`${path} endpoint does not exist`, { status: 500, })); } catch (errRes) { res = errRes; } } } catch (error) { if (error instanceof Response) { res = error; } else { try { return (res = new Response( `The routeHandler for ${path} threw a [${error.constructor?.name ?? error.name}] error: ${error.message || error}` + '\n' + error.stack + (fastly.debugMessages ? '\n[DEBUG BUILD MESSAGES]:\n\n - ' + fastly.debugMessages.join('\n - ') : ''), { status: 500 }, )); } catch (errRes) { res = errRes; } } } finally { res.headers.set('fastly_service_version', FASTLY_SERVICE_VERSION); } return res; } ================================================ FILE: integration-tests/js-compute/fixtures/app/src/logger.js ================================================ import { Logger, configureConsole } from 'fastly:logger'; import { routes, isRunningLocally } from './routes'; configureConsole({ prefixing: false, stderr: true }); const earlyLogger = new Logger('AnotherLog'); routes.set('/logger', () => { if (isRunningLocally()) { let logger = new Logger('ComputeLog'); logger.log('Hello!'); earlyLogger.log('World!'); } console.log('LOG'); console.error('ERROR'); return new Response(); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/manual-framing-headers.js ================================================ /// /* eslint-env serviceworker */ import { CacheOverride } from 'fastly:cache-override'; import { assert, assertRejects } from './assertions.js'; import { routes, isRunningLocally } from './routes.js'; async function requestInitObjectLiteral(manualFramingHeaders) { let request = new Request('https://http-me.fastly.dev/anything', { backend: 'httpme', method: 'POST', body: 'meow', manualFramingHeaders, headers: { 'content-length': '1', }, }); let response = await fetch(request); let body = await response.json(); return body?.headers?.['content-length']; } async function requestMethod(manualFramingHeaders) { let request = new Request('https://http-me.fastly.dev/anything', { backend: 'httpme', method: 'POST', body: 'meow', headers: { 'content-length': '1', }, }); request.setManualFramingHeaders(manualFramingHeaders); let response = await fetch(request); let body = await response.json(); return body?.headers?.['content-length']; } async function requestClone(manualFramingHeaders) { let request = new Request('https://http-me.fastly.dev/anything', { backend: 'httpme', method: 'POST', body: 'meow', manualFramingHeaders, headers: { 'content-length': '1', }, }); let response = await fetch(request.clone()); let body = await response.json(); return body?.headers?.['content-length']; } async function fetchInitObjectLiteral(manualFramingHeaders) { let response = await fetch('https://http-me.fastly.dev/anything', { backend: 'httpme', method: 'POST', body: 'meow', manualFramingHeaders, headers: { 'content-length': '1', }, }); let body = await response.json(); return body?.headers?.['content-length']; } routes.set( '/override-content-length/request/init/object-literal/true', async () => { if (isRunningLocally()) { await assertRejects(() => requestInitObjectLiteral(true)); } else { let actual = await requestInitObjectLiteral(true); let expected = '1'; assert(actual, expected, `await requestInitObjectLiteral(true)`); } }, ); routes.set( '/override-content-length/request/init/object-literal/false', async () => { let actual = await requestInitObjectLiteral(false); let expected = '4'; assert(actual, expected, `await requestInitObjectLiteral(false)`); }, ); routes.set( '/override-content-length/request/method/object-literal/true', async () => { if (isRunningLocally()) { await assertRejects(() => requestMethod(true)); } else { let actual = await requestMethod(true); let expected = '1'; assert(actual, expected, `await requestMethod(true)`); } }, ); routes.set( '/override-content-length/request/method/object-literal/false', async () => { let actual = await requestMethod(false); let expected = '4'; assert(actual, expected, `await requestMethod(false)`); }, ); routes.set('/override-content-length/request/clone/true', async () => { if (isRunningLocally()) { await assertRejects(() => requestClone(true)); } else { let actual = await requestClone(true); let expected = '1'; assert(actual, expected, `await requestClone(true)`); } }); routes.set('/override-content-length/request/clone/false', async () => { let actual = await requestClone(false); let expected = '4'; assert(actual, expected, `await requestClone(false)`); }); routes.set( '/override-content-length/fetch/init/object-literal/true', async () => { if (isRunningLocally()) { await assertRejects(() => fetchInitObjectLiteral(true)); } else { let actual = await fetchInitObjectLiteral(true); let expected = '1'; assert(actual, expected, `await fetchInitObjectLiteral(true)`); } }, ); routes.set( '/override-content-length/fetch/init/object-literal/false', async () => { let actual = await fetchInitObjectLiteral(false); let expected = '4'; assert(actual, expected, `await fetchInitObjectLiteral(false)`); }, ); async function responseInitObjectLiteral(manualFramingHeaders) { let response = new Response( new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode('meow')); controller.close(); }, }), { manualFramingHeaders, headers: { 'content-length': '4', }, }, ); return response; } async function responseInitresponseInstance(manualFramingHeaders) { let response = new Response( new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode('meow')); controller.close(); }, }), { manualFramingHeaders, headers: { 'content-length': '4', }, }, ); response = new Response( new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode('meow')); controller.close(); }, }), response, ); return response; } routes.set( '/override-content-length/response/init/object-literal/true', async () => { return responseInitObjectLiteral(true); }, ); routes.set( '/override-content-length/response/init/object-literal/false', async () => { return responseInitObjectLiteral(false); }, ); routes.set( '/override-content-length/response/init/response-instance/true', async () => { return responseInitresponseInstance(true); }, ); routes.set( '/override-content-length/response/init/response-instance/false', async () => { return responseInitresponseInstance(false); }, ); async function responseMethod(setManualFramingHeaders) { const response = await fetch('https://http-me.fastly.dev/drip=11', { backend: 'httpme', cacheOverride: new CacheOverride('pass'), }); response.setManualFramingHeaders(setManualFramingHeaders); response.headers.set('content-length', '11'); response.headers.delete('transfer-encoding'); return response; } routes.set('/override-content-length/response/method/false', async () => { return responseMethod(false); }); routes.set('/override-content-length/response/method/true', async () => { return responseMethod(true); }); async function responseClone(setManualFramingHeaders) { let response = new Response('meow', { backend: 'httpme', method: 'POST', body: 'meow', setManualFramingHeaders, headers: { 'transfer-encoding': 'chunked', }, }); response = response.clone(); return response; } // TODO: implement Response.clone routes.set('/override-content-length/response/clone/true', async () => { return responseClone(true); }); // TODO: implement Response.clone routes.set('/override-content-length/response/clone/false', async () => { return responseClone(false); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/missing-backend.js ================================================ import { assertRejects } from './assertions.js'; import { routes } from './routes.js'; routes.set('/missing-backend', async () => { await assertRejects( async () => fetch('https://example.com', { backend: 'missing' }), TypeError, `Requested backend named 'missing' does not exist`, ); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/multiple-set-cookie.js ================================================ import { routes } from './routes.js'; routes.set('/multiple-set-cookie/response-init', async () => { let h = new Headers(); h.append( 'Set-Cookie', 'test=1; expires=Tue, 06-Dec-2022 12:34:56 GMT; Max-Age=60; Path=/; HttpOnly; Secure, test_id=1; Max-Age=60; Path=/; expires=Tue, 06-Dec-2022 12:34:56 GMT, test_id=1; Max-Age=60; Path=/; expires=Tue, 06-Dec-2022 12:34:56 GMT', ); h.append('Set-Cookie', 'test2=2'); h.append('Set-Cookie', 'test3=3'); h.append('Set-Cookie', 'test4=4'); h.append('Set-Cookie', 'test5=5'); h.append('Set-Cookie', 'test6=6'); h.append('Set-Cookie', 'test7=7'); h.append('Set-Cookie', 'test8=8'); h.append('Set-Cookie', 'test9=9'); h.append('Set-Cookie', 'test10=10'); h.append('Set-Cookie', 'test11=11'); let r = new Response('Hello', { headers: h, }); return r; }); routes.set('/multiple-set-cookie/response-direct', async () => { let r = new Response('Hello'); r.headers.append( 'Set-Cookie', 'test=1; expires=Tue, 06-Dec-2022 12:34:56 GMT; Max-Age=60; Path=/; HttpOnly; Secure, test_id=1; Max-Age=60; Path=/; expires=Tue, 06-Dec-2022 12:34:56 GMT, test_id=1; Max-Age=60; Path=/; expires=Tue, 06-Dec-2022 12:34:56 GMT', ); r.headers.append('Set-Cookie', 'test2=2'); r.headers.append('Set-Cookie', 'test3=3'); r.headers.append('Set-Cookie', 'test4=4'); r.headers.append('Set-Cookie', 'test5=5'); r.headers.append('Set-Cookie', 'test6=6'); r.headers.append('Set-Cookie', 'test7=7'); r.headers.append('Set-Cookie', 'test8=8'); r.headers.append('Set-Cookie', 'test9=9'); r.headers.append('Set-Cookie', 'test10=10'); r.headers.append('Set-Cookie', 'test11=11'); return r; }); routes.set('/multiple-set-cookie/downstream', async () => { let response = await fetch( 'https://http-me.fastly.dev/append-header=Set-Cookie:test1=1/append-header=Set-Cookie:test2=2/append-header=Set-Cookie:test3=3/anything', { backend: 'httpme', }, ); return new Response('', response); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/performance.js ================================================ /* eslint-env serviceworker */ import { routes } from './routes.js'; import { assert, assertThrows } from './assertions.js'; routes.set('/Performance/interface', () => { let actual = Reflect.ownKeys(Performance); let expected = ['prototype', 'length', 'name']; assert(actual, expected, `Reflect.ownKeys(Performance)`); // Check the prototype descriptors are correct { actual = Reflect.getOwnPropertyDescriptor(Performance, 'prototype'); expected = { value: Performance.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Performance, 'prototype')`, ); } // Check the constructor function's defined parameter length is correct { actual = Reflect.getOwnPropertyDescriptor(Performance, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Performance, 'length')`, ); } // Check the constructor function's name is correct { actual = Reflect.getOwnPropertyDescriptor(Performance, 'name'); expected = { value: 'Performance', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Performance, 'name')`, ); } // Check the prototype has the correct keys { actual = Reflect.ownKeys(Performance.prototype); expected = ['constructor', 'timeOrigin', 'now', Symbol.toStringTag]; assert(actual, expected, `Reflect.ownKeys(Performance.prototype)`); } // Check the constructor on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( Performance.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: Performance.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Performance.prototype, 'constructor')`, ); assert( typeof Performance.prototype.constructor, 'function', `typeof Performance.prototype.constructor`, ); actual = Reflect.getOwnPropertyDescriptor( Performance.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Performance.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( Performance.prototype.constructor, 'name', ); expected = { value: 'Performance', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Performance.prototype.constructor, 'name')`, ); } // Check the Symbol.toStringTag on the prototype is correct { actual = Reflect.getOwnPropertyDescriptor( Performance.prototype, Symbol.toStringTag, ); expected = { value: 'performance', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Performance.prototype, [Symbol.toStringTag])`, ); assert( typeof Performance.prototype[Symbol.toStringTag], 'string', `typeof Performance.prototype[Symbol.toStringTag]`, ); } // Check the timeOrigin property is correct { const descriptors = Reflect.getOwnPropertyDescriptor( Performance.prototype, 'timeOrigin', ); expected = { enumerable: true, configurable: true }; assert( descriptors.enumerable, true, `Reflect.getOwnPropertyDescriptor(Performance, 'timeOrigin').enumerable`, ); assert( descriptors.configurable, true, `Reflect.getOwnPropertyDescriptor(Performance, 'timeOrigin').configurable`, ); assert( descriptors.value, undefined, `Reflect.getOwnPropertyDescriptor(Performance, 'timeOrigin').value`, ); assert( descriptors.set, undefined, `Reflect.getOwnPropertyDescriptor(Performance, 'timeOrigin').set`, ); assert( typeof descriptors.get, 'function', `typeof Reflect.getOwnPropertyDescriptor(Performance, 'timeOrigin').get`, ); assert( typeof Performance.prototype.timeOrigin, 'number', `typeof Performance.prototype.timeOrigin`, ); } // Check the now property is correct { actual = Reflect.getOwnPropertyDescriptor(Performance.prototype, 'now'); expected = { writable: true, enumerable: true, configurable: true, value: Performance.prototype.now, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Performance, 'now')`, ); assert( typeof Performance.prototype.now, 'function', `typeof Performance.prototype.now`, ); actual = Reflect.getOwnPropertyDescriptor( Performance.prototype.now, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Performance.prototype.now, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( Performance.prototype.now, 'name', ); expected = { value: 'now', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Performance.prototype.now, 'name')`, ); } }); routes.set('/globalThis.performance', () => { assert( globalThis.performance instanceof Performance, true, `globalThis.performance instanceof Performance`, ); }); routes.set('/globalThis.performance/now', () => { assertThrows(() => new performance.now()); assert(typeof performance.now(), 'number'); assert(performance.now() > 0, true); assert(Number.isNaN(performance.now()), false); assert(Number.isFinite(performance.now()), true); assert(performance.now() < Date.now(), true); }); routes.set('/globalThis.performance/timeOrigin', () => { assert(typeof performance.timeOrigin, 'number'); assert(performance.timeOrigin > 0, true); assert(Number.isNaN(performance.timeOrigin), false); assert(Number.isFinite(performance.timeOrigin), true); assert(performance.timeOrigin < Date.now(), true); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/proxy-transform-stream.js ================================================ /* eslint-env serviceworker */ // These are tests for the dreaded proxy transform stream optimization: https://github.com/fastly/js-compute-runtime/issues/1260 import { assert, assertThrows } from './assertions.js'; import { routes } from './routes.js'; routes.set('/proxy-transform-stream/content-length', async (event) => { let request = new Request( 'https://http-me.fastly.dev/anything', event.request, ); let proxy = new Request(request); const response = await fetch(proxy); assert(response.status, 200, 'status == 200'); assert( (await response.json()).headers['content-length'], '11', 'headers["content-length"] == 11', ); return new Response('ok'); }); routes.set( '/proxy-transform-stream/simple-response-body-chain', async (event) => { const res = new Response('body'); return new Response(res.body, res); }, ); routes.set( '/proxy-transform-stream/multi-response-body-chain', async (event) => { let res = new Response('body'); res = new Response(res.body, res); res = new Response(res.body, res); return res; }, ); routes.set('/proxy-transform-stream/response-body-into-js', async (event) => { let res = new Response('body'); const body = await res.text(); return new Response(body, res); }); routes.set('/proxy-transform-stream/framing', async (event) => { const newUrl = new URL('https://http-me.fastly.dev/anything'); let req = new Request(newUrl, { headers: event.request.headers, body: event.request.body, method: event.request.method, }); req = new Request(req.url, { headers: req.headers, body: req.body, method: req.method, }); req = new Request(req.url, { headers: req.headers, body: req.body, method: req.method, }); const cacheOverride = new CacheOverride('pass'); const res = await fetch(req, { backend: 'httpme', cacheOverride, }); let json = await res.json(); assert(res.status, 200, 'Status should be 200'); assert( json['headers']['content-length'], '11', 'Content-Length header should be 11', ); return new Response('ok'); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/random.js ================================================ /* eslint-env serviceworker */ import { routes } from './routes.js'; import { assert } from './assertions.js'; function random3Decimals() { return String(Math.random()).slice(0, 5); } let a = random3Decimals(); let b = random3Decimals(); // This tests can fail sporadically as it is testing randomness. // If it fails, rerun the tests and it should pass, if it does not // then we may have another bug with how we are seeding the random // number generator in SpiderMonkey. routes.set('/random', () => { assert( a !== b, true, 'The first 4 digits were repeated in sequential calls to Math.random() during wizening\n\n' + JSON.stringify({ a, b }, undefined, 4), ); let c = random3Decimals(); let d = random3Decimals(); assert( c !== d, true, 'The first 4 digits were repeated in sequential calls to Math.random() during request handling\n\n' + JSON.stringify({ c, d }, undefined, 4), ); }); ================================================ FILE: integration-tests/js-compute/fixtures/app/src/react-byob.js ================================================ /* eslint-env serviceworker */ import { routes } from './routes.js'; // React var React = {}; { /** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ let exports = React; let l = Symbol.for('react.element'), n = Symbol.for('react.portal'), p = Symbol.for('react.fragment'), q = Symbol.for('react.strict_mode'), r = Symbol.for('react.profiler'), t = Symbol.for('react.provider'), u = Symbol.for('react.context'), v = Symbol.for('react.forward_ref'), w = Symbol.for('react.suspense'), x = Symbol.for('react.memo'), y = Symbol.for('react.lazy'), z = Symbol.iterator; function A(a) { if (null === a || 'object' !== typeof a) return null; a = (z && a[z]) || a['@@iterator']; return 'function' === typeof a ? a : null; } let B = { isMounted: function () { return !1; }, enqueueForceUpdate: function () {}, enqueueReplaceState: function () {}, enqueueSetState: function () {}, }, C = Object.assign, D = {}; function E(a, b, e) { this.props = a; this.context = b; this.refs = D; this.updater = e || B; } E.prototype.isReactComponent = {}; E.prototype.setState = function (a, b) { if ('object' !== typeof a && 'function' !== typeof a && null != a) throw Error( 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.', ); this.updater.enqueueSetState(this, a, b, 'setState'); }; E.prototype.forceUpdate = function (a) { this.updater.enqueueForceUpdate(this, a, 'forceUpdate'); }; function F() {} F.prototype = E.prototype; function G(a, b, e) { this.props = a; this.context = b; this.refs = D; this.updater = e || B; } var H = (G.prototype = new F()); H.constructor = G; C(H, E.prototype); H.isPureReactComponent = !0; var I = Array.isArray, J = Object.prototype.hasOwnProperty, K = { current: null }, L = { key: !0, ref: !0, __self: !0, __source: !0 }; function M(a, b, e) { var d, c = {}, k = null, h = null; if (null != b) for (d in (void 0 !== b.ref && (h = b.ref), void 0 !== b.key && (k = '' + b.key), b)) J.call(b, d) && !L.hasOwnProperty(d) && (c[d] = b[d]); var g = arguments.length - 2; if (1 === g) c.children = e; else if (1 < g) { for (var f = Array(g), m = 0; m < g; m++) f[m] = arguments[m + 2]; c.children = f; } if (a && a.defaultProps) for (d in ((g = a.defaultProps), g)) void 0 === c[d] && (c[d] = g[d]); return { $$typeof: l, type: a, key: k, ref: h, props: c, _owner: K.current, }; } function N(a, b) { return { $$typeof: l, type: a.type, key: b, ref: a.ref, props: a.props, _owner: a._owner, }; } function O(a) { return 'object' === typeof a && null !== a && a.$$typeof === l; } function escape(a) { var b = { '=': '=0', ':': '=2' }; return ( '$' + a.replace(/[=:]/g, function (a) { return b[a]; }) ); } var P = /\/+/g; function Q(a, b) { return 'object' === typeof a && null !== a && null != a.key ? escape('' + a.key) : b.toString(36); } function R(a, b, e, d, c) { var k = typeof a; if ('undefined' === k || 'boolean' === k) a = null; var h = !1; if (null === a) h = !0; else switch (k) { case 'string': case 'number': h = !0; break; case 'object': switch (a.$$typeof) { case l: case n: h = !0; } } if (h) return ( (h = a), (c = c(h)), (a = '' === d ? '.' + Q(h, 0) : d), I(c) ? ((e = ''), null != a && (e = a.replace(P, '$&/') + '/'), R(c, b, e, '', function (a) { return a; })) : null != c && (O(c) && (c = N( c, e + (!c.key || (h && h.key === c.key) ? '' : ('' + c.key).replace(P, '$&/') + '/') + a, )), b.push(c)), 1 ); h = 0; d = '' === d ? '.' : d + ':'; if (I(a)) for (var g = 0; g < a.length; g++) { k = a[g]; var f = d + Q(k, g); h += R(k, b, e, f, c); } else if (((f = A(a)), 'function' === typeof f)) for (a = f.call(a), g = 0; !(k = a.next()).done; ) (k = k.value), (f = d + Q(k, g++)), (h += R(k, b, e, f, c)); else if ('object' === k) throw ( ((b = String(a)), Error( 'Objects are not valid as a React child (found: ' + ('[object Object]' === b ? 'object with keys {' + Object.keys(a).join(', ') + '}' : b) + '). If you meant to render a collection of children, use an array instead.', )) ); return h; } function S(a, b, e) { if (null == a) return a; var d = [], c = 0; R(a, d, '', '', function (a) { return b.call(e, a, c++); }); return d; } function T(a) { if (-1 === a._status) { var b = a._result; b = b(); b.then( function (b) { if (0 === a._status || -1 === a._status) (a._status = 1), (a._result = b); }, function (b) { if (0 === a._status || -1 === a._status) (a._status = 2), (a._result = b); }, ); -1 === a._status && ((a._status = 0), (a._result = b)); } if (1 === a._status) return a._result.default; throw a._result; } var U = { current: null }, V = { transition: null }, W = { ReactCurrentDispatcher: U, ReactCurrentBatchConfig: V, ReactCurrentOwner: K, }; exports.Children = { map: S, forEach: function (a, b, e) { S( a, function () { b.apply(this, arguments); }, e, ); }, count: function (a) { var b = 0; S(a, function () { b++; }); return b; }, toArray: function (a) { return ( S(a, function (a) { return a; }) || [] ); }, only: function (a) { if (!O(a)) throw Error( 'React.Children.only expected to receive a single React element child.', ); return a; }, }; exports.Component = E; exports.Fragment = p; exports.Profiler = r; exports.PureComponent = G; exports.StrictMode = q; exports.Suspense = w; exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = W; exports.cloneElement = function (a, b, e) { if (null === a || void 0 === a) throw Error( 'React.cloneElement(...): The argument must be a React element, but you passed ' + a + '.', ); var d = C({}, a.props), c = a.key, k = a.ref, h = a._owner; if (null != b) { void 0 !== b.ref && ((k = b.ref), (h = K.current)); void 0 !== b.key && (c = '' + b.key); if (a.type && a.type.defaultProps) var g = a.type.defaultProps; for (f in b) J.call(b, f) && !L.hasOwnProperty(f) && (d[f] = void 0 === b[f] && void 0 !== g ? g[f] : b[f]); } var f = arguments.length - 2; if (1 === f) d.children = e; else if (1 < f) { g = Array(f); for (var m = 0; m < f; m++) g[m] = arguments[m + 2]; d.children = g; } return { $$typeof: l, type: a.type, key: c, ref: k, props: d, _owner: h }; }; exports.createContext = function (a) { a = { $$typeof: u, _currentValue: a, _currentValue2: a, _threadCount: 0, Provider: null, Consumer: null, _defaultValue: null, _globalName: null, }; a.Provider = { $$typeof: t, _context: a }; return (a.Consumer = a); }; exports.createElement = M; exports.createFactory = function (a) { var b = M.bind(null, a); b.type = a; return b; }; exports.createRef = function () { return { current: null }; }; exports.forwardRef = function (a) { return { $$typeof: v, render: a }; }; exports.isValidElement = O; exports.lazy = function (a) { return { $$typeof: y, _payload: { _status: -1, _result: a }, _init: T }; }; exports.memo = function (a, b) { return { $$typeof: x, type: a, compare: void 0 === b ? null : b }; }; exports.startTransition = function (a) { var b = V.transition; V.transition = {}; try { a(); } finally { V.transition = b; } }; exports.unstable_act = function () { throw Error('act(...) is not supported in production builds of React.'); }; exports.useCallback = function (a, b) { return U.current.useCallback(a, b); }; exports.useContext = function (a) { return U.current.useContext(a); }; exports.useDebugValue = function () {}; exports.useDeferredValue = function (a) { return U.current.useDeferredValue(a); }; exports.useEffect = function (a, b) { return U.current.useEffect(a, b); }; exports.useId = function () { return U.current.useId(); }; exports.useImperativeHandle = function (a, b, e) { return U.current.useImperativeHandle(a, b, e); }; exports.useInsertionEffect = function (a, b) { return U.current.useInsertionEffect(a, b); }; exports.useLayoutEffect = function (a, b) { return U.current.useLayoutEffect(a, b); }; exports.useMemo = function (a, b) { return U.current.useMemo(a, b); }; exports.useReducer = function (a, b, e) { return U.current.useReducer(a, b, e); }; exports.useRef = function (a) { return U.current.useRef(a); }; exports.useState = function (a) { return U.current.useState(a); }; exports.useSyncExternalStore = function (a, b, e) { return U.current.useSyncExternalStore(a, b, e); }; exports.useTransition = function () { return U.current.useTransition(); }; exports.version = '18.2.0'; } // react/jsx-runtime let jsx, jsxs; { /** * @license React * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ let k = Symbol.for('react.element'), m = Object.prototype.hasOwnProperty, n = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .ReactCurrentOwner, p = { key: !0, ref: !0, __self: !0, __source: !0 }; function q(c, a, g) { var b, d = {}, e = null, h = null; void 0 !== g && (e = '' + g); void 0 !== a.key && (e = '' + a.key); void 0 !== a.ref && (h = a.ref); for (b in a) m.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); if (c && c.defaultProps) for (b in ((a = c.defaultProps), a)) void 0 === d[b] && (d[b] = a[b]); return { $$typeof: k, type: c, key: e, ref: h, props: d, _owner: n.current, }; } jsx = jsxs = q; } // react-dom/server let renderToReadableStream; { /** * @license React * react-dom-server.browser.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var aa = React; function k(a) { for ( var b = 'https://reactjs.org/docs/error-decoder.html?invariant=' + a, c = 1; c < arguments.length; c++ ) b += '&args[]=' + encodeURIComponent(arguments[c]); return ( 'Minified React error #' + a + '; visit ' + b + ' for the full message or use the non-minified dev environment for full errors and additional helpful warnings.' ); } var l = null, n = 0; function p(a, b) { if (0 !== b.length) if (512 < b.length) 0 < n && (a.enqueue(new Uint8Array(l.buffer, 0, n)), (l = new Uint8Array(512)), (n = 0)), a.enqueue(b); else { var c = l.length - n; c < b.length && (0 === c ? a.enqueue(l) : (l.set(b.subarray(0, c), n), a.enqueue(l), (b = b.subarray(c))), (l = new Uint8Array(512)), (n = 0)); l.set(b, n); n += b.length; } } function t(a, b) { p(a, b); return !0; } function ba(a) { l && 0 < n && (a.enqueue(new Uint8Array(l.buffer, 0, n)), (l = null), (n = 0)); } var ca = new TextEncoder(); function u(a) { return ca.encode(a); } function w(a) { return ca.encode(a); } function da(a, b) { 'function' === typeof a.error ? a.error(b) : a.close(); } var x = Object.prototype.hasOwnProperty, ea = /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, fa = {}, ha = {}; function ia(a) { if (x.call(ha, a)) return !0; if (x.call(fa, a)) return !1; if (ea.test(a)) return (ha[a] = !0); fa[a] = !0; return !1; } function y(a, b, c, d, f, e, g) { this.acceptsBooleans = 2 === b || 3 === b || 4 === b; this.attributeName = d; this.attributeNamespace = f; this.mustUseProperty = c; this.propertyName = a; this.type = b; this.sanitizeURL = e; this.removeEmptyString = g; } var z = {}; 'children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style' .split(' ') .forEach(function (a) { z[a] = new y(a, 0, !1, a, null, !1, !1); }); [ ['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv'], ].forEach(function (a) { var b = a[0]; z[b] = new y(b, 1, !1, a[1], null, !1, !1); }); ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (a) { z[a] = new y(a, 2, !1, a.toLowerCase(), null, !1, !1); }); [ 'autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha', ].forEach(function (a) { z[a] = new y(a, 2, !1, a, null, !1, !1); }); 'allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope' .split(' ') .forEach(function (a) { z[a] = new y(a, 3, !1, a.toLowerCase(), null, !1, !1); }); ['checked', 'multiple', 'muted', 'selected'].forEach(function (a) { z[a] = new y(a, 3, !0, a, null, !1, !1); }); ['capture', 'download'].forEach(function (a) { z[a] = new y(a, 4, !1, a, null, !1, !1); }); ['cols', 'rows', 'size', 'span'].forEach(function (a) { z[a] = new y(a, 6, !1, a, null, !1, !1); }); ['rowSpan', 'start'].forEach(function (a) { z[a] = new y(a, 5, !1, a.toLowerCase(), null, !1, !1); }); var ja = /[\-:]([a-z])/g; function ka(a) { return a[1].toUpperCase(); } 'accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height' .split(' ') .forEach(function (a) { var b = a.replace(ja, ka); z[b] = new y(b, 1, !1, a, null, !1, !1); }); 'xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type' .split(' ') .forEach(function (a) { var b = a.replace(ja, ka); z[b] = new y(b, 1, !1, a, 'http://www.w3.org/1999/xlink', !1, !1); }); ['xml:base', 'xml:lang', 'xml:space'].forEach(function (a) { var b = a.replace(ja, ka); z[b] = new y(b, 1, !1, a, 'http://www.w3.org/XML/1998/namespace', !1, !1); }); ['tabIndex', 'crossOrigin'].forEach(function (a) { z[a] = new y(a, 1, !1, a.toLowerCase(), null, !1, !1); }); z.xlinkHref = new y( 'xlinkHref', 1, !1, 'xlink:href', 'http://www.w3.org/1999/xlink', !0, !1, ); ['src', 'href', 'action', 'formAction'].forEach(function (a) { z[a] = new y(a, 1, !1, a.toLowerCase(), null, !0, !0); }); var B = { animationIterationCount: !0, aspectRatio: !0, borderImageOutset: !0, borderImageSlice: !0, borderImageWidth: !0, boxFlex: !0, boxFlexGroup: !0, boxOrdinalGroup: !0, columnCount: !0, columns: !0, flex: !0, flexGrow: !0, flexPositive: !0, flexShrink: !0, flexNegative: !0, flexOrder: !0, gridArea: !0, gridRow: !0, gridRowEnd: !0, gridRowSpan: !0, gridRowStart: !0, gridColumn: !0, gridColumnEnd: !0, gridColumnSpan: !0, gridColumnStart: !0, fontWeight: !0, lineClamp: !0, lineHeight: !0, opacity: !0, order: !0, orphans: !0, tabSize: !0, widows: !0, zIndex: !0, zoom: !0, fillOpacity: !0, floodOpacity: !0, stopOpacity: !0, strokeDasharray: !0, strokeDashoffset: !0, strokeMiterlimit: !0, strokeOpacity: !0, strokeWidth: !0, }, la = ['Webkit', 'ms', 'Moz', 'O']; Object.keys(B).forEach(function (a) { la.forEach(function (b) { b = b + a.charAt(0).toUpperCase() + a.substring(1); B[b] = B[a]; }); }); var oa = /["'&<>]/; function C(a) { if ('boolean' === typeof a || 'number' === typeof a) return '' + a; a = '' + a; var b = oa.exec(a); if (b) { var c = '', d, f = 0; for (d = b.index; d < a.length; d++) { switch (a.charCodeAt(d)) { case 34: b = '"'; break; case 38: b = '&'; break; case 39: b = '''; break; case 60: b = '<'; break; case 62: b = '>'; break; default: continue; } f !== d && (c += a.substring(f, d)); f = d + 1; c += b; } a = f !== d ? c + a.substring(f, d) : c; } return a; } var pa = /([A-Z])/g, qa = /^ms-/, ra = Array.isArray, sa = w('" ] } }, "POST /tee": { "downstream_request": { "method": "POST", "pathname": "/tee", "headers": ["Content-Type", "application/json"], "body": "hello world!" } }, "GET /tee/error": { "downstream_request": { "method": "GET", "pathname": "/tee/error", "headers": ["Content-Type", "application/json"] }, "downstream_response": { "status": 200, "body": "Error: TypeError" } }, "GET /override-content-length/request/init/object-literal/true": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /override-content-length/request/init/object-literal/false": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /override-content-length/request/clone/true": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /override-content-length/request/clone/false": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /override-content-length/fetch/init/object-literal/true": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /override-content-length/fetch/init/object-literal/false": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "ok" } }, "/override-content-length/response/clone/true": { "skip": true, "environments": ["compute"] }, "/override-content-length/response/clone/false": { "skip": true, "environments": ["compute"] }, "GET /override-content-length/response/init/object-literal/true": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "meow", "headers": { "content-length": "4" } } }, "GET /override-content-length/response/init/object-literal/false": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "meow" } }, "GET /override-content-length/response/init/response-instance/true": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "meow", "headers": { "content-length": "4" } } }, "GET /override-content-length/response/init/response-instance/false": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "meow" } }, "GET /override-content-length/response/method/false": { "environments": ["compute"] }, "GET /override-content-length/response/method/true": { "environments": ["compute"], "downstream_response": { "status": 200, "headers": { "content-length": "11" } } }, "GET /headers/getsetcookie": { "downstream_response": { "status": 200, "headers": [["name1=value1"], ["name2=value2"]] } }, "GET /headers/construct": { "downstream_response": { "status": 200, "headers": { "foo": "bar" } } }, "GET /headers/from-response/set": { "flake": true, "downstream_response": { "status": 200, "headers": [["cuStom", "test"]] } }, "GET /headers/from-response/delete-invalid": { "flake": true }, "GET /headers/from-response/set-delete": { "flake": true, "downstream_response": { "status": 200, "headers": [["cuStom", "test"]] } }, "GET /FastlyBody/interface": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/constructor/called-as-regular-function": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/constructor/called-as-constructor": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/called-as-constructor": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-not-supplied": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-wrong-type": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-readablestream-guest-backed": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-readablestream-host-backed": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-URLSearchParams": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-strings": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-calls-7.1.17-ToString": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-buffer": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-arraybuffer": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-typed-arrays": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/append/data-parameter-dataview": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/called-as-constructor": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-not-supplied": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-wrong-type": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-readablestream-guest-backed": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-readablestream-host-backed": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-readablestream-locked": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-URLSearchParams": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-strings": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-calls-7.1.17-ToString": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-buffer": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-arraybuffer": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-typed-arrays": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/prepend/data-parameter-dataview": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/concat/called-as-constructor": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/concat/dest-parameter-not-supplied": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/concat/dest-parameter-wrong-type": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/concat/concat-same-fastlybody-twice": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/concat/happy-path": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/read/called-as-constructor": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/read/chunkSize-parameter-not-supplied": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/read/chunkSize-parameter-wrong-type": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/read/chunkSize-parameter-negative": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/read/chunkSize-parameter-infinity": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/read/chunkSize-parameter-NaN": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/read/happy-path": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/close/called-as-constructor": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/close/called-once": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /FastlyBody/close/called-twice": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/interface": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/constructor/called-as-regular-function": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/constructor/throws": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/lookup/called-as-constructor": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/lookup/key-parameter-calls-7.1.17-ToString": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/lookup/key-parameter-not-supplied": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/lookup/key-parameter-empty-string": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/lookup/key-parameter-8135-character-string": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/lookup/key-parameter-8136-character-string": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/lookup/key-does-not-exist-returns-null": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/lookup/key-exists": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/lookup/options-parameter-wrong-type": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /core-cache/lookup/options-parameter-none": { "environments": ["compute"] }, "GET /core-cache/lookup/options-parameter-headers-field-wrong-type": { "environments": ["compute"] }, "GET /core-cache/lookup/options-parameter-headers-field-undefined": { "flake": true, "environments": ["compute"] }, "GET /core-cache/lookup/options-parameter-headers-field-valid-sequence": { "flake": true, "environments": ["compute"] }, "GET /core-cache/lookup/options-parameter-headers-field-valid-record": { "flake": true, "environments": ["compute"] }, "GET /core-cache/lookup/options-parameter-headers-field-valid-Headers-instance": { "flake": true, "environments": ["compute"] }, "GET /core-cache/insert/called-as-constructor": { "environments": ["compute"] }, "GET /core-cache/insert/key-parameter-calls-7.1.17-ToString": { "environments": ["compute"] }, "GET /core-cache/insert/key-parameter-not-supplied": { "environments": ["compute"] }, "GET /core-cache/insert/key-parameter-empty-string": { "environments": ["compute"] }, "GET /core-cache/insert/key-parameter-8135-character-string": { "environments": ["compute"] }, "GET /core-cache/insert/key-parameter-8136-character-string": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-wrong-type": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-headers-field-wrong-type": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-headers-field-undefined": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-headers-field-valid-sequence": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-headers-field-valid-record": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-headers-field-valid-Headers-instance": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-maxAge-field-valid-record": { "flake": true, "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-maxAge-field-NaN": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-maxAge-field-postitive-infinity": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-maxAge-field-negative-infinity": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-maxAge-field-negative-number": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-maxAge-field-too-large": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-initialAge-field-valid-record": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-initialAge-field-NaN": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-initialAge-field-postitive-infinity": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-initialAge-field-negative-infinity": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-initialAge-field-negative-number": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-initialAge-field-too-large": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-staleWhileRevalidate-field-valid-record": { "flake": true, "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-staleWhileRevalidate-field-NaN": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-staleWhileRevalidate-field-postitive-infinity": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-staleWhileRevalidate-field-negative-infinity": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-staleWhileRevalidate-field-negative-number": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-staleWhileRevalidate-field-too-large": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-length-field-valid-record": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-length-field-NaN": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-length-field-postitive-infinity": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-length-field-negative-infinity": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-length-field-negative-number": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-sensitive-field": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-vary-field": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-userMetadata-field/arraybuffer/empty": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-userMetadata-field/arraybuffer/not-empty": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-userMetadata-field/URLSearchParams": { "environments": ["compute"] }, "GET /core-cache/insert/options-parameter-userMetadata-field/string": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/called-as-constructor": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/key-parameter-calls-7.1.17-ToString": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/key-parameter-not-supplied": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/key-parameter-empty-string": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/key-parameter-8135-character-string": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/key-parameter-8136-character-string": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/key-does-not-exist": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/key-exists": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/options-parameter-wrong-type": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/options-parameter-headers-field-wrong-type": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/options-parameter-headers-field-undefined": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/options-parameter-headers-field-valid-sequence": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/options-parameter-headers-field-valid-record": { "environments": ["compute"] }, "GET /core-cache/transactionLookup/options-parameter-headers-field-valid-Headers-instance": { "environments": ["compute"] }, "GET /cache-entry/interface": { "environments": ["compute"] }, "GET /cache-entry/constructor/called-as-regular-function": { "environments": ["compute"] }, "GET /cache-entry/constructor/throws": { "environments": ["compute"] }, "GET /cache-entry/close/called-as-constructor": { "environments": ["compute"] }, "GET /cache-entry/close/called-unbound": { "environments": ["compute"] }, "GET /cache-entry/close/called-on-instance": { "environments": ["compute"] }, "GET /cache-entry/state/called-as-constructor": { "environments": ["compute"] }, "GET /cache-entry/state/called-unbound": { "environments": ["compute"] }, "GET /cache-entry/state/called-on-instance": { "environments": ["compute"] }, "GET /cache-entry/userMetadata/called-as-constructor": { "environments": ["compute"] }, "GET /cache-entry/userMetadata/called-unbound": { "environments": ["compute"] }, "GET /cache-entry/userMetadata/called-on-instance": { "environments": ["compute"] }, "GET /cache-entry/userMetadata/basic": { "environments": ["compute"] }, "GET /cache-entry/body/called-as-constructor": { "environments": ["compute"] }, "GET /cache-entry/body/called-unbound": { "environments": ["compute"] }, "GET /cache-entry/body/called-on-instance": { "environments": ["compute"] }, "GET /cache-entry/body/options-start-negative": { "environments": ["compute"] }, "GET /cache-entry/body/options-start-NaN": { "environments": ["compute"] }, "GET /cache-entry/body/options-start-Infinity": { "environments": ["compute"] }, "GET /cache-entry/body/options-start-valid": { "environments": ["compute"] }, "GET /cache-entry/body/options-start-longer-than-body": { "environments": ["compute"] }, "GET /cache-entry/body/options-end-negative": { "environments": ["compute"] }, "GET /cache-entry/body/options-end-NaN": { "environments": ["compute"] }, "GET /cache-entry/body/options-end-Infinity": { "environments": ["compute"] }, "GET /cache-entry/body/options-end-valid": { "environments": ["compute"] }, "GET /cache-entry/body/options-end-zero": { "environments": ["compute"] }, "GET /cache-entry/length/called-as-constructor": { "environments": ["compute"] }, "GET /cache-entry/length/called-unbound": { "environments": ["compute"] }, "GET /cache-entry/length/called-on-instance": { "environments": ["compute"] }, "GET /cache-entry/maxAge/called-as-constructor": { "environments": ["compute"] }, "GET /cache-entry/maxAge/called-unbound": { "environments": ["compute"] }, "GET /cache-entry/maxAge/called-on-instance": { "environments": ["compute"] }, "GET /cache-entry/staleWhileRevalidate/called-as-constructor": { "environments": ["compute"] }, "GET /cache-entry/staleWhileRevalidate/called-unbound": { "environments": ["compute"] }, "GET /cache-entry/staleWhileRevalidate/called-on-instance": { "environments": ["compute"] }, "GET /cache-entry/age/called-as-constructor": { "environments": ["compute"] }, "GET /cache-entry/age/called-unbound": { "environments": ["compute"] }, "GET /cache-entry/age/called-on-instance": { "environments": ["compute"] }, "GET /cache-entry/hits/called-as-constructor": { "environments": ["compute"] }, "GET /cache-entry/hits/called-unbound": { "environments": ["compute"] }, "GET /cache-entry/hits/called-on-instance": { "environments": ["compute"] }, "GET /transaction-cache-entry/interface": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/called-as-constructor": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/entry-parameter-not-supplied": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-maxAge-field-valid-record": { "flake": true, "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-maxAge-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-maxAge-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-maxAge-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-maxAge-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-maxAge-field-too-large": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-initialAge-field-valid-record": { "flake": true, "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-initialAge-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-initialAge-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-initialAge-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-initialAge-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-initialAge-field-too-large": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-valid-record": { "flake": true, "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-staleWhileRevalidate-field-too-large": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-length-field-valid-record": { "flake": true, "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-length-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-length-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-length-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-length-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-sensitive-field": { "flake": true, "environments": ["compute"] }, "GET /transaction-cache-entry/insert/options-parameter-vary-field": { "flake": true, "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/called-as-constructor": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/entry-parameter-not-supplied": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-valid-record": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-maxAge-field-too-large": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-valid-record": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-initialAge-field-too-large": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-valid-record": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-staleWhileRevalidate-field-too-large": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-length-field-valid-record": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-length-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-length-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-length-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-length-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-sensitive-field": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/write-to-writer-and-read-from-reader": { "environments": ["compute"] }, "GET /transaction-cache-entry/insertAndStreamBack/options-parameter-vary-field": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/called-as-constructor": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/entry-parameter-not-supplied": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-maxAge-field-valid-record": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-maxAge-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-maxAge-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-maxAge-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-maxAge-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-maxAge-field-too-large": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-initialAge-field-valid-record": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-initialAge-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-initialAge-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-initialAge-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-initialAge-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-initialAge-field-too-large": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-valid-record": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-staleWhileRevalidate-field-too-large": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-length-field-valid-record": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-length-field-NaN": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-length-field-postitive-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-length-field-negative-infinity": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-length-field-negative-number": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/write-to-writer-and-read-from-reader": { "flake": true, "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-vary-field": { "environments": ["compute"] }, "GET /transaction-cache-entry/update/options-parameter-userMetadata-field": { "environments": ["compute"] }, "GET /transaction-cache-entry/cancel/called-as-constructor": { "environments": ["compute"] }, "GET /transaction-cache-entry/cancel/called-once": { "environments": ["compute"] }, "GET /transaction-cache-entry/cancel/makes-entry-cancelled": { "environments": ["compute"] }, "GET /transaction-cache-entry/cancel/called-twice-throws": { "environments": ["compute"] }, "GET /rate-counter/interface": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/constructor/called-as-regular-function": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/constructor/called-as-constructor-no-arguments": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/constructor/name-parameter-calls-7.1.17-ToString": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/constructor/happy-path": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/increment/called-as-constructor": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/increment/entry-parameter-calls-7.1.17-ToString": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/increment/entry-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/increment/delta-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/increment/delta-parameter-negative": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/increment/delta-parameter-infinity": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/increment/delta-parameter-NaN": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/increment/returns-undefined": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupRate/called-as-constructor": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupRate/entry-parameter-calls-7.1.17-ToString": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupRate/entry-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupRate/window-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupRate/window-parameter-negative": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupRate/window-parameter-infinity": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupRate/window-parameter-NaN": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupRate/returns-number": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupCount/called-as-constructor": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupCount/entry-parameter-calls-7.1.17-ToString": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupCount/entry-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupCount/duration-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupCount/duration-parameter-negative": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupCount/duration-parameter-infinity": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupCount/duration-parameter-NaN": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /rate-counter/lookupCount/returns-number": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/interface": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/constructor/called-as-regular-function": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/constructor/called-as-constructor-no-arguments": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/constructor/name-parameter-calls-7.1.17-ToString": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/constructor/happy-path": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/has/called-as-constructor": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/has/entry-parameter-calls-7.1.17-ToString": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/has/entry-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/has/returns-boolean": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/add/called-as-constructor": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/add/entry-parameter-calls-7.1.17-ToString": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/add/entry-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/add/timeToLive-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/add/timeToLive-parameter-negative": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/add/timeToLive-parameter-infinity": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/add/timeToLive-parameter-NaN": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /penalty-box/add/returns-undefined": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/interface": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/constructor/called-as-regular-function": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/constructor/called-as-constructor-no-arguments": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/constructor/rate-counter-not-instance-of-rateCounter": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/constructor/penalty-box-not-instance-of-penaltyBox": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/constructor/happy-path": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/called-as-constructor": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/entry-parameter-calls-7.1.17-ToString": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/entry-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/delta-parameter-negative": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/delta-parameter-infinity": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/delta-parameter-NaN": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/window-parameter-negative": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/window-parameter-infinity": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/window-parameter-NaN": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/limit-parameter-negative": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/limit-parameter-infinity": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/limit-parameter-NaN": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/timeToLive-parameter-negative": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/timeToLive-parameter-infinity": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/timeToLive-parameter-NaN": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /edge-rate-limiter/checkRate/returns-boolean": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/interface": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/constructor/called-as-regular-function": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/constructor/throws": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/lookup/called-as-constructor": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/lookup/useragent-parameter-calls-7.1.17-ToString": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/lookup/useragent-parameter-not-supplied": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/lookup/useragent-parameter-empty-string": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/lookup/useragent-does-not-exist-returns-null": { "environments": ["viceroy"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/lookup/useragent-exists-all-fields-identified": { "environments": ["viceroy"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/lookup/useragent-exists-all-fields-identified-tojson": { "environments": ["viceroy"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/lookup/useragent-exists-some-fields-identified": { "environments": ["viceroy"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /device/lookup/bot-detection": { "environments": ["viceroy"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /server/address": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /core-cache/transaction-lookup-transaction-insert-vary-works": { "flake": true, "environments": ["compute"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /core-cache/lookup-insert-vary-works": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "GET"]] } }, "get /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "GET"]] } }, "GeT /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "GET"]] } }, "HEAD /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "HEAD"]] } }, "head /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "HEAD"]] } }, "HeAd /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "HEAD"]] } }, "OPTIONS /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "OPTIONS"]] } }, "OPTioNS /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "OPTIONS"]] } }, "options /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "OPTIONS"]] } }, "POST /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "POST"]] } }, "post /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "POST"]] } }, "PosT /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "POST"]] } }, "PUT /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "PUT"]] } }, "put /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "PUT"]] } }, "Put /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "PUT"]] } }, "DELETE /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "DELETE"]] } }, "DeLeTe /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "DELETE"]] } }, "delete /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "DELETE"]] } }, "HELLO /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "HELLO"]] } }, "hello /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "hello"]] } }, "heLLo /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [["result", "heLLo"]] } }, "!*+-.^_`|~1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ /request/method/host": { "downstream_response": { "status": 200, "body": "", "headers": [ [ "result", "!*+-.^_`|~1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ] ] } }, "GET /request/method/guest": { "downstream_response": { "status": 200, "body": "ok" } }, "GET /compute/get-vcpu-ms": { "flake": true, "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /compute/purge-surrogate-key-invalid": {}, "GET /compute/purge-surrogate-key-hard": { "environments": ["compute"] }, "GET /compute/purge-surrogate-key-soft": { "environments": ["compute"] }, "GET /html-rewriter/set-attribute": {}, "GET /html-rewriter/get-attribute": {}, "GET /html-rewriter/remove-attribute": {}, "GET /html-rewriter/replace-with": {}, "GET /html-rewriter/replace-children": {}, "GET /html-rewriter/insert": {}, "GET /html-rewriter/complex-selector": {}, "GET /html-rewriter/no-match-rewritten-content": {}, "GET /html-rewriter/multiple-handlers": {}, "GET /html-rewriter/invalid-selector": {}, "GET /html-rewriter/invalid-handler": {}, "GET /html-rewriter/throw-in-handler": {}, "GET /html-rewriter/invalid-html": {}, "GET /html-rewriter/insertion-order": {}, "GET /html-rewriter/escape-html": {}, "GET /image-optimizer/options/region": {}, "GET /image-optimizer/options/auto": {}, "GET /image-optimizer/options/bw": {}, "GET /image-optimizer/options/crop-mode": {}, "GET /image-optimizer/options/disable": {}, "GET /image-optimizer/options/enable": {}, "GET /image-optimizer/options/fit": {}, "GET /image-optimizer/options/metadata": {}, "GET /image-optimizer/options/optimize": {}, "GET /image-optimizer/options/orient": {}, "GET /image-optimizer/options/profile": {}, "GET /image-optimizer/options/resizeFilter": {}, "GET /image-optimizer/options/bgColor": {}, "GET /image-optimizer/options/blur": {}, "GET /image-optimizer/options/brightness": {}, "GET /image-optimizer/options/canvas": {}, "GET /image-optimizer/options/crop": {}, "GET /image-optimizer/options/precrop": {}, "GET /image-optimizer/options/dpr": {}, "GET /image-optimizer/options/frame": {}, "GET /image-optimizer/options/height": {}, "GET /image-optimizer/options/level": {}, "GET /image-optimizer/options/pad": {}, "GET /image-optimizer/options/quality": {}, "GET /image-optimizer/options/saturation": {}, "GET /image-optimizer/options/sharpen": {}, "GET /image-optimizer/options/trim": {}, "GET /image-optimizer/options/viewbox": {}, "GET /early-hints/manual-response": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 }, "downstream_info": { "status": 103, "headers": { "link": "; rel=preload; as=style" } } }, "GET /early-hints/manual-response-late": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /early-hints/manual-response-async": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 }, "downstream_info": { "status": 103, "headers": { "link": "; rel=preload; as=style" } } }, "GET /early-hints/manual-response-late-async": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /early-hints/send-early-hints": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 }, "downstream_info": { "status": 103, "headers": { "link": "; rel=preload; as=style" } } }, "GET /early-hints/send-early-hints-late": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /early-hints/send-early-hints-multiple-headers": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 }, "downstream_info": { "status": 103, "headers": [ ["link", "; rel=preload; as=style"], ["link", "; rel=preload; as=style"] ] } }, "GET /early-hints/send-early-hints-async": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 }, "downstream_info": { "status": 103, "headers": { "link": "; rel=preload; as=style" } } }, "GET /early-hints/send-early-hints-late-async": { "environments": ["compute"], "downstream_response": { "body": "ok", "status": 200 } }, "GET /shielding/invalid-shield": { "environments": ["compute"] }, "GET /fastly/security/inspect/invalid-config": { "environments": ["viceroy"] }, "GET /fastly/security/inspect/basic": { "environments": ["viceroy"] }, "POST /proxy-transform-stream/content-length": { "downstream_response": { "status": 200, "body": "ok" }, "downstream_request": { "method": "POST", "pathname": "/proxy-transform-stream/content-length", "body": "hello world" } }, "POST /proxy-transform-stream/simple-response-body-chain": { "downstream_response": { "status": 200, "body": "body", "headers": [["content-length", "4"]] }, "downstream_request": { "method": "POST", "pathname": "/proxy-transform-stream/simple-response-body-chain", "body": "body" } }, "POST /proxy-transform-stream/multi-response-body-chain": { "downstream_response": { "status": 200, "body": "body", "headers": [["content-length", "4"]] }, "downstream_request": { "method": "POST", "pathname": "/proxy-transform-stream/multi-response-body-chain", "body": "body" } }, "POST /proxy-transform-stream/response-body-into-js": { "downstream_response": { "status": 200, "body": "body", "headers": [["content-length", "4"]] }, "downstream_request": { "method": "POST", "pathname": "/proxy-transform-stream/response-body-into-js", "body": "body" } }, "POST /proxy-transform-stream/framing": { "downstream_response": { "status": 200, "body": "ok" }, "downstream_request": { "method": "POST", "pathname": "/proxy-transform-stream/framing", "body": "hello world" } } } ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/.eslintrc.cjs ================================================ module.exports = { env: { es2021: true, }, extends: 'eslint:recommended', overrides: [], parserOptions: { ecmaVersion: 'latest', sourceType: 'module', }, rules: {}, }; ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/fastly.toml.in ================================================ # This file describes a Fastly Compute package. To learn more visit: # https://developer.fastly.com/reference/fastly-toml/ authors = ["jchampion@fastly.com"] description = "" language = "other" manifest_version = 2 name = "js-test-app" service_id = "" [scripts] build = "node ../../../../dist/cli/js-compute-runtime-cli.js --env FASTLY_DEBUG_LOGGING,ACL_NAME,CONFIG_STORE_NAME,DICTIONARY_NAME,KV_STORE_NAME,SECRET_STORE_NAME,LOCAL_TEST,TEST=\"foo\" --enable-experimental-high-resolution-time-methods --module-mode src/index.js" [local_server] [local_server.backends] [local_server.backends.TheOrigin] url = "https://compute-sdk-test-backend.edgecompute.app" override_host = "compute-sdk-test-backend.edgecompute.app" [local_server.backends.TheOrigin2] url = "https://compute-sdk-test-backend.edgecompute.app" override_host = "compute-sdk-test-backend.edgecompute.app" [local_server.backends.httpme] url = "https://http-me.fastly.dev" override_host = "http-me.fastly.dev" [local_server.config_stores] [local_server.config_stores.CONFIG_STORE_NAME] format = "inline-toml" [local_server.config_stores.CONFIG_STORE_NAME.contents] "twitter" = "https://twitter.com/fastly" [local_server.config_stores."DICTIONARY_NAME"] format = "inline-toml" [local_server.config_stores."DICTIONARY_NAME".contents] "twitter" = "https://twitter.com/fastly" [local_server.geolocation] format = "inline-toml" [local_server.geolocation.addresses] [local_server.geolocation.addresses."2.216.196.179"] as_name = "sky uk limited" as_number = 5607 area_code = 0 city = "bircotes" conn_speed = "broadband" conn_type = "wifi" continent = "EU" country_code = "GB" country_code3 = "GBR" country_name = "united kingdom" gmt_offset = 0 latitude = 53.42 longitude = -1.05 metro_code = 826039 postal_code = "dn11 8af" proxy_description = "?" proxy_type = "?" region = "NTT" utc_offset = 0 [local_server.geolocation.addresses."2607:f0d0:1002:51::4"] as_name = "softlayer technologies inc." as_number = 36351 area_code = 214 city = "dallas" conn_speed = "broadband" conn_type = "wired" continent = "NA" country_code = "US" country_code3 = "USA" country_name = "united states" gmt_offset = -600 latitude = 32.94 longitude = -96.84 metro_code = 623 postal_code = "75244" proxy_description = "?" proxy_type = "hosting" region = "TX" utc_offset = -600 [local_server.kv_stores] [[local_server.kv_stores.KV_STORE_NAME]] key = "placeholder" data = 'placholder' [local_server.secret_stores] [[local_server.secret_stores.SECRET_STORE_NAME]] key = "first" data = "This is also some secret data" [[local_server.secret_stores.SECRET_STORE_NAME]] key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" data = "This is some secret data" [local_server.device_detection] format = "inline-toml" [local_server.device_detection.user_agents] [local_server.device_detection.user_agents."Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 FBAN/FBIOS;FBAV/8.0.0.28.18;FBBV/1665515;FBDV/iPhone4,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/7.0.4;FBSS/2; FBCR/Telekom.de;FBID/phone;FBLC/de_DE;FBOP/5"] user_agent = {} os = {} device = {name = "iPhone", brand = "Apple", model = "iPhone4,1", hwtype = "Mobile Phone", is_ereader = false, is_gameconsole = false, is_mediaplayer = false, is_mobile = true, is_smarttv = false, is_tablet = false, is_tvplayer = false, is_desktop = false, is_touchscreen = true } [local_server.device_detection.user_agents."ghosts-app/1.0.2.1 (ASUSTeK COMPUTER INC.; X550CC; Windows 8 (X86); en)"] user_agent = {} os = {} device = {name = "Asus TeK", brand = "Asus", model = "TeK", is_desktop = false } [setup] [setup.backends] [setup.backends.httpme] address = "http-me.fastly.dev" port = 443 [setup.backends.TheOrigin] address = "compute-sdk-test-backend.edgecompute.app" port = 443 [setup.backends.TheOrigin2] address = "compute-sdk-test-backend.edgecompute.app" port = 443 ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/acl.js ================================================ /// import { strictEqual, assertThrows, assertRejects, deepStrictEqual, } from './assertions.js'; import { routes } from './routes.js'; import { env } from 'fastly:env'; import { Acl } from 'fastly:acl'; const ACL_NAME = env('ACL_NAME'); routes.set('/acl', async () => { assertThrows( () => Acl(), TypeError, "Acl builtin can't be instantiated directly", ); assertThrows( () => new Acl(), TypeError, "Acl builtin can't be instantiated directly", ); assertThrows( () => Acl.open(), TypeError, 'Acl open: At least 1 argument required, but only 0 passed', ); assertThrows(() => Acl.open(4), TypeError, 'Acl open: name must be a string'); assertThrows( () => Acl.open(''), TypeError, 'Acl open: name can not be an empty string', ); assertThrows( () => Acl.open('foo'), TypeError, 'Acl open: "foo" acl not found', ); const acl = Acl.open(ACL_NAME); await assertRejects( () => acl.lookup(), TypeError, 'lookup: At least 1 argument required, but only 0 passed', ); await assertRejects( () => acl.lookup(5), Error, 'Invalid address passed to acl.lookup', ); await assertRejects( () => acl.lookup('not ip'), Error, 'Invalid address passed to acl.lookup', ); await assertRejects( () => acl.lookup('999.999.999.999'), Error, 'Invalid address passed to acl.lookup', ); await assertRejects( () => acl.lookup('123.123.123'), Error, 'Invalid address passed to acl.lookup', ); await assertRejects( () => acl.lookup('123.123.123.123.123'), Error, 'Invalid address passed to acl.lookup', ); await assertRejects( () => acl.lookup('100.100.0.0/16'), Error, 'Invalid address passed to acl.lookup', ); strictEqual(await acl.lookup('123.123.123.123'), null); strictEqual(await acl.lookup('100.99.100.100'), null); strictEqual( await acl.lookup('2a04:4b80:1234:5678:9abc:def0:1234:5678'), null, ); deepStrictEqual(await acl.lookup('100.100.100.100'), { action: 'BLOCK', prefix: '100.100.0.0/16', }); deepStrictEqual(await acl.lookup('2a03:4b80::1'), { action: 'ALLOW', prefix: '2a03:4b80:0000:0000:0000:0000:0000:0000/32', }); deepStrictEqual(await acl.lookup('2a03:4b80:5c1d:e8f7:92a3:b45c:61d8:7e9f'), { action: 'ALLOW', prefix: '2a03:4b80:0000:0000:0000:0000:0000:0000/32', }); }); ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/assertions.js ================================================ export function strictEqual(actual, expected, message) { if (actual !== expected) { throw new Error( `Expected \`${JSON.stringify(actual)}\` to equal \`${JSON.stringify(expected)}\`${message ? '\n' + message : ''}`, ); } } export function assert(truthy, maybeMessage) { if (!truthy) { throw new Error(`Assertion failed: ${maybeMessage}`); } } export { assert as ok }; export async function assertResolves(func) { try { await func(); } catch (error) { throw new Error( `Expected \`${func.toString()}\` to resolve - Found it rejected: ${error.name}: ${error.message}`, ); } } export async function assertRejects(func, errorClass, errorMessage) { try { await func(); } catch (error) { if (errorClass) { if (error instanceof errorClass === false) { throw new Error( `Expected \`${func.toString()}\` to reject instance of \`${errorClass.name}\` - Found instance of \`${error.name}\``, ); } } if (errorMessage) { if (error.message !== errorMessage) { throw new Error( `Expected \`${func.toString()}\` to reject error message of \`${errorMessage}\` - Found \`${error.message}\``, ); } } return; } throw new Error( `Expected \`${func.toString()}\` to reject - Found it did not reject`, ); } export function assertThrows(func, errorClass, errorMessage) { try { func(); } catch (error) { if (errorClass) { if (error instanceof errorClass === false) { throw new Error( `Expected \`${func.toString()}\` to throw instance of \`${errorClass.name}\` - Found instance of \`${error.name}\`: ${error.message}\n${error.stack}`, ); } } if (errorMessage) { if (error.message !== errorMessage) { throw new Error( `Expected \`${func.toString()}\` to throw error message of \`${errorMessage}\` - Found \`${error.message}\``, ); } } return; } throw new Error( `Expected \`${func.toString()}\` to throw - Found it did not throw`, ); } export function assertDoesNotThrow(func) { try { func(); } catch (error) { throw new Error( `Expected \`${func.toString()}\` to not throw - Found it did throw: ${error.name}: ${error.message}`, ); } } export function deepStrictEqual(a, b) { if (!deepEqual(a, b)) { throw new Error( `Expected ${a} to equal ${b}, got ${JSON.stringify(a, null, 2)}`, ); } } export function deepEqual(a, b) { var aKeys; var bKeys; var typeA; var typeB; var key; var i; typeA = typeof a; typeB = typeof b; if (a === null || typeA !== 'object') { if (b === null || typeB !== 'object') { return a === b; } return false; } // Case: `a` is of type 'object' if (b === null || typeB !== 'object') { return false; } if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) { return false; } if (a instanceof Date) { return a.getTime() === b.getTime(); } if (a instanceof RegExp) { return a.source === b.source && a.flags === b.flags; } if (a instanceof Error) { if (a.message !== b.message || a.name !== b.name) { return false; } } aKeys = Object.keys(a); bKeys = Object.keys(b); if (aKeys.length !== bKeys.length) { return false; } aKeys.sort(); bKeys.sort(); // Cheap key test: for (i = 0; i < aKeys.length; i++) { if (aKeys[i] !== bKeys[i]) { return false; } } // Possibly expensive deep equality test for each corresponding key: for (i = 0; i < aKeys.length; i++) { key = aKeys[i]; if (!deepEqual(a[key], b[key])) { return false; } } return typeA === typeB; } ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/console.js ================================================ /* eslint-env serviceworker */ /// import { routes } from './routes.js'; routes.set('/console', () => { console.log('Happy', 'birthday', 'Aki', 'and', 'Yuki!'); let arg; arg = new Map(); arg.set({ a: 1, b: { c: 2 } }, 2); arg.set(function foo() {}, {}); console.log('Map:', arg); arg = new Set([{ a: 1, b: { c: 2 } }, 2, 3]); console.log('Set:', arg); arg = [1, 2, 3, [], 5]; console.log('Array:', arg); arg = { a: 1, b: 2, c: 3, d() {}, get f() { return 1; }, g: function bar() {}, h: Array.from, }; console.log('Object:', arg); arg = function () {}; console.log('function:', arg); arg = true; console.log('boolean:', arg); arg = undefined; console.log('undefined:', arg); arg = null; console.log('null:', arg); arg = new Proxy({ a: 21 }, {}); console.log('proxy:', arg); arg = Infinity; console.log('Infinity:', arg); arg = NaN; console.log('NaN:', arg); arg = Symbol('wow'); console.log('Symbol:', arg); arg = new Error('uh oh'); console.log('Error:', arg); arg = 1; console.log('Number:', arg); arg = 1.111; console.log('Number:', arg); arg = 10n; console.log('BigInt:', arg); arg = new Date('2022-08-18T09:57:47.120Z'); console.log('Date:', arg); arg = 'cake'; console.log('string:', arg); arg = /magic/; console.log('RegExp:', arg); arg = Int8Array.from([1, 3, 4, 2, 5, 6, 99999]); console.log('Int8Array:', arg); arg = Uint8Array.from([1, 3, 4, 2, 5, 6, 99999]); console.log('Uint8Array:', arg); arg = Uint8ClampedArray.from([1, 3, 4, 2, 5, 6, 99999]); console.log('Uint8ClampedArray:', arg); arg = Int16Array.from([1, 3, 4, 2, 5, 6, 99999]); console.log('Int16Array:', arg); arg = Uint16Array.from([1, 3, 4, 2, 5, 6, 99999]); console.log('Uint16Array:', arg); arg = Int32Array.from([1, 3, 4, 2, 5, 6, 99999]); console.log('Int32Array:', arg); arg = Uint32Array.from([1, 3, 4, 2, 5, 6, 99999]); console.log('Uint32Array:', arg); arg = Float32Array.from([1, 3, 4, 2, 5, 6, 99999]); console.log('Float32Array:', arg); arg = Float64Array.from([1, 3, 4, 2, 5, 6, 99999]); console.log('Float64Array:', arg); arg = BigInt64Array.from([1n, 3n, 4n, 2n, 5n, 6n, 99999n]); console.log('BigInt64Array:', arg); arg = BigUint64Array.from([1n, 3n, 4n, 2n, 5n, 6n, 99999n]); console.log('BigUint64Array:', arg); arg = new WeakMap(); console.log('WeakMap:', arg); arg = new WeakSet(); console.log('WeakSet:', arg); arg = new Promise(() => {}); console.log('Promise:', arg); arg = Promise.resolve(9); console.log('resolved promise:', arg); arg = Promise.reject(new Error('oops')); console.log('rejected promise:', arg); arg.catch(() => {}); arg = new Response('Me? I am the response'); console.log('Response:', arg); arg = new Request('https://www.fastly.com', { body: 'I am the body', method: 'POST', }); console.log('Request:', arg); arg = new ReadableStream(); console.log('ReadableStream:', arg); arg = new TransformStream(); console.log('TransformStream:', arg); arg = new WritableStream(); console.log('WritableStream:', arg); arg = new URL('https://www.test.com:123/asdf?some¶ms=val'); console.log('URL:', arg); return new Response('ok'); }); ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/dynamic-backend.js ================================================ /// import { Backend, setDefaultDynamicBackendConfig, enforceExplicitBackends, } from 'fastly:backend'; import { allowDynamicBackends } from 'fastly:experimental'; import { CacheOverride } from 'fastly:cache-override'; import { assert, assertDoesNotThrow, assertRejects, assertResolves, assertThrows, deepStrictEqual, ok, strictEqual, } from './assertions.js'; import { isRunningLocally, routes } from './routes.js'; routes.set('/backend/timeout', async () => { if (isRunningLocally()) { return; } allowDynamicBackends(true); let backend = new Backend({ name: 'httpme1', target: 'http-me.fastly.dev', hostOverride: 'http-me.fastly.dev', useSSL: true, dontPool: true, betweenBytesTimeout: 1_000, connectTimeout: 1_000, firstByteTimeout: 1_000, }); console.time(`fetch('https://http-me.fastly.dev/test?wait=5000'`); await assertRejects( () => fetch('https://http-me.fastly.dev/test?wait=5000', { backend, cacheOverride: new CacheOverride('pass'), }), DOMException, 'HTTP response timeout', ); console.timeEnd(`fetch('https://http-me.fastly.dev/test?wait=5000'`); }); // implicit dynamic backend { routes.set( '/implicit-dynamic-backend/dynamic-backends-disabled', async () => { allowDynamicBackends(false); await assertRejects(() => fetch('https://http-me.fastly.dev/headers', { cacheOverride: 'pass', }), ); }, ); routes.set( '/implicit-dynamic-backend/dynamic-backends-enabled', async (evt) => { allowDynamicBackends(true); strictEqual(evt.request.backend, undefined); strictEqual(new Response('test').backend, undefined); await assertResolves(async () => { const res = await fetch('https://http-me.fastly.dev/headers', { cacheOverride: 'pass', }); strictEqual(res.backend.name, 'http-me.fastly.dev'); strictEqual(res.backend.isSSL, true); }); await assertResolves(() => fetch('https://www.fastly.com')); enforceExplicitBackends(); await assertRejects(() => fetch('https://www.fastly.com')); enforceExplicitBackends('TheOrigin'); await assertResolves(() => fetch('https://www.fastly.com')); }, ); routes.set( '/implicit-dynamic-backend/dynamic-backends-enabled-called-twice', async () => { allowDynamicBackends(true); await assertResolves(() => fetch('https://http-me.fastly.dev/headers')); await assertResolves(() => fetch('https://http-me.fastly.dev/headers')); }, ); routes.set('/implicit-dynamic-backend/default-timeouts', async () => { if (isRunningLocally()) { return; } allowDynamicBackends(true); allowDynamicBackends({ betweenBytesTimeout: 3_000, connectTimeout: 3_000, firstByteTimeout: 3_000, }); await assertResolves(() => fetch('https://http-me.fastly.dev/test?wait=2000'), ); await assertRejects( () => fetch('https://http-me.fastly.dev/test?wait=5000'), DOMException, 'HTTP response timeout', ); }); } // explicit dynamic backend { routes.set( '/explicit-dynamic-backend/dynamic-backends-enabled-all-fields', async () => { allowDynamicBackends(true); let backend = createValidHttpMeBackend(); await assertResolves(() => fetch('https://http-me.fastly.dev/headers', { backend, cacheOverride: new CacheOverride('pass'), }), ); }, ); routes.set( '/explicit-dynamic-backend/dynamic-backends-enabled-minimal-fields', async () => { allowDynamicBackends(true); let backend = createValidFastlyBackend(); await assertResolves(() => fetch('https://www.fastly.com', { backend, cacheOverride: new CacheOverride('pass'), }), ); }, ); } // Backend { routes.set('/backend/interface', async () => { let actual = Reflect.ownKeys(Backend); let expected = [ 'prototype', 'exists', 'fromName', 'health', 'length', 'name', ]; assert(actual, expected, `Reflect.ownKeys(Backend)`); actual = Reflect.getOwnPropertyDescriptor(Backend, 'prototype'); expected = { value: Backend.prototype, writable: false, enumerable: false, configurable: false, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend, 'prototype')`, ); actual = Reflect.getOwnPropertyDescriptor(Backend, 'exists'); expected = { value: Backend.exists, writable: true, enumerable: true, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend, 'exists')`, ); assert(typeof Backend.exists, 'function', `typeof Backend.exists`); assert(Backend.exists.length, 1, `Backend.exists.length`); assert(Backend.exists.name, 'exists', `Backend.exists.name`); actual = Reflect.getOwnPropertyDescriptor(Backend, 'fromName'); expected = { value: Backend.fromName, writable: true, enumerable: true, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend, 'fromName')`, ); assert(typeof Backend.fromName, 'function', `typeof Backend.fromName`); assert(Backend.fromName.length, 1, `Backend.fromName.length`); assert(Backend.fromName.name, 'fromName', `Backend.fromName.name`); actual = Reflect.getOwnPropertyDescriptor(Backend, 'health'); expected = { value: Backend.health, writable: true, enumerable: true, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend, 'health')`, ); assert(typeof Backend.health, 'function', `typeof Backend.health`); assert(Backend.health.length, 1, `Backend.health.length`); assert(Backend.health.name, 'health', `Backend.health.name`); actual = Reflect.getOwnPropertyDescriptor(Backend, 'length'); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(Backend, 'name'); expected = { value: 'Backend', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend, 'name')`, ); actual = Reflect.ownKeys(Backend.prototype); expected = [ 'constructor', 'name', 'isDynamic', 'target', 'hostOverride', 'port', 'connectTimeout', 'firstByteTimeout', 'betweenBytesTimeout', 'httpKeepaliveTime', 'tcpKeepalive', 'isSSL', 'tlsMinVersion', 'tlsMaxVersion', 'toString', 'toName', ]; assert(actual, expected, `Reflect.ownKeys(Backend.prototype)`); actual = Reflect.getOwnPropertyDescriptor(Backend.prototype, 'constructor'); expected = { writable: true, enumerable: false, configurable: true, value: Backend.prototype.constructor, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend.prototype, 'constructor')`, ); actual = Reflect.getOwnPropertyDescriptor(Backend.prototype, 'toString'); expected = { writable: true, enumerable: true, configurable: true, value: Backend.prototype.toString, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend.prototype, 'toString')`, ); assert( typeof Backend.prototype.constructor, 'function', `typeof Backend.prototype.constructor`, ); assert( typeof Backend.prototype.toString, 'function', `typeof Backend.prototype.toString`, ); assert( typeof Backend.prototype.toName, 'function', `typeof Backend.prototype.toName`, ); actual = Reflect.getOwnPropertyDescriptor( Backend.prototype.constructor, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( Backend.prototype.constructor, 'name', ); expected = { value: 'Backend', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend.prototype.constructor, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor( Backend.prototype.toString, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend.prototype.toString, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( Backend.prototype.toString, 'name', ); expected = { value: 'toString', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend.prototype.toString, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor( Backend.prototype.toName, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend.prototype.toName, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(Backend.prototype.toName, 'name'); expected = { value: 'toName', writable: false, enumerable: false, configurable: true, }; assert( actual, expected, `Reflect.getOwnPropertyDescriptor(Backend.prototype.toName, 'name')`, ); }); // constructor { routes.set('/backend/constructor/called-as-regular-function', async () => { assertThrows( () => { Backend(); }, TypeError, `calling a builtin Backend constructor without new is forbidden`, ); }); routes.set('/backend/constructor/empty-parameter', async () => { assertThrows( () => { new Backend(); }, TypeError, `Backend constructor: At least 1 argument required, but only 0 passed`, ); }); routes.set('/backend/constructor/parameter-not-an-object', async () => { const constructorArguments = [ true, false, 1, 1n, 'hello', null, undefined, Symbol(), NaN, ]; for (const argument of constructorArguments) { assertThrows( () => { new Backend(argument); }, TypeError, `Backend constructor: configuration parameter must be an Object`, ); } }); // name property { routes.set( '/backend/constructor/parameter-name-property-null', async () => { assertThrows( () => { new Backend({ name: null }); }, TypeError, `Backend constructor: name can not be null or undefined`, ); }, ); routes.set( '/backend/constructor/parameter-name-property-undefined', async () => { assertThrows( () => { new Backend({ name: undefined }); }, TypeError, `Backend constructor: name can not be null or undefined`, ); }, ); routes.set( '/backend/constructor/parameter-name-property-too-long', async () => { assertThrows( () => { new Backend({ name: 'a'.repeat(255) }); }, TypeError, `Backend constructor: name can not be more than 254 characters`, ); }, ); routes.set( '/backend/constructor/parameter-name-property-empty-string', async () => { assertThrows( () => { new Backend({ name: '' }); }, TypeError, `Backend constructor: name can not be an empty string`, ); }, ); // https://tc39.es/ecma262/#sec-tostring routes.set( '/backend/constructor/parameter-name-property-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const name = { toString() { throw sentinel; }, }; new Backend({ name }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => new Backend({ name: Symbol() }), TypeError, `can't convert symbol to string`, ); }, ); } // target property { routes.set( '/backend/constructor/parameter-target-property-null', async () => { assertThrows( () => { new Backend({ name: 'a', target: null }); }, TypeError, `Backend constructor: target can not be null or undefined`, ); }, ); routes.set( '/backend/constructor/parameter-target-property-undefined', async () => { assertThrows( () => { new Backend({ name: 'a', target: undefined }); }, TypeError, `Backend constructor: target can not be null or undefined`, ); }, ); routes.set( '/backend/constructor/parameter-target-property-empty-string', async () => { assertThrows( () => { new Backend({ name: 'a', target: '' }); }, TypeError, `Backend constructor: target can not be an empty string`, ); }, ); // https://tc39.es/ecma262/#sec-tostring routes.set( '/backend/constructor/parameter-target-property-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const target = { toString() { throw sentinel; }, }; new Backend({ name: 'a', target }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => new Backend({ name: 'a', target: Symbol() }), TypeError, `can't convert symbol to string`, ); }, ); routes.set( '/backend/constructor/parameter-target-property-valid-host', async () => { const targets = [ 'www.fastly.com', 'w-w-w.f-a-s-t-l-y.c-o-m', 'a'.repeat(63) + '.com', `${'a'.repeat(63)}.${'a'.repeat(63)}.${'a'.repeat(63)}.${'a'.repeat(57)}.com`, 'ai', 'w.a:1', 'fastly.com:1', 'fastly.com:80', 'fastly.com:443', 'fastly.com:65535', // Basic zero IPv4 address. '0.0.0.0', // Basic non-zero IPv4 address. '192.168.140.255', // TODO: These are commented out as the hostcall currently yields an error of "invalid authority" when given an ipv6 address // Localhost IPv6. // "::1", // Fully expanded IPv6 address. // "fd7a:115c:a1e0:ab12:4843:cd96:626b:430b", // IPv6 with elided fields in the middle. // "fd7a:115c::626b:430b", // IPv6 with elided fields at the end. // "fd7a:115c:a1e0:ab12:4843:cd96::", // IPv6 with single elided field at the end. // "fd7a:115c:a1e0:ab12:4843:cd96:626b::", // IPv6 with single elided field in the middle. // "fd7a:115c:a1e0::4843:cd96:626b:430b", // IPv6 with the trailing 32 bits written as IPv4 dotted decimal. (4in6) // "::ffff:192.168.140.255", // IPv6 with capital letters. // "FD9E:1A04:F01D::1", ]; let i = 0; for (const target of targets) { assertDoesNotThrow(() => { new Backend({ name: 'target-property-valid-host-' + i, target }); }); i++; } }, ); routes.set( '/backend/constructor/parameter-target-property-invalid-host', async () => { const targets = [ '-www.fastly.com', 'www.fastly.com-', 'a'.repeat(64) + '.com', `${'a'.repeat(63)}.${'a'.repeat(63)}.${'a'.repeat(63)}.${'a'.repeat(58)}.com`, 'w$.com', 'w.a:a', 'fastly.com:-1', 'fastly.com:0', 'fastly.com:65536', // IPv4 address in windows-style "print all the digits" form. // "010.000.015.001", // IPv4 address with a silly amount of leading zeros. // "000001.00000002.00000003.000000004", // 4-in-6 with octet with leading zero // "::ffff:1.2.03.4", // Basic zero IPv6 address. '::', // IPv6 with not enough fields '1:2:3:4:5:6:7', // IPv6 with too many fields '1:2:3:4:5:6:7:8:9', // IPv6 with 8 fields and a :: expander '1:2:3:4::5:6:7:8', // IPv6 with a field bigger than 2b 'fe801::1', // IPv6 with non-hex values in field 'fe80:tail:scal:e::', // IPv6 with a zone delimiter but no zone. 'fe80::1%', // IPv6 (without ellipsis) with too many fields for trailing embedded IPv4. 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:192.168.140.255', // IPv6 (with ellipsis) with too many fields for trailing embedded IPv4. 'ffff::ffff:ffff:ffff:ffff:ffff:ffff:192.168.140.255', // IPv6 with invalid embedded IPv4. '::ffff:192.168.140.bad', // IPv6 with multiple ellipsis ::. 'fe80::1::1', // IPv6 with invalid non hex/colon character. 'fe80:1?:1', // IPv6 with truncated bytes after single colon. 'fe80:', ':::1', ':0:1', ':', ]; let i = 0; for (const target of targets) { assertThrows( () => { new Backend({ name: 'target-property-invalid-host-' + i, target, }); }, TypeError, `Backend constructor: target does not contain a valid IPv4, IPv6, or hostname address`, ); i++; } }, ); } // ciphers property { routes.set( '/backend/constructor/parameter-ciphers-property-empty-string', async () => { assertThrows( () => { new Backend({ name: 'a', target: 'a', ciphers: '' }); }, TypeError, `Backend constructor: ciphers can not be an empty string`, ); }, ); routes.set( '/backend/constructor/parameter-ciphers-property-invalid-cipherlist-string', async () => { assertThrows( () => { new Backend({ name: 'a', target: 'a', ciphers: ",;'^%$#^" }); }, TypeError, `Backend constructor: none of the provided ciphers are supported by Fastly. The list of supported ciphers is available on https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration`, ); }, ); const validCiphers = [ 'ALL', 'DEFAULT', 'COMPLEMENTOFDEFAULT', 'aRSA', 'RSA', 'kEECDH', 'kECDHE', 'ECDH', 'ECDHE', 'EECDH', 'TLSv1.2', 'TLSv1.0', 'SSLv3', 'AES128', 'AES256', 'AES', 'AESGCM', 'CHACHA20', '3DES', 'SHA1', 'SHA', 'SHA256', 'SHA384', 'DES-CBC3-SHA', 'AES128-SHA', 'AES256-SHA', 'ECDHE-RSA-AES128-SHA', 'ECDHE-RSA-AES256-SHA', 'AES128-GCM-SHA256', 'ECDHE-RSA-AES128-SHA256', 'ECDHE-RSA-AES256-SHA384', 'ECDHE-RSA-AES128-GCM-SHA256', 'ECDHE-RSA-AES256-GCM-SHA384', 'ECDHE-RSA-CHACHA20-POLY1305', ]; const invalidCiphers = [ 'COMPLEMENTOFALL', 'eNULL', 'NULL', 'aNULL', 'kDHr', 'kDHd', 'kDH', 'kDHE', 'kEDH', 'DH', 'DHE', 'EDH', 'ADH', 'AECDH', 'aDSS', 'DSS', 'aDH', 'aECDSA', 'ECDSA', 'AESCCM', 'AESCCM8', 'ARIA128', 'ARIA256', 'ARIA', 'CAMELLIA128', 'CAMELLIA256', 'CAMELLIA', 'DES', 'RC4', 'RC2', 'IDEA', 'SEED', 'MD5', 'aGOST', 'aGOST01', 'kGOST', 'GOST94', 'GOST89MAC', 'PSK', 'kPSK', 'kECDHEPSK', 'kDHEPSK', 'kRSAPSK', 'aPSK', 'SUITEB128', 'SUITEB128ONLY', 'SUITEB192', 'CBC', 'NULL-MD5', 'NULL-SHA', 'RC4-MD5', 'RC4-SHA', 'IDEA-CBC-SHA', 'DH-DSS-DES-CBC3-SHA', 'DH-RSA-DES-CBC3-SHA', 'DHE-DSS-DES-CBC3-SHA', 'DHE-RSA-DES-CBC3-SHA', 'ADH-RC4-MD5', 'ADH-DES-CBC3-SHA', 'NULL-MD5', 'NULL-SHA', 'RC4-MD5', 'RC4-SHA', 'IDEA-CBC-SHA', 'DHE-DSS-DES-CBC3-SHA', 'DHE-RSA-DES-CBC3-SHA', 'ADH-RC4-MD5', 'ADH-DES-CBC3-SHA', 'DH-DSS-AES128-SHA', 'DH-DSS-AES256-SHA', 'DH-RSA-AES128-SHA', 'DH-RSA-AES256-SHA', 'DHE-DSS-AES128-SHA', 'DHE-DSS-AES256-SHA', 'DHE-RSA-AES128-SHA', 'DHE-RSA-AES256-SHA', 'ADH-AES128-SHA', 'ADH-AES256-SHA', 'CAMELLIA128-SHA', 'CAMELLIA256-SHA', 'DH-DSS-CAMELLIA128-SHA', 'DH-DSS-CAMELLIA256-SHA', 'DH-RSA-CAMELLIA128-SHA', 'DH-RSA-CAMELLIA256-SHA', 'DHE-DSS-CAMELLIA128-SHA', 'DHE-DSS-CAMELLIA256-SHA', 'DHE-RSA-CAMELLIA128-SHA', 'DHE-RSA-CAMELLIA256-SHA', 'ADH-CAMELLIA128-SHA', 'ADH-CAMELLIA256-SHA', 'SEED-SHA', 'DH-DSS-SEED-SHA', 'DH-RSA-SEED-SHA', 'DHE-DSS-SEED-SHA', 'DHE-RSA-SEED-SHA', 'ADH-SEED-SHA', 'GOST94-GOST89-GOST89', 'GOST2001-GOST89-GOST89', 'GOST94-NULL-GOST94', 'GOST2001-NULL-GOST94', 'GOST2012-GOST8912-GOST8912', 'GOST2012-NULL-GOST12', 'DHE-DSS-RC4-SHA', 'ECDHE-RSA-NULL-SHA', 'ECDHE-RSA-RC4-SHA', 'ECDHE-RSA-DES-CBC3-SHA', 'ECDHE-ECDSA-NULL-SHA', 'ECDHE-ECDSA-RC4-SHA', 'ECDHE-ECDSA-DES-CBC3-SHA', 'ECDHE-ECDSA-AES128-SHA', 'ECDHE-ECDSA-AES256-SHA', 'AECDH-NULL-SHA', 'AECDH-RC4-SHA', 'AECDH-DES-CBC3-SHA', 'AECDH-AES128-SHA', 'AECDH-AES256-SHA', 'NULL-SHA256', 'AES128-SHA256', 'AES256-SHA256', 'AES256-GCM-SHA384', 'DH-RSA-AES128-SHA256', 'DH-RSA-AES256-SHA256', 'DH-RSA-AES128-GCM-SHA256', 'DH-RSA-AES256-GCM-SHA384', 'DH-DSS-AES128-SHA256', 'DH-DSS-AES256-SHA256', 'DH-DSS-AES128-GCM-SHA256', 'DH-DSS-AES256-GCM-SHA384', 'DHE-RSA-AES128-SHA256', 'DHE-RSA-AES256-SHA256', 'DHE-RSA-AES128-GCM-SHA256', 'DHE-RSA-AES256-GCM-SHA384', 'DHE-DSS-AES128-SHA256', 'DHE-DSS-AES256-SHA256', 'DHE-DSS-AES128-GCM-SHA256', 'DHE-DSS-AES256-GCM-SHA384', 'ECDHE-ECDSA-AES128-SHA256', 'ECDHE-ECDSA-AES256-SHA384', 'ECDHE-ECDSA-AES128-GCM-SHA256', 'ECDHE-ECDSA-AES256-GCM-SHA384', 'ADH-AES128-SHA256', 'ADH-AES256-SHA256', 'ADH-AES128-GCM-SHA256', 'ADH-AES256-GCM-SHA384', 'AES128-CCM', 'AES256-CCM', 'DHE-RSA-AES128-CCM', 'DHE-RSA-AES256-CCM', 'AES128-CCM8', 'AES256-CCM8', 'DHE-RSA-AES128-CCM8', 'DHE-RSA-AES256-CCM8', 'ECDHE-ECDSA-AES128-CCM', 'ECDHE-ECDSA-AES256-CCM', 'ECDHE-ECDSA-AES128-CCM8', 'ECDHE-ECDSA-AES256-CCM8', 'ARIA128-GCM-SHA256', 'ARIA256-GCM-SHA384', 'DHE-RSA-ARIA128-GCM-SHA256', 'DHE-RSA-ARIA256-GCM-SHA384', 'DHE-DSS-ARIA128-GCM-SHA256', 'DHE-DSS-ARIA256-GCM-SHA384', 'ECDHE-ECDSA-ARIA128-GCM-SHA256', 'ECDHE-ECDSA-ARIA256-GCM-SHA384', 'ECDHE-ARIA128-GCM-SHA256', 'ECDHE-ARIA256-GCM-SHA384', 'PSK-ARIA128-GCM-SHA256', 'PSK-ARIA256-GCM-SHA384', 'DHE-PSK-ARIA128-GCM-SHA256', 'DHE-PSK-ARIA256-GCM-SHA384', 'RSA-PSK-ARIA128-GCM-SHA256', 'RSA-PSK-ARIA256-GCM-SHA384', 'ECDHE-ECDSA-CAMELLIA128-SHA256', 'ECDHE-ECDSA-CAMELLIA256-SHA384', 'ECDHE-RSA-CAMELLIA128-SHA256', 'ECDHE-RSA-CAMELLIA256-SHA384', 'PSK-NULL-SHA', 'DHE-PSK-NULL-SHA', 'RSA-PSK-NULL-SHA', 'PSK-RC4-SHA', 'PSK-3DES-EDE-CBC-SHA', 'PSK-AES128-CBC-SHA', 'PSK-AES256-CBC-SHA', 'DHE-PSK-RC4-SHA', 'DHE-PSK-3DES-EDE-CBC-SHA', 'DHE-PSK-AES128-CBC-SHA', 'DHE-PSK-AES256-CBC-SHA', 'RSA-PSK-RC4-SHA', 'RSA-PSK-3DES-EDE-CBC-SHA', 'RSA-PSK-AES128-CBC-SHA', 'RSA-PSK-AES256-CBC-SHA', 'PSK-AES128-GCM-SHA256', 'PSK-AES256-GCM-SHA384', 'DHE-PSK-AES128-GCM-SHA256', 'DHE-PSK-AES256-GCM-SHA384', 'RSA-PSK-AES128-GCM-SHA256', 'RSA-PSK-AES256-GCM-SHA384', 'PSK-AES128-CBC-SHA256', 'PSK-AES256-CBC-SHA384', 'PSK-NULL-SHA256', 'PSK-NULL-SHA384', 'DHE-PSK-AES128-CBC-SHA256', 'DHE-PSK-AES256-CBC-SHA384', 'DHE-PSK-NULL-SHA256', 'DHE-PSK-NULL-SHA384', 'RSA-PSK-AES128-CBC-SHA256', 'RSA-PSK-AES256-CBC-SHA384', 'RSA-PSK-NULL-SHA256', 'RSA-PSK-NULL-SHA384', 'PSK-AES128-GCM-SHA256', 'PSK-AES256-GCM-SHA384', 'ECDHE-PSK-RC4-SHA', 'ECDHE-PSK-3DES-EDE-CBC-SHA', 'ECDHE-PSK-AES128-CBC-SHA', 'ECDHE-PSK-AES256-CBC-SHA', 'ECDHE-PSK-AES128-CBC-SHA256', 'ECDHE-PSK-AES256-CBC-SHA384', 'ECDHE-PSK-NULL-SHA', 'ECDHE-PSK-NULL-SHA256', 'ECDHE-PSK-NULL-SHA384', 'PSK-CAMELLIA128-SHA256', 'PSK-CAMELLIA256-SHA384', 'DHE-PSK-CAMELLIA128-SHA256', 'DHE-PSK-CAMELLIA256-SHA384', 'RSA-PSK-CAMELLIA128-SHA256', 'RSA-PSK-CAMELLIA256-SHA384', 'ECDHE-PSK-CAMELLIA128-SHA256', 'ECDHE-PSK-CAMELLIA256-SHA384', 'PSK-AES128-CCM', 'PSK-AES256-CCM', 'DHE-PSK-AES128-CCM', 'DHE-PSK-AES256-CCM', 'PSK-AES128-CCM8', 'PSK-AES256-CCM8', 'DHE-PSK-AES128-CCM8', 'DHE-PSK-AES256-CCM8', 'ECDHE-ECDSA-CHACHA20-POLY1305', 'DHE-RSA-CHACHA20-POLY1305', 'PSK-CHACHA20-POLY1305', 'ECDHE-PSK-CHACHA20-POLY1305', 'DHE-PSK-CHACHA20-POLY1305', 'RSA-PSK-CHACHA20-POLY1305', ]; routes.set( '/backend/constructor/parameter-ciphers-property-valid-cipherlist-strings-supported-by-fastly', async () => { const ciphers = [...validCiphers]; for (const cipher of ciphers) { assertDoesNotThrow(() => { new Backend({ name: cipher, target: 'a', ciphers: cipher }); }); } assertDoesNotThrow(() => { new Backend({ name: 'all-valid-ciphers', target: 'a', ciphers: validCiphers.join(':'), }); new Backend({ name: 'all-ciphers-invalid-marked-as-exclude', target: 'a', ciphers: validCiphers .concat(invalidCiphers.map((c) => '!' + c)) .join(':'), }); }); }, ); routes.set( '/backend/constructor/parameter-ciphers-property-valid-cipherlist-strings-but-not-supported-by-fastly', async () => { const ciphers = [...invalidCiphers]; for (const cipher of ciphers) { assertThrows( () => { new Backend({ name: cipher, target: 'a', ciphers: cipher }); }, TypeError, `Backend constructor: none of the provided ciphers are supported by Fastly. The list of supported ciphers is available on https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration`, ); } assertThrows( () => { new Backend({ name: 'all-invalid-ciphers', target: 'a', ciphers: invalidCiphers.join(':'), }); }, TypeError, `Backend constructor: none of the provided ciphers are supported by Fastly. The list of supported ciphers is available on https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration`, ); assertThrows( () => { new Backend({ name: 'all-ciphers-valid-marked-as-exclude', target: 'a', ciphers: invalidCiphers .concat(validCiphers.map((c) => '!' + c)) .join(':'), }); }, TypeError, `Backend constructor: none of the provided ciphers are supported by Fastly. The list of supported ciphers is available on https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration`, ); }, ); // https://tc39.es/ecma262/#sec-tostring routes.set( '/backend/constructor/parameter-ciphers-property-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const ciphers = { toString() { throw sentinel; }, }; new Backend({ name: 'a', target: 'a', ciphers }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => new Backend({ name: 'a', target: 'a', ciphers: Symbol() }), TypeError, `can't convert symbol to string`, ); }, ); // AND (+) operator: intersection of two cipher groups routes.set( '/backend/constructor/parameter-ciphers-property-and-operator', async () => { assertDoesNotThrow(() => { new Backend({ name: 'and-sha1-aes128', target: 'a', ciphers: 'SHA1+AES128', }); }); assertDoesNotThrow(() => { new Backend({ name: 'and-sha1-aes256', target: 'a', ciphers: 'SHA1+AES256', }); }); assertDoesNotThrow(() => { new Backend({ name: 'and-sha1-ecdhe', target: 'a', ciphers: 'SHA1+ECDHE', }); }); assertThrows( () => { new Backend({ name: 'and-sha1-aesgcm', target: 'a', ciphers: 'SHA1+AESGCM', }); }, TypeError, `Backend constructor: none of the provided ciphers are supported by Fastly. The list of supported ciphers is available on https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration`, ); assertThrows( () => { new Backend({ name: 'and-sha1-chacha20', target: 'a', ciphers: 'SHA1+CHACHA20', }); }, TypeError, `Backend constructor: none of the provided ciphers are supported by Fastly. The list of supported ciphers is available on https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration`, ); }, ); } // hostOverride property { routes.set( '/backend/constructor/parameter-hostOverride-property-empty-string', async () => { assertThrows( () => { new Backend({ name: 'hostOverride-property-empty-string', target: 'a', hostOverride: '', }); }, TypeError, `Backend constructor: hostOverride can not be an empty string`, ); }, ); // https://tc39.es/ecma262/#sec-tostring routes.set( '/backend/constructor/parameter-hostOverride-property-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const hostOverride = { toString() { throw sentinel; }, }; new Backend({ name: 'hostOverride-property-calls-ToString', target: 'a', hostOverride, }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => new Backend({ name: 'hostOverride-property-calls-ToString', target: 'a', hostOverride: Symbol(), }), TypeError, `can't convert symbol to string`, ); }, ); routes.set( '/backend/constructor/parameter-hostOverride-property-valid-string', async () => { assertDoesNotThrow(() => { new Backend({ name: 'hostOverride-property-valid-string', target: 'a', hostOverride: 'www.fastly.com', }); }); }, ); } // connectTimeout property { routes.set( '/backend/constructor/parameter-connectTimeout-property-negative-number', async () => { assertThrows( () => { new Backend({ name: 'connectTimeout-property-negative-number', target: 'a', connectTimeout: -1, }); }, RangeError, `Backend constructor: connectTimeout can not be a negative number`, ); }, ); routes.set( '/backend/constructor/parameter-connectTimeout-property-too-big', async () => { assertThrows( () => { new Backend({ name: 'connectTimeout-property-too-big', target: 'a', connectTimeout: Math.pow(2, 32), }); }, RangeError, `Backend constructor: connectTimeout is above the maximum of 4294967296`, ); }, ); // https://tc39.es/ecma262/#sec-tonumber routes.set( '/backend/constructor/parameter-connectTimeout-property-calls-7.1.4-ToNumber', async () => { let sentinel; let requestedType; const test = () => { sentinel = Symbol(); const connectTimeout = { [Symbol.toPrimitive](type) { requestedType = type; throw sentinel; }, }; new Backend({ name: 'connectTimeout-property-calls-ToNumber', target: 'a', connectTimeout, }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); assert(requestedType, 'number', 'requestedType === "number"'); } assertThrows( () => new Backend({ name: 'connectTimeout-property-calls-ToNumber', target: 'a', connectTimeout: Symbol(), }), TypeError, `can't convert symbol to number`, ); }, ); routes.set( '/backend/constructor/parameter-connectTimeout-property-valid-number', async () => { assertDoesNotThrow(() => { new Backend({ name: 'connectTimeout-property-valid-number', target: 'a', connectTimeout: 1, }); }); }, ); } // firstByteTimeout property { routes.set( '/backend/constructor/parameter-firstByteTimeout-property-negative-number', async () => { assertThrows( () => { new Backend({ name: 'firstByteTimeout-property-negative-number', target: 'a', firstByteTimeout: -1, }); }, RangeError, `Backend constructor: firstByteTimeout can not be a negative number`, ); }, ); routes.set( '/backend/constructor/parameter-firstByteTimeout-property-too-big', async () => { assertThrows( () => { new Backend({ name: 'firstByteTimeout-property-too-big', target: 'a', firstByteTimeout: Math.pow(2, 32), }); }, RangeError, `Backend constructor: firstByteTimeout is above the maximum of 4294967296`, ); }, ); // https://tc39.es/ecma262/#sec-tonumber routes.set( '/backend/constructor/parameter-firstByteTimeout-property-calls-7.1.4-ToNumber', async () => { let sentinel; let requestedType; const test = () => { sentinel = Symbol(); const firstByteTimeout = { [Symbol.toPrimitive](type) { requestedType = type; throw sentinel; }, }; new Backend({ name: 'firstByteTimeout-property-calls-ToNumber', target: 'a', firstByteTimeout, }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); assert(requestedType, 'number', 'requestedType === "number"'); } assertThrows( () => new Backend({ name: 'firstByteTimeout-property-calls-ToNumber', target: 'a', firstByteTimeout: Symbol(), }), TypeError, `can't convert symbol to number`, ); }, ); routes.set( '/backend/constructor/parameter-firstByteTimeout-property-valid-number', async () => { assertDoesNotThrow(() => { new Backend({ name: 'firstByteTimeout-property-valid-number', target: 'a', firstByteTimeout: 1, }); }); }, ); routes.set( '/backend/constructor/parameter-firstByteTimeout-property-invalid-number', async () => { assertThrows(() => { new Backend({ name: 'firstByteTimeout-property-valid-number', target: 'a', firstByteTimeout: 'zzz', }); }, RangeError); }, ); } // betweenBytesTimeout property { routes.set( '/backend/constructor/parameter-betweenBytesTimeout-property-negative-number', async () => { assertThrows( () => { new Backend({ name: 'betweenBytesTimeout-property-negative-number', target: 'a', betweenBytesTimeout: -1, }); }, RangeError, `Backend constructor: betweenBytesTimeout can not be a negative number`, ); }, ); routes.set( '/backend/constructor/parameter-betweenBytesTimeout-property-too-big', async () => { assertThrows( () => { new Backend({ name: 'betweenBytesTimeout-property-too-big', target: 'a', betweenBytesTimeout: Math.pow(2, 32), }); }, RangeError, `Backend constructor: betweenBytesTimeout is above the maximum of 4294967296`, ); }, ); // https://tc39.es/ecma262/#sec-tonumber routes.set( '/backend/constructor/parameter-betweenBytesTimeout-property-calls-7.1.4-ToNumber', async () => { let sentinel; let requestedType; const test = () => { sentinel = Symbol(); const betweenBytesTimeout = { [Symbol.toPrimitive](type) { requestedType = type; throw sentinel; }, }; new Backend({ name: 'betweenBytesTimeout-property-calls-ToNumber', target: 'a', betweenBytesTimeout, }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); assert(requestedType, 'number', 'requestedType === "number"'); } assertThrows( () => new Backend({ name: 'betweenBytesTimeout-property-calls-ToNumber', target: 'a', betweenBytesTimeout: Symbol(), }), TypeError, `can't convert symbol to number`, ); }, ); routes.set( '/backend/constructor/parameter-betweenBytesTimeout-property-valid-number', async () => { assertDoesNotThrow(() => { new Backend({ name: 'betweenBytesTimeout-property-valid-number', target: 'a', betweenBytesTimeout: 1, }); }); }, ); } // useSSL property { routes.set( '/backend/constructor/parameter-useSSL-property-valid-boolean', async () => { const types = [{}, [], Symbol(), 1, '2']; for (const type of types) { assertDoesNotThrow(() => { new Backend({ name: 'useSSL-property-valid-boolean' + String(type), target: 'a', useSSL: type, }); }); } assertDoesNotThrow(() => { new Backend({ name: 'useSSL-property-valid-boolean-true', target: 'a', useSSL: true, }); }); assertDoesNotThrow(() => { new Backend({ name: 'useSSL-property-valid-boolean-false', target: 'a', useSSL: false, }); }); }, ); } // dontPool property { routes.set( '/backend/constructor/parameter-dontPool-property-valid-boolean', async () => { const types = [{}, [], Symbol(), 1, '2']; for (const type of types) { assertDoesNotThrow(() => { new Backend({ name: 'dontPool-property-valid-boolean' + String(type), target: 'a', dontPool: type, }); }); } assertDoesNotThrow(() => { new Backend({ name: 'dontPool-property-valid-boolean-true', target: 'a', dontPool: true, }); }); assertDoesNotThrow(() => { new Backend({ name: 'dontPool-property-valid-boolean-false', target: 'a', dontPool: false, }); }); }, ); } // tlsMinVersion property { routes.set( '/backend/constructor/parameter-tlsMinVersion-property-nan', async () => { assertThrows( () => { new Backend({ name: 'tlsMinVersion-property-nan', target: 'a', tlsMinVersion: NaN, }); }, RangeError, `Backend constructor: tlsMinVersion must be either 1, 1.1, 1.2, or 1.3`, ); }, ); routes.set( '/backend/constructor/parameter-tlsMinVersion-property-invalid-number', async () => { assertThrows( () => { new Backend({ name: 'tlsMinVersion-property-invalid-number', target: 'a', tlsMinVersion: 1.4, }); }, RangeError, `Backend constructor: tlsMinVersion must be either 1, 1.1, 1.2, or 1.3`, ); }, ); // https://tc39.es/ecma262/#sec-tonumber routes.set( '/backend/constructor/parameter-tlsMinVersion-property-calls-7.1.4-ToNumber', async () => { let sentinel; let requestedType; const test = () => { sentinel = Symbol(); const tlsMinVersion = { [Symbol.toPrimitive](type) { requestedType = type; throw sentinel; }, }; new Backend({ name: 'tlsMinVersion-property-calls-ToNumber', target: 'a', tlsMinVersion, }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); assert(requestedType, 'number', 'requestedType === "number"'); } assertThrows( () => new Backend({ name: 'tlsMinVersion-property-calls-ToNumber', target: 'a', tlsMinVersion: Symbol(), }), TypeError, `can't convert symbol to number`, ); }, ); routes.set( '/backend/constructor/parameter-tlsMinVersion-property-valid-number', async () => { assertDoesNotThrow(() => { new Backend({ name: 'tlsMinVersion-property-valid-number-1', target: 'a', tlsMinVersion: 1, }); }); assertDoesNotThrow(() => { new Backend({ name: 'tlsMinVersion-property-valid-number-1.0', target: 'a', tlsMinVersion: 1.0, }); }); assertDoesNotThrow(() => { new Backend({ name: 'tlsMinVersion-property-valid-number-1.1', target: 'a', tlsMinVersion: 1.1, }); }); assertDoesNotThrow(() => { new Backend({ name: 'tlsMinVersion-property-valid-number-1.2', target: 'a', tlsMinVersion: 1.2, }); }); assertDoesNotThrow(() => { new Backend({ name: 'tlsMinVersion-property-valid-number-1.3', target: 'a', tlsMinVersion: 1.3, }); }); }, ); routes.set( '/backend/constructor/parameter-tlsMinVersion-greater-than-tlsMaxVersion', async () => { assertThrows( () => { new Backend({ name: 'tlsMinVersion-property-valid-number', target: 'a', tlsMinVersion: 1.3, tlsMaxVersion: 1.2, }); }, RangeError, `Backend constructor: tlsMinVersion must be less than or equal to tlsMaxVersion`, ); }, ); } // tlsMaxVersion property { routes.set( '/backend/constructor/parameter-tlsMaxVersion-property-nan', async () => { assertThrows( () => { new Backend({ name: 'tlsMaxVersion-property-nan', target: 'a', tlsMaxVersion: NaN, }); }, RangeError, `Backend constructor: tlsMaxVersion must be either 1, 1.1, 1.2, or 1.3`, ); }, ); routes.set( '/backend/constructor/parameter-tlsMaxVersion-property-invalid-number', async () => { assertThrows( () => { new Backend({ name: 'tlsMaxVersion-property-invalid-number', target: 'a', tlsMaxVersion: 1.4, }); }, RangeError, `Backend constructor: tlsMaxVersion must be either 1, 1.1, 1.2, or 1.3`, ); }, ); // https://tc39.es/ecma262/#sec-tonumber routes.set( '/backend/constructor/parameter-tlsMaxVersion-property-calls-7.1.4-ToNumber', async () => { let sentinel; let requestedType; const test = () => { sentinel = Symbol(); const tlsMaxVersion = { [Symbol.toPrimitive](type) { requestedType = type; throw sentinel; }, }; new Backend({ name: 'tlsMaxVersion-property-calls-ToNumber', target: 'a', tlsMaxVersion, }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); assert(requestedType, 'number', 'requestedType === "number"'); } assertThrows( () => new Backend({ name: 'tlsMaxVersion-property-calls-ToNumber', target: 'a', tlsMaxVersion: Symbol(), }), TypeError, `can't convert symbol to number`, ); }, ); routes.set( '/backend/constructor/parameter-tlsMaxVersion-property-valid-number', async () => { assertDoesNotThrow(() => { new Backend({ name: 'tlsMaxVersion-property-valid-number-1', target: 'a', tlsMaxVersion: 1, }); new Backend({ name: 'tlsMaxVersion-property-valid-number-1.0', target: 'a', tlsMaxVersion: 1.0, }); new Backend({ name: 'tlsMaxVersion-property-valid-number-1.1', target: 'a', tlsMaxVersion: 1.1, }); new Backend({ name: 'tlsMaxVersion-property-valid-number-1.2', target: 'a', tlsMaxVersion: 1.2, }); new Backend({ name: 'tlsMaxVersion-property-valid-number-1.3', target: 'a', tlsMaxVersion: 1.3, }); }); }, ); } // certificateHostname property { routes.set( '/backend/constructor/parameter-certificateHostname-property-empty-string', async () => { assertThrows( () => { new Backend({ name: 'certificateHostname-property-empty-string', target: 'a', certificateHostname: '', }); }, TypeError, `Backend constructor: certificateHostname can not be an empty string`, ); }, ); // https://tc39.es/ecma262/#sec-tostring routes.set( '/backend/constructor/parameter-certificateHostname-property-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const certificateHostname = { toString() { throw sentinel; }, }; new Backend({ name: 'certificateHostname-property-calls-ToString', target: 'a', certificateHostname, }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => new Backend({ name: 'certificateHostname-property-calls-ToString', target: 'a', certificateHostname: Symbol(), }), TypeError, `can't convert symbol to string`, ); }, ); routes.set( '/backend/constructor/parameter-certificateHostname-property-valid-string', async () => { assertDoesNotThrow(() => { new Backend({ name: 'certificateHostname-property-valid-string', target: 'a', certificateHostname: 'www.fastly.com', }); }); }, ); } // caCertificate property { routes.set( '/backend/constructor/parameter-caCertificate-property-empty-string', async () => { assertThrows( () => { new Backend({ name: 'caCertificate-property-empty-string', target: 'a', caCertificate: '', }); }, TypeError, `Backend constructor: caCertificate can not be an empty string`, ); }, ); // https://tc39.es/ecma262/#sec-tostring routes.set( '/backend/constructor/parameter-caCertificate-property-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const caCertificate = { toString() { throw sentinel; }, }; new Backend({ name: 'caCertificate-property-calls-ToString', target: 'a', caCertificate, }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => new Backend({ name: 'caCertificate-property-calls-ToString', target: 'a', caCertificate: Symbol(), }), TypeError, `can't convert symbol to string`, ); }, ); routes.set( '/backend/constructor/parameter-caCertificate-property-valid-string', async () => { assertDoesNotThrow(() => { new Backend({ name: 'caCertificate-property-valid-string', target: 'a', caCertificate: 'www.fastly.com', }); }); }, ); } // sniHostname property { routes.set( '/backend/constructor/parameter-sniHostname-property-empty-string', async () => { assertThrows( () => { new Backend({ name: 'sniHostname-property-empty-string', target: 'a', sniHostname: '', }); }, TypeError, `Backend constructor: sniHostname can not be an empty string`, ); }, ); // https://tc39.es/ecma262/#sec-tostring routes.set( '/backend/constructor/parameter-sniHostname-property-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const sniHostname = { toString() { throw sentinel; }, }; new Backend({ name: 'sniHostname-property-calls-ToString', target: 'a', sniHostname, }); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => new Backend({ name: 'sniHostname-property-calls-ToString', target: 'a', sniHostname: Symbol(), }), TypeError, `can't convert symbol to string`, ); }, ); routes.set( '/backend/constructor/parameter-sniHostname-property-valid-string', async () => { assertDoesNotThrow(() => { new Backend({ name: 'sniHostname-property-valid-string', target: 'a', sniHostname: 'www.fastly.com', }); }); }, ); } // clientCertificate property { routes.set( '/backend/constructor/parameter-clientCertificate-property-invalid', async () => { assertThrows( () => { new Backend({ name: 'clientCertificate-clientCertificate-property-invalid', target: 'a', clientCertificate: '', }); }, TypeError, `Backend constructor: clientCertificate must be an object containing 'certificate' and 'key' properties`, ); }, ); routes.set( '/backend/constructor/parameter-clientCertificate-certificate-property-missing', async () => { assertThrows( () => { new Backend({ name: 'clientCertificate-clientCertificate-certificate-property-missing', target: 'a', clientCertificate: {}, }); }, TypeError, `Backend constructor: clientCertificate 'certificate' must be a certificate string`, ); }, ); routes.set( '/backend/constructor/parameter-clientCertificate-certificate-property-invalid', async () => { assertThrows( () => { new Backend({ name: 'clientCertificate-clientCertificate-certificate-property-invalid', target: 'a', clientCertificate: { certificate: '' }, }); }, TypeError, `Backend constructor: clientCertificate 'certificate' can not be an empty string`, ); }, ); routes.set( '/backend/constructor/parameter-clientCertificate-key-property-missing', async () => { assertThrows( () => { new Backend({ name: 'clientCertificate-clientCertificate-key-property-missing', target: 'a', clientCertificate: { certificate: 'a' }, }); }, TypeError, `Backend constructor: clientCertificate 'key' must be a SecretStoreEntry instance`, ); }, ); routes.set( '/backend/constructor/parameter-clientCertificate-key-property-invalid', async () => { assertThrows( () => { new Backend({ name: 'clientCertificate-clientCertificate-key-property-invalid', target: 'a', clientCertificate: { certificate: 'a', key: '' }, }); }, TypeError, `Backend constructor: clientCertificate 'key' must be a SecretStoreEntry instance`, ); }, ); routes.set( '/backend/constructor/parameter-clientCertificate-key-property-fake', async () => { assertThrows( () => { new Backend({ name: 'clientCertificate-clientCertificate-key-property-fake', target: 'a', clientCertificate: { certificate: 'a', key: Object.create(SecretStoreEntry.prototype), }, }); }, TypeError, `Backend constructor: clientCertificate 'key' must be a SecretStoreEntry instance`, ); }, ); routes.set( '/backend/constructor/parameter-clientCertificate-valid', async () => { if (isRunningLocally()) { return; } let backend = new Backend({ name: 'clientCertificate-clientCertificate-valid', target: 'http-me.fastly.dev', clientCertificate: { certificate: 'a', key: SecretStore.fromBytes(new Uint8Array([1, 2, 3])), }, }); await fetch('https://http-me.fastly.dev/headers', { backend, cacheOverride: new CacheOverride('pass'), }); }, ); } // grpc property { routes.set( '/backend/constructor/parameter-grpc-property-falsy', async () => { if (isRunningLocally()) { return; } let backend = new Backend({ name: 'grpc-grpc-invalid', target: 'http-me.fastly.dev', grpc: 0, }); await fetch('https://http-me.fastly.dev/anything', { backend, cacheOverride: new CacheOverride('pass'), }); }, ); routes.set('/backend/constructor/parameter-grpc-enabled', async () => { if (isRunningLocally()) { return; } let backend = new Backend({ name: 'grpc-grpc-valid', target: 'http-me.fastly.dev', grpc: true, }); await assertRejects( () => fetch('https://http-me.fastly.dev/anything', { backend, cacheOverride: new CacheOverride('pass'), }), DOMException, ); }); } // httpKeepalive { routes.set('/backend/constructor/http-keepalive-invalid', async () => { await assertRejects(async () => { await fetch('https://http-me.fastly.dev/anything', { backend: new Backend({ name: 'grpc-grpc-invalid', target: 'http-me.fastly.dev', httpKeepalive: NaN, }), cacheOverride: new CacheOverride('pass'), }); }, RangeError); }); routes.set('/backend/constructor/http-keepalive', async () => { await fetch('https://http-me.fastly.dev/anything', { backend: new Backend({ name: 'grpc-grpc-invalid', target: 'http-me.fastly.dev', httpKeepalive: 500, }), cacheOverride: new CacheOverride('pass'), }); }); } // tcpKeepalive { routes.set('/backend/constructor/tcp-keepalive-invalid', async () => { await assertRejects(async () => { await fetch('https://http-me.fastly.dev/anything', { backend: new Backend({ name: 'grpc-grpc-invalid', target: 'http-me.fastly.dev', tcpKeepalive: 'blah', }), cacheOverride: new CacheOverride('pass'), }); }, TypeError); await assertRejects(async () => { await fetch('https://http-me.fastly.dev/anything', { backend: new Backend({ name: 'grpc-grpc-invalid', target: 'http-me.fastly.dev', tcpKeepalive: { intervalSecs: 'boo', }, }), cacheOverride: new CacheOverride('pass'), }); }, RangeError); }); routes.set('/backend/constructor/tcp-keepalive', async () => { await fetch('https://http-me.fastly.dev/anything', { backend: new Backend({ name: 'grpc-grpc-invalid', target: 'http-me.fastly.dev', tcpKeepalive: { intervalSecs: 1000, probes: 4, }, }), cacheOverride: new CacheOverride('pass'), }); }); } } // setDefaultDynamicBackendConfig { routes.set('/backend/set-default-backend-configuration', async () => { if (isRunningLocally()) { return; } setDefaultDynamicBackendConfig({ firstByteTimeout: 1_000, useSSL: true, }); const backend = new Backend({ name: 'new-default', target: 'http-me.fastly.dev', }); console.time(`fetch('https://http-me.fastly.dev/test?wait=2000'`); await assertRejects( () => fetch('https://http-me.fastly.dev/test?wait=2000', { backend, cacheOverride: new CacheOverride('pass'), }), DOMException, 'HTTP response timeout', ); console.timeEnd(`fetch('https://http-me.fastly.dev/test?wait=2000'`); }); } // exists { routes.set('/backend/exists/called-as-constructor-function', async () => { assertThrows( () => { new Backend.exists(); }, TypeError, `Backend.exists is not a constructor`, ); }); routes.set('/backend/exists/empty-parameter', async () => { assertThrows( () => { Backend.exists(); }, TypeError, `Backend.exists: At least 1 argument required, but only 0 passed`, ); }); // https://tc39.es/ecma262/#sec-tostring routes.set('/backend/exists/parameter-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const name = { toString() { throw sentinel; }, }; Backend.exists(name); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => Backend.exists(Symbol()), TypeError, `can't convert symbol to string`, ); }); routes.set('/backend/exists/parameter-invalid', async () => { // null assertThrows(() => Backend.exists(null), TypeError); // undefined assertThrows(() => Backend.exists(undefined), TypeError); // .length > 254 assertThrows(() => Backend.exists('a'.repeat(255)), TypeError); // .length == 0 assertThrows(() => Backend.exists(''), TypeError); }); routes.set('/backend/exists/happy-path-backend-exists', async () => { assert(Backend.exists('TheOrigin'), true, `Backend.exists('TheOrigin')`); }); routes.set( '/backend/exists/happy-path-backend-does-not-exist', async () => { assert(Backend.exists('meow'), false, `Backend.exists('meow')`); }, ); } // fromName { routes.set('/backend/fromName/called-as-constructor-function', async () => { assertThrows( () => { new Backend.fromName(); }, TypeError, `Backend.fromName is not a constructor`, ); }); routes.set('/backend/fromName/empty-parameter', async () => { assertThrows( () => { Backend.fromName(); }, TypeError, `Backend.fromName: At least 1 argument required, but only 0 passed`, ); }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/backend/fromName/parameter-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const name = { toString() { throw sentinel; }, }; Backend.fromName(name); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => Backend.fromName(Symbol()), TypeError, `can't convert symbol to string`, ); }, ); routes.set('/backend/fromName/parameter-invalid', async () => { // null assertThrows(() => Backend.fromName(null), TypeError); // undefined assertThrows(() => Backend.fromName(undefined), TypeError); // .length > 254 assertThrows(() => Backend.fromName('a'.repeat(255)), TypeError); // .length == 0 assertThrows(() => Backend.fromName(''), TypeError); }); routes.set('/backend/fromName/happy-path-backend-exists', async () => { allowDynamicBackends(false); assert( Backend.fromName('TheOrigin') instanceof Backend, true, `Backend.fromName('TheOrigin') instanceof Backend`, ); await assertResolves(() => fetch('https://http-me.fastly.dev/headers', { backend: Backend.fromName('TheOrigin'), }), ); }); routes.set( '/backend/fromName/happy-path-backend-does-not-exist', async () => { assertThrows( () => Backend.fromName('meow'), Error, "Backend.fromName: backend named 'meow' does not exist", ); }, ); } // health { routes.set('/backend/health/called-as-constructor-function', async () => { assertThrows(() => { new Backend.health(); }, TypeError); }); routes.set('/backend/health/empty-parameter', async () => { assertThrows( () => { Backend.health(); }, TypeError, `Backend.health: At least 1 argument required, but only 0 passed`, ); }); // https://tc39.es/ecma262/#sec-tostring routes.set('/backend/health/parameter-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const name = { toString() { throw sentinel; }, }; Backend.health(name); }; assertThrows(test); try { test(); } catch (thrownError) { assert(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => Backend.health(Symbol()), TypeError, `can't convert symbol to string`, ); }); routes.set('/backend/health/parameter-invalid', async () => { // null assertThrows(() => Backend.health(null), TypeError); // undefined assertThrows(() => Backend.health(undefined), TypeError); // .length > 254 assertThrows(() => Backend.health('a'.repeat(255)), TypeError); // .length == 0 assertThrows(() => Backend.health(''), TypeError); }); routes.set('/backend/health/happy-path-backend-exists', async () => { assert( typeof Backend.health('TheOrigin'), 'string', "typeof Backend.health('TheOrigin')", ); assert( Backend.health('TheOrigin'), 'unknown', "Backend.health('TheOrigin')", ); }); routes.set( '/backend/health/happy-path-backend-does-not-exist', async () => { assertThrows( () => Backend.health('meow'), Error, "Backend.health: backend named 'meow' does not exist", ); }, ); } // backend props routes.set('/backend/props', async () => { allowDynamicBackends(true); { const backend = createValidFastlyBackend() ?? validFastlyBackend; strictEqual(backend.isDynamic, true, 'isDymamic'); strictEqual(backend.name, 'fastly'); strictEqual(backend.toString(), 'fastly'); strictEqual(backend.toName(), 'fastly'); strictEqual(backend.health(), 'unknown'); strictEqual(backend.target, 'www.fastly.com', 'target'); strictEqual(backend.hostOverride, 'www.fastly.com', 'override'); strictEqual(backend.port, 443, 'port'); if (isRunningLocally()) { strictEqual(backend.connectTimeout, null, 'connectTimeout'); strictEqual(backend.firstByteTimeout, null, 'firstByteTimeout'); strictEqual(backend.betweenBytesTimeout, null, 'betweenBytesTimeout'); strictEqual(backend.httpKeepaliveTime, 0, 'httpKeepaliveTime'); strictEqual(backend.tcpKeepalive, null, 'tcpKeepalive'); strictEqual(backend.isSSL, true, 'isSSL'); strictEqual(backend.tlsMinVersion, null, 'tlsMinVersion'); strictEqual(backend.tlsMaxVersion, null, 'tlsMaxVersion'); } else { strictEqual(backend.connectTimeout, 1000, 'connectTimeout'); strictEqual(backend.firstByteTimeout, 15000, 'firstByteTimeout'); strictEqual(backend.betweenBytesTimeout, 10000, 'betweenBytesTimeout'); strictEqual(backend.httpKeepaliveTime, 600000, 'httpKeepaliveTime'); deepStrictEqual( backend.tcpKeepalive, { timeSecs: 1, probes: 1, intervalSecs: 10, }, 'tcpKeepalive', ); strictEqual(backend.isSSL, true, 'isSSL'); strictEqual(backend.tlsMinVersion, null, 'tlsMinVersion'); strictEqual(backend.tlsMaxVersion, null, 'tlsMaxVersion'); } } { const backend = createValidHttpMeBackend() ?? validHttpMeBackend; strictEqual(backend.isDynamic, true, 'isDynamic'); strictEqual(backend.name, 'http-me'); strictEqual(backend.toString(), 'http-me'); strictEqual(backend.toName(), 'http-me'); strictEqual(backend.health(), 'unknown'); strictEqual(backend.target, 'http-me.fastly.dev', 'target'); strictEqual(backend.hostOverride, 'http-me.fastly.dev', 'hostOverride'); strictEqual(backend.port, 443, 'port'); if (isRunningLocally()) { strictEqual(backend.connectTimeout, null, 'connectTimeout'); strictEqual(backend.firstByteTimeout, null, 'firstByteTimeout'); strictEqual(backend.betweenBytesTimeout, null, 'betweenBytesTimeout'); strictEqual(backend.httpKeepaliveTime, 0, 'httpKeepaliveTime'); strictEqual(backend.tcpKeepalive, null, 'tcpKeepalive'); strictEqual(backend.isSSL, true, 'isSSL'); strictEqual(backend.tlsMinVersion, null, 'tlsMinVersion'); strictEqual(backend.tlsMaxVersion, null, 'tlsMaxVersion'); } else { strictEqual(backend.connectTimeout, 1000, 'connectTimeout'); strictEqual(backend.firstByteTimeout, 180000, 'firstByteTimeout'); strictEqual(backend.betweenBytesTimeout, 9000, 'betweenBytesTimeout'); strictEqual(backend.httpKeepaliveTime, 600000, 'httpKeepaliveTime'); deepStrictEqual( backend.tcpKeepalive, { intervalSecs: 10, timeSecs: 300, probes: 3, }, 'tcpKeepalive', ); strictEqual(backend.isSSL, true, 'isSSL'); strictEqual(backend.tlsMinVersion, 1.2, 'tlsMinVersion'); strictEqual(backend.tlsMaxVersion, 1.2, 'tlsMaxVersion'); } } }); // ip & port routes.set('/backend/port-ip-defined', async () => { allowDynamicBackends(true); const res = await fetch('https://http-me.fastly.dev/headers', { cacheOverride: new CacheOverride('pass'), }); ok(res.port > 0); ok(res.ip.split('.').length > 1 || res.ip.split(':').length > 1); }); routes.set('/backend/port-ip-cached', async () => { allowDynamicBackends(true); const res = await fetch('https://http-me.fastly.dev/headers'); strictEqual(res.port, undefined); strictEqual(res.ip, undefined); }); } let validHttpMeBackend; function createValidHttpMeBackend() { if (validHttpMeBackend) return; // We are defining all the possible fields here but any number of fields can be defined - the ones which are not defined will use their default value instead. return (validHttpMeBackend = new Backend({ name: 'http-me', target: 'http-me.fastly.dev', hostOverride: 'http-me.fastly.dev', connectTimeout: 1000, firstByteTimeout: 180000, betweenBytesTimeout: 9000, useSSL: true, dontPool: false, tlsMinVersion: 1.2, tlsMaxVersion: 1.2, certificateHostname: 'http-me.fastly.dev', // Colon-delimited list of permitted SSL Ciphers ciphers: 'ECDHE-RSA-AES128-GCM-SHA256:!RC4', sniHostname: 'http-me.fastly.dev', })); } let validFastlyBackend; function createValidFastlyBackend() { if (validFastlyBackend) return; return (validFastlyBackend = new Backend({ name: 'fastly', target: 'www.fastly.com', hostOverride: 'www.fastly.com', useSSL: true, dontPool: true, tcpKeepalive: { timeSecs: 1, probes: 1, }, })); } ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/hello-world.js ================================================ import { routes } from './routes'; routes.set('/hello-world', (evt) => { console.log(evt.request); const res = new Response('hello world'); return res; }); ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/hono.js ================================================ import { routes } from './routes.js'; import { allowDynamicBackends } from 'fastly:experimental'; routes.set('/hono', async (evt) => { const app = new Hono2(); const REALIP = '1.2.3.4'; const HONO_TAG = 'hono'; const REAL_HDR = 'real-hdr'; const xdeviceid = 'device-id'; allowDynamicBackends(true); app.get('/hono', async (c) => { const newRequest = new Request( 'https://http-me.fastly.dev/anything', c.req.raw, ); newRequest.headers.set('X-Connecting-IP', `${REALIP}`); newRequest.headers.set(`${REAL_HDR}`, `${REALIP}`); let cacheOverride = new CacheOverride('pass'); newRequest.headers.set('Cache-Control', 'no-cache'); newRequest.headers.set('Surrogate-Control', 'maxage=0'); if (xdeviceid === true) { newRequest.headers.set('X-KnownDevice', '1'); } else { newRequest.headers.set('X-KnownDevice', '0'); } console.log('a', newRequest.backend); const res = await fetch(newRequest, { cacheOverride }); const newResponse = new Response(res.body, res); if (c.req.header('Fastly-Debug') === 'bw-fastly-debug') { newResponse.headers.set('X-Connecting-IP', `${REALIP}`); newResponse.headers.set('X-Custom-Router', `${HONO_TAG}`); newResponse.headers.set('X-Service-Version', fastly.sdkVersion); newResponse.headers.set('X-KnownDevice', `${xdeviceid}`); } return newResponse; }); return app.dispatch(evt.request, evt, void 0, evt.request.method); }); // node_modules/hono/dist/utils/body.js var parseBody = async ( request, options = /* @__PURE__ */ Object.create(null), ) => { const { all = false, dot = false } = options; const headers = request instanceof HonoRequest ? request.raw.headers : request.headers; const contentType = headers.get('Content-Type'); if ( (contentType !== null && contentType.startsWith('multipart/form-data')) || (contentType !== null && contentType.startsWith('application/x-www-form-urlencoded')) ) { return parseFormData(request, { all, dot }); } return {}; }; async function parseFormData(request, options) { const formData = await request.formData(); if (formData) { return convertFormDataToBodyData(formData, options); } return {}; } function convertFormDataToBodyData(formData, options) { const form = /* @__PURE__ */ Object.create(null); formData.forEach((value, key) => { const shouldParseAllValues = options.all || key.endsWith('[]'); if (!shouldParseAllValues) { form[key] = value; } else { handleParsingAllValues(form, key, value); } }); if (options.dot) { Object.entries(form).forEach(([key, value]) => { const shouldParseDotValues = key.includes('.'); if (shouldParseDotValues) { handleParsingNestedValues(form, key, value); delete form[key]; } }); } return form; } var handleParsingAllValues = (form, key, value) => { if (form[key] !== void 0) { if (Array.isArray(form[key])) { form[key].push(value); } else { form[key] = [form[key], value]; } } else { form[key] = value; } }; var handleParsingNestedValues = (form, key, value) => { let nestedForm = form; const keys = key.split('.'); keys.forEach((key2, index) => { if (index === keys.length - 1) { nestedForm[key2] = value; } else { if ( !nestedForm[key2] || typeof nestedForm[key2] !== 'object' || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File ) { nestedForm[key2] = /* @__PURE__ */ Object.create(null); } nestedForm = nestedForm[key2]; } }); }; // node_modules/hono/dist/utils/url.js var splitPath = (path) => { const paths = path.split('/'); if (paths[0] === '') { paths.shift(); } return paths; }; var splitRoutingPath = (routePath) => { const { groups, path } = extractGroupsFromPath(routePath); const paths = splitPath(path); return replaceGroupMarks(paths, groups); }; var extractGroupsFromPath = (path) => { const groups = []; path = path.replace(/\{[^}]+\}/g, (match, index) => { const mark = `@${index}`; groups.push([mark, match]); return mark; }); return { groups, path }; }; var replaceGroupMarks = (paths, groups) => { for (let i = groups.length - 1; i >= 0; i--) { const [mark] = groups[i]; for (let j = paths.length - 1; j >= 0; j--) { if (paths[j].includes(mark)) { paths[j] = paths[j].replace(mark, groups[i][1]); break; } } } return paths; }; var patternCache = {}; var getPattern = (label) => { if (label === '*') { return '*'; } const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); if (match) { if (!patternCache[label]) { if (match[2]) { patternCache[label] = [ label, match[1], new RegExp('^' + match[2] + '$'), ]; } else { patternCache[label] = [label, match[1], true]; } } return patternCache[label]; } return null; }; var tryDecodeURI = (str) => { try { return decodeURI(str); } catch { return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => { try { return decodeURI(match); } catch { return match; } }); } }; var getPath = (request) => { const url = request.url; const start = url.indexOf('/', 8); let i = start; for (; i < url.length; i++) { const charCode = url.charCodeAt(i); if (charCode === 37) { const queryIndex = url.indexOf('?', i); const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex); return tryDecodeURI( path.includes('%25') ? path.replace(/%25/g, '%2525') : path, ); } else if (charCode === 63) { break; } } return url.slice(start, i); }; var getPathNoStrict = (request) => { const result = getPath(request); return result.length > 1 && result[result.length - 1] === '/' ? result.slice(0, -1) : result; }; var mergePath = (...paths) => { let p = ''; let endsWithSlash = false; for (let path of paths) { if (p[p.length - 1] === '/') { p = p.slice(0, -1); endsWithSlash = true; } if (path[0] !== '/') { path = `/${path}`; } if (path === '/' && endsWithSlash) { p = `${p}/`; } else if (path !== '/') { p = `${p}${path}`; } if (path === '/' && p === '') { p = '/'; } } return p; }; var checkOptionalParameter = (path) => { if (!path.match(/\:.+\?$/)) { return null; } const segments = path.split('/'); const results = []; let basePath = ''; segments.forEach((segment) => { if (segment !== '' && !/\:/.test(segment)) { basePath += '/' + segment; } else if (/\:/.test(segment)) { if (/\?/.test(segment)) { if (results.length === 0 && basePath === '') { results.push('/'); } else { results.push(basePath); } const optionalSegment = segment.replace('?', ''); basePath += '/' + optionalSegment; results.push(basePath); } else { basePath += '/' + segment; } } }); return results.filter((v, i, a) => a.indexOf(v) === i); }; var _decodeURI = (value) => { if (!/[%+]/.test(value)) { return value; } if (value.indexOf('+') !== -1) { value = value.replace(/\+/g, ' '); } return /%/.test(value) ? decodeURIComponent_(value) : value; }; var _getQueryParam = (url, key, multiple) => { let encoded; if (!multiple && key && !/[%+]/.test(key)) { let keyIndex2 = url.indexOf(`?${key}`, 8); if (keyIndex2 === -1) { keyIndex2 = url.indexOf(`&${key}`, 8); } while (keyIndex2 !== -1) { const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1); if (trailingKeyCode === 61) { const valueIndex = keyIndex2 + key.length + 2; const endIndex = url.indexOf('&', valueIndex); return _decodeURI( url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex), ); } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) { return ''; } keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); } encoded = /[%+]/.test(url); if (!encoded) { return void 0; } } const results = {}; encoded ??= /[%+]/.test(url); let keyIndex = url.indexOf('?', 8); while (keyIndex !== -1) { const nextKeyIndex = url.indexOf('&', keyIndex + 1); let valueIndex = url.indexOf('=', keyIndex); if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) { valueIndex = -1; } let name = url.slice( keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex, ); if (encoded) { name = _decodeURI(name); } keyIndex = nextKeyIndex; if (name === '') { continue; } let value; if (valueIndex === -1) { value = ''; } else { value = url.slice( valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex, ); if (encoded) { value = _decodeURI(value); } } if (multiple) { if (!(results[name] && Array.isArray(results[name]))) { results[name] = []; } results[name].push(value); } else { results[name] ??= value; } } return key ? results[key] : results; }; var getQueryParam = _getQueryParam; var getQueryParams = (url, key) => { return _getQueryParam(url, key, true); }; var decodeURIComponent_ = decodeURIComponent; // node_modules/hono/dist/request.js var HonoRequest = class { raw; #validatedData; #matchResult; routeIndex = 0; path; bodyCache = {}; constructor(request, path = '/', matchResult = [[]]) { this.raw = request; this.path = path; this.#matchResult = matchResult; this.#validatedData = {}; } param(key) { return key ? this.getDecodedParam(key) : this.getAllDecodedParams(); } getDecodedParam(key) { const paramKey = this.#matchResult[0][this.routeIndex][1][key]; const param = this.getParamValue(paramKey); return param ? /\%/.test(param) ? decodeURIComponent_(param) : param : void 0; } getAllDecodedParams() { const decoded = {}; const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]); for (const key of keys) { const value = this.getParamValue( this.#matchResult[0][this.routeIndex][1][key], ); if (value && typeof value === 'string') { decoded[key] = /\%/.test(value) ? decodeURIComponent_(value) : value; } } return decoded; } getParamValue(paramKey) { return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey; } query(key) { return getQueryParam(this.url, key); } queries(key) { return getQueryParams(this.url, key); } header(name) { if (name) { return this.raw.headers.get(name.toLowerCase()) ?? void 0; } const headerData = {}; this.raw.headers.forEach((value, key) => { headerData[key] = value; }); return headerData; } async parseBody(options) { return (this.bodyCache.parsedBody ??= await parseBody(this, options)); } cachedBody = (key) => { const { bodyCache, raw: raw2 } = this; const cachedBody = bodyCache[key]; if (cachedBody) { return cachedBody; } const anyCachedKey = Object.keys(bodyCache)[0]; if (anyCachedKey) { return bodyCache[anyCachedKey].then((body) => { if (anyCachedKey === 'json') { body = JSON.stringify(body); } return new Response(body)[key](); }); } return (bodyCache[key] = raw2[key]()); }; json() { return this.cachedBody('json'); } text() { return this.cachedBody('text'); } arrayBuffer() { return this.cachedBody('arrayBuffer'); } blob() { return this.cachedBody('blob'); } formData() { return this.cachedBody('formData'); } addValidatedData(target, data) { this.#validatedData[target] = data; } valid(target) { return this.#validatedData[target]; } get url() { return this.raw.url; } get method() { return this.raw.method; } get matchedRoutes() { return this.#matchResult[0].map(([[, route]]) => route); } get routePath() { return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex] .path; } }; // node_modules/hono/dist/utils/html.js var HtmlEscapedCallbackPhase = { Stringify: 1, BeforeStream: 2, Stream: 3, }; var raw = (value, callbacks) => { const escapedString = new String(value); escapedString.isEscaped = true; escapedString.callbacks = callbacks; return escapedString; }; var resolveCallback = async ( str, phase, preserveCallbacks, context, buffer, ) => { const callbacks = str.callbacks; if (!callbacks?.length) { return Promise.resolve(str); } if (buffer) { buffer[0] += str; } else { buffer = [str]; } const resStr = Promise.all( callbacks.map((c) => c({ phase, buffer, context })), ).then((res) => Promise.all( res .filter(Boolean) .map((str2) => resolveCallback(str2, phase, false, context, buffer)), ).then(() => buffer[0]), ); if (preserveCallbacks) { return raw(await resStr, callbacks); } else { return resStr; } }; // node_modules/hono/dist/context.js var TEXT_PLAIN = 'text/plain; charset=UTF-8'; var setHeaders = (headers, map = {}) => { Object.entries(map).forEach(([key, value]) => headers.set(key, value)); return headers; }; var Context = class { #rawRequest; #req; env = {}; #var; finalized = false; error; #status = 200; #executionCtx; #headers; #preparedHeaders; #res; #isFresh = true; #layout; #renderer; #notFoundHandler; #matchResult; #path; constructor(req, options) { this.#rawRequest = req; if (options) { this.#executionCtx = options.executionCtx; this.env = options.env; this.#notFoundHandler = options.notFoundHandler; this.#path = options.path; this.#matchResult = options.matchResult; } } get req() { this.#req ??= new HonoRequest( this.#rawRequest, this.#path, this.#matchResult, ); return this.#req; } get event() { if (this.#executionCtx && 'respondWith' in this.#executionCtx) { return this.#executionCtx; } else { throw Error('This context has no FetchEvent'); } } get executionCtx() { if (this.#executionCtx) { return this.#executionCtx; } else { throw Error('This context has no ExecutionContext'); } } get res() { this.#isFresh = false; return (this.#res ||= new Response('404 Not Found', { status: 404 })); } set res(_res) { this.#isFresh = false; if (this.#res && _res) { this.#res.headers.delete('content-type'); for (const [k, v] of this.#res.headers.entries()) { if (k === 'set-cookie') { const cookies = this.#res.headers.getSetCookie(); _res.headers.delete('set-cookie'); for (const cookie of cookies) { _res.headers.append('set-cookie', cookie); } } else { _res.headers.set(k, v); } } } this.#res = _res; this.finalized = true; } render = (...args) => { this.#renderer ??= (content) => this.html(content); return this.#renderer(...args); }; setLayout = (layout) => (this.#layout = layout); getLayout = () => this.#layout; setRenderer = (renderer) => { this.#renderer = renderer; }; header = (name, value, options) => { if (value === void 0) { if (this.#headers) { this.#headers.delete(name); } else if (this.#preparedHeaders) { delete this.#preparedHeaders[name.toLocaleLowerCase()]; } if (this.finalized) { this.res.headers.delete(name); } return; } if (options?.append) { if (!this.#headers) { this.#isFresh = false; this.#headers = new Headers(this.#preparedHeaders); this.#preparedHeaders = {}; } this.#headers.append(name, value); } else { if (this.#headers) { this.#headers.set(name, value); } else { this.#preparedHeaders ??= {}; this.#preparedHeaders[name.toLowerCase()] = value; } } if (this.finalized) { if (options?.append) { this.res.headers.append(name, value); } else { this.res.headers.set(name, value); } } }; status = (status) => { this.#isFresh = false; this.#status = status; }; set = (key, value) => { this.#var ??= /* @__PURE__ */ new Map(); this.#var.set(key, value); }; get = (key) => { return this.#var ? this.#var.get(key) : void 0; }; get var() { if (!this.#var) { return {}; } return Object.fromEntries(this.#var); } newResponse = (data, arg, headers) => { if (this.#isFresh && !headers && !arg && this.#status === 200) { return new Response(data, { headers: this.#preparedHeaders, }); } if (arg && typeof arg !== 'number') { const header = new Headers(arg.headers); if (this.#headers) { this.#headers.forEach((v, k) => { if (k === 'set-cookie') { header.append(k, v); } else { header.set(k, v); } }); } const headers2 = setHeaders(header, this.#preparedHeaders); return new Response(data, { headers: headers2, status: arg.status ?? this.#status, }); } const status = typeof arg === 'number' ? arg : this.#status; this.#preparedHeaders ??= {}; this.#headers ??= new Headers(); setHeaders(this.#headers, this.#preparedHeaders); if (this.#res) { this.#res.headers.forEach((v, k) => { if (k === 'set-cookie') { this.#headers?.append(k, v); } else { this.#headers?.set(k, v); } }); setHeaders(this.#headers, this.#preparedHeaders); } headers ??= {}; for (const [k, v] of Object.entries(headers)) { if (typeof v === 'string') { this.#headers.set(k, v); } else { this.#headers.delete(k); for (const v2 of v) { this.#headers.append(k, v2); } } } return new Response(data, { status, headers: this.#headers, }); }; body = (data, arg, headers) => { return typeof arg === 'number' ? this.newResponse(data, arg, headers) : this.newResponse(data, arg); }; text = (text, arg, headers) => { if (!this.#preparedHeaders) { if (this.#isFresh && !headers && !arg) { return new Response(text); } this.#preparedHeaders = {}; } this.#preparedHeaders['content-type'] = TEXT_PLAIN; return typeof arg === 'number' ? this.newResponse(text, arg, headers) : this.newResponse(text, arg); }; json = (object, arg, headers) => { const body = JSON.stringify(object); this.#preparedHeaders ??= {}; this.#preparedHeaders['content-type'] = 'application/json; charset=UTF-8'; return typeof arg === 'number' ? this.newResponse(body, arg, headers) : this.newResponse(body, arg); }; html = (html, arg, headers) => { this.#preparedHeaders ??= {}; this.#preparedHeaders['content-type'] = 'text/html; charset=UTF-8'; if (typeof html === 'object') { if (!(html instanceof Promise)) { html = html.toString(); } if (html instanceof Promise) { return html .then((html2) => resolveCallback( html2, HtmlEscapedCallbackPhase.Stringify, false, {}, ), ) .then((html2) => { return typeof arg === 'number' ? this.newResponse(html2, arg, headers) : this.newResponse(html2, arg); }); } } return typeof arg === 'number' ? this.newResponse(html, arg, headers) : this.newResponse(html, arg); }; redirect = (location, status) => { this.#headers ??= new Headers(); this.#headers.set('Location', location); return this.newResponse(null, status ?? 302); }; notFound = () => { this.#notFoundHandler ??= () => new Response(); return this.#notFoundHandler(this); }; }; // node_modules/hono/dist/compose.js var compose = (middleware, onError, onNotFound) => { return (context, next) => { let index = -1; return dispatch(0); async function dispatch(i) { if (i <= index) { throw new Error('next() called multiple times'); } index = i; let res; let isError = false; let handler; if (middleware[i]) { handler = middleware[i][0][0]; if (context instanceof Context) { context.req.routeIndex = i; } } else { handler = (i === middleware.length && next) || void 0; } if (!handler) { if ( context instanceof Context && context.finalized === false && onNotFound ) { res = await onNotFound(context); } } else { try { res = await handler(context, () => { return dispatch(i + 1); }); } catch (err) { if (err instanceof Error && context instanceof Context && onError) { context.error = err; res = await onError(err, context); isError = true; } else { throw err; } } } if (res && (context.finalized === false || isError)) { context.res = res; } return context; } }; }; // node_modules/hono/dist/router.js var METHOD_NAME_ALL = 'ALL'; var METHOD_NAME_ALL_LOWERCASE = 'all'; var METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch']; var MESSAGE_MATCHER_IS_ALREADY_BUILT = 'Can not add a route since the matcher is already built.'; var UnsupportedPathError = class extends Error {}; // node_modules/hono/dist/hono-base.js var COMPOSED_HANDLER = Symbol('composedHandler'); var notFoundHandler = (c) => { return c.text('404 Not Found', 404); }; var errorHandler = (err, c) => { if ('getResponse' in err) { return err.getResponse(); } console.error(err); return c.text('Internal Server Error', 500); }; var Hono = class { get; post; put; delete; options; patch; all; on; use; router; getPath; _basePath = '/'; #path = '/'; routes = []; constructor(options = {}) { const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]; allMethods.forEach((method) => { this[method] = (args1, ...args) => { if (typeof args1 === 'string') { this.#path = args1; } else { this.addRoute(method, this.#path, args1); } args.forEach((handler) => { if (typeof handler !== 'string') { this.addRoute(method, this.#path, handler); } }); return this; }; }); this.on = (method, path, ...handlers) => { for (const p of [path].flat()) { this.#path = p; for (const m of [method].flat()) { handlers.map((handler) => { this.addRoute(m.toUpperCase(), this.#path, handler); }); } } return this; }; this.use = (arg1, ...handlers) => { if (typeof arg1 === 'string') { this.#path = arg1; } else { this.#path = '*'; handlers.unshift(arg1); } handlers.forEach((handler) => { this.addRoute(METHOD_NAME_ALL, this.#path, handler); }); return this; }; const strict = options.strict ?? true; delete options.strict; Object.assign(this, options); this.getPath = strict ? (options.getPath ?? getPath) : getPathNoStrict; } clone() { const clone = new Hono({ router: this.router, getPath: this.getPath, }); clone.routes = this.routes; return clone; } notFoundHandler = notFoundHandler; errorHandler = errorHandler; route(path, app) { const subApp = this.basePath(path); app.routes.map((r) => { let handler; if (app.errorHandler === errorHandler) { handler = r.handler; } else { handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))) .res; handler[COMPOSED_HANDLER] = r.handler; } subApp.addRoute(r.method, r.path, handler); }); return this; } basePath(path) { const subApp = this.clone(); subApp._basePath = mergePath(this._basePath, path); return subApp; } onError = (handler) => { this.errorHandler = handler; return this; }; notFound = (handler) => { this.notFoundHandler = handler; return this; }; mount(path, applicationHandler, options) { let replaceRequest; let optionHandler; if (options) { if (typeof options === 'function') { optionHandler = options; } else { optionHandler = options.optionHandler; replaceRequest = options.replaceRequest; } } const getOptions = optionHandler ? (c) => { const options2 = optionHandler(c); return Array.isArray(options2) ? options2 : [options2]; } : (c) => { let executionContext = void 0; try { executionContext = c.executionCtx; } catch {} return [c.env, executionContext]; }; replaceRequest ||= (() => { const mergedPath = mergePath(this._basePath, path); const pathPrefixLength = mergedPath === '/' ? 0 : mergedPath.length; return (request) => { const url = new URL(request.url); url.pathname = url.pathname.slice(pathPrefixLength) || '/'; return new Request(url, request); }; })(); const handler = async (c, next) => { const res = await applicationHandler( replaceRequest(c.req.raw), ...getOptions(c), ); if (res) { return res; } await next(); }; this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler); return this; } addRoute(method, path, handler) { method = method.toUpperCase(); path = mergePath(this._basePath, path); const r = { path, method, handler }; this.router.add(method, path, [handler, r]); this.routes.push(r); } matchRoute(method, path) { return this.router.match(method, path); } handleError(err, c) { if (err instanceof Error) { return this.errorHandler(err, c); } throw err; } dispatch(request, executionCtx, env, method) { if (method === 'HEAD') { return (async () => new Response( null, await this.dispatch(request, executionCtx, env, 'GET'), ))(); } const path = this.getPath(request, { env }); const matchResult = this.matchRoute(method, path); const c = new Context(request, { path, matchResult, env, executionCtx, notFoundHandler: this.notFoundHandler, }); if (matchResult[0].length === 1) { let res; try { res = matchResult[0][0][0][0](c, async () => { c.res = await this.notFoundHandler(c); }); } catch (err) { return this.handleError(err, c); } return res instanceof Promise ? res .then( (resolved) => resolved || (c.finalized ? c.res : this.notFoundHandler(c)), ) .catch((err) => this.handleError(err, c)) : (res ?? this.notFoundHandler(c)); } const composed = compose( matchResult[0], this.errorHandler, this.notFoundHandler, ); return (async () => { try { const context = await composed(c); if (!context.finalized) { throw new Error( 'Context is not finalized. Did you forget to return a Response object or `await next()`?', ); } return context.res; } catch (err) { return this.handleError(err, c); } })(); } fetch = (request, ...rest) => { return this.dispatch(request, rest[1], rest[0], request.method); }; request = (input, requestInit, Env, executionCtx) => { if (input instanceof Request) { if (requestInit !== void 0) { input = new Request(input, requestInit); } return this.fetch(input, Env, executionCtx); } input = input.toString(); const path = /^https?:\/\//.test(input) ? input : `http://localhost${mergePath('/', input)}`; const req = new Request(path, requestInit); return this.fetch(req, Env, executionCtx); }; fire = () => { addEventListener('fetch', (event) => { event.respondWith( this.dispatch(event.request, event, void 0, event.request.method), ); }); }; }; // node_modules/hono/dist/router/reg-exp-router/node.js var LABEL_REG_EXP_STR = '[^/]+'; var ONLY_WILDCARD_REG_EXP_STR = '.*'; var TAIL_WILDCARD_REG_EXP_STR = '(?:|/.*)'; var PATH_ERROR = Symbol(); var regExpMetaChars = new Set('.\\+*[^]$()'); function compareKey(a, b) { if (a.length === 1) { return b.length === 1 ? (a < b ? -1 : 1) : -1; } if (b.length === 1) { return 1; } if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) { return 1; } else if ( b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR ) { return -1; } if (a === LABEL_REG_EXP_STR) { return 1; } else if (b === LABEL_REG_EXP_STR) { return -1; } return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length; } var Node = class { index; varIndex; children = /* @__PURE__ */ Object.create(null); insert(tokens, index, paramMap, context, pathErrorCheckOnly) { if (tokens.length === 0) { if (this.index !== void 0) { throw PATH_ERROR; } if (pathErrorCheckOnly) { return; } this.index = index; return; } const [token, ...restTokens] = tokens; const pattern = token === '*' ? restTokens.length === 0 ? ['', '', ONLY_WILDCARD_REG_EXP_STR] : ['', '', LABEL_REG_EXP_STR] : token === '/*' ? ['', '', TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); let node; if (pattern) { const name = pattern[1]; let regexpStr = pattern[2] || LABEL_REG_EXP_STR; if (name && pattern[2]) { regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, '(?:'); if (/\((?!\?:)/.test(regexpStr)) { throw PATH_ERROR; } } node = this.children[regexpStr]; if (!node) { if ( Object.keys(this.children).some( (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR, ) ) { throw PATH_ERROR; } if (pathErrorCheckOnly) { return; } node = this.children[regexpStr] = new Node(); if (name !== '') { node.varIndex = context.varIndex++; } } if (!pathErrorCheckOnly && name !== '') { paramMap.push([name, node.varIndex]); } } else { node = this.children[token]; if (!node) { if ( Object.keys(this.children).some( (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR, ) ) { throw PATH_ERROR; } if (pathErrorCheckOnly) { return; } node = this.children[token] = new Node(); } } node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly); } buildRegExpStr() { const childKeys = Object.keys(this.children).sort(compareKey); const strList = childKeys.map((k) => { const c = this.children[k]; return ( (typeof c.varIndex === 'number' ? `(${k})@${c.varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr() ); }); if (typeof this.index === 'number') { strList.unshift(`#${this.index}`); } if (strList.length === 0) { return ''; } if (strList.length === 1) { return strList[0]; } return '(?:' + strList.join('|') + ')'; } }; // node_modules/hono/dist/router/reg-exp-router/trie.js var Trie = class { context = { varIndex: 0 }; root = new Node(); insert(path, index, pathErrorCheckOnly) { const paramAssoc = []; const groups = []; for (let i = 0; ; ) { let replaced = false; path = path.replace(/\{[^}]+\}/g, (m) => { const mark = `@\\${i}`; groups[i] = [mark, m]; i++; replaced = true; return mark; }); if (!replaced) { break; } } const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []; for (let i = groups.length - 1; i >= 0; i--) { const [mark] = groups[i]; for (let j = tokens.length - 1; j >= 0; j--) { if (tokens[j].indexOf(mark) !== -1) { tokens[j] = tokens[j].replace(mark, groups[i][1]); break; } } } this.root.insert( tokens, index, paramAssoc, this.context, pathErrorCheckOnly, ); return paramAssoc; } buildRegExp() { let regexp = this.root.buildRegExpStr(); if (regexp === '') { return [/^$/, [], []]; } let captureIndex = 0; const indexReplacementMap = []; const paramReplacementMap = []; regexp = regexp.replace( /#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => { if (typeof handlerIndex !== 'undefined') { indexReplacementMap[++captureIndex] = Number(handlerIndex); return '$()'; } if (typeof paramIndex !== 'undefined') { paramReplacementMap[Number(paramIndex)] = ++captureIndex; return ''; } return ''; }, ); return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]; } }; // node_modules/hono/dist/router/reg-exp-router/router.js var emptyParam = []; var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)]; var wildcardRegExpCache = /* @__PURE__ */ Object.create(null); function buildWildcardRegExp(path) { return (wildcardRegExpCache[path] ??= new RegExp( path === '*' ? '' : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : '(?:|/.*)', )}$`, )); } function clearWildcardRegExpCache() { wildcardRegExpCache = /* @__PURE__ */ Object.create(null); } function buildMatcherFromPreprocessedRoutes(routes) { const trie = new Trie(); const handlerData = []; if (routes.length === 0) { return nullMatcher; } const routesWithStaticPathFlag = routes .map((route) => [!/\*|\/:/.test(route[0]), ...route]) .sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length, ); const staticMap = /* @__PURE__ */ Object.create(null); for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) { const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]; if (pathErrorCheckOnly) { staticMap[path] = [ handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam, ]; } else { j++; } let paramAssoc; try { paramAssoc = trie.insert(path, j, pathErrorCheckOnly); } catch (e) { throw e === PATH_ERROR ? new UnsupportedPathError(path) : e; } if (pathErrorCheckOnly) { continue; } handlerData[j] = handlers.map(([h, paramCount]) => { const paramIndexMap = /* @__PURE__ */ Object.create(null); paramCount -= 1; for (; paramCount >= 0; paramCount--) { const [key, value] = paramAssoc[paramCount]; paramIndexMap[key] = value; } return [h, paramIndexMap]; }); } const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp(); for (let i = 0, len = handlerData.length; i < len; i++) { for (let j = 0, len2 = handlerData[i].length; j < len2; j++) { const map = handlerData[i][j]?.[1]; if (!map) { continue; } const keys = Object.keys(map); for (let k = 0, len3 = keys.length; k < len3; k++) { map[keys[k]] = paramReplacementMap[map[keys[k]]]; } } } const handlerMap = []; for (const i in indexReplacementMap) { handlerMap[i] = handlerData[indexReplacementMap[i]]; } return [regexp, handlerMap, staticMap]; } function findMiddleware(middleware, path) { if (!middleware) { return void 0; } for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) { if (buildWildcardRegExp(k).test(path)) { return [...middleware[k]]; } } return void 0; } var RegExpRouter = class { name = 'RegExpRouter'; middleware; routes; constructor() { this.middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null), }; this.routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }; } add(method, path, handler) { const { middleware, routes } = this; if (!middleware || !routes) { throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); } if (!middleware[method]) { [middleware, routes].forEach((handlerMap) => { handlerMap[method] = /* @__PURE__ */ Object.create(null); Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => { handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]; }); }); } if (path === '/*') { path = '*'; } const paramCount = (path.match(/\/:/g) || []).length; if (/\*$/.test(path)) { const re = buildWildcardRegExp(path); if (method === METHOD_NAME_ALL) { Object.keys(middleware).forEach((m) => { middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || []; }); } else { middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || []; } Object.keys(middleware).forEach((m) => { if (method === METHOD_NAME_ALL || method === m) { Object.keys(middleware[m]).forEach((p) => { re.test(p) && middleware[m][p].push([handler, paramCount]); }); } }); Object.keys(routes).forEach((m) => { if (method === METHOD_NAME_ALL || method === m) { Object.keys(routes[m]).forEach( (p) => re.test(p) && routes[m][p].push([handler, paramCount]), ); } }); return; } const paths = checkOptionalParameter(path) || [path]; for (let i = 0, len = paths.length; i < len; i++) { const path2 = paths[i]; Object.keys(routes).forEach((m) => { if (method === METHOD_NAME_ALL || method === m) { routes[m][path2] ||= [ ...(findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []), ]; routes[m][path2].push([handler, paramCount - len + i + 1]); } }); } } match(method, path) { clearWildcardRegExpCache(); const matchers = this.buildAllMatchers(); this.match = (method2, path2) => { const matcher = matchers[method2] || matchers[METHOD_NAME_ALL]; const staticMatch = matcher[2][path2]; if (staticMatch) { return staticMatch; } const match = path2.match(matcher[0]); if (!match) { return [[], emptyParam]; } const index = match.indexOf('', 1); return [matcher[1][index], match]; }; return this.match(method, path); } buildAllMatchers() { const matchers = /* @__PURE__ */ Object.create(null); [...Object.keys(this.routes), ...Object.keys(this.middleware)].forEach( (method) => { matchers[method] ||= this.buildMatcher(method); }, ); this.middleware = this.routes = void 0; return matchers; } buildMatcher(method) { const routes = []; let hasOwnRoute = method === METHOD_NAME_ALL; [this.middleware, this.routes].forEach((r) => { const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : []; if (ownRoute.length !== 0) { hasOwnRoute ||= true; routes.push(...ownRoute); } else if (method !== METHOD_NAME_ALL) { routes.push( ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [ path, r[METHOD_NAME_ALL][path], ]), ); } }); if (!hasOwnRoute) { return null; } else { return buildMatcherFromPreprocessedRoutes(routes); } } }; // node_modules/hono/dist/router/smart-router/router.js var SmartRouter = class { name = 'SmartRouter'; routers = []; routes = []; constructor(init) { Object.assign(this, init); } add(method, path, handler) { if (!this.routes) { throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); } this.routes.push([method, path, handler]); } match(method, path) { if (!this.routes) { throw new Error('Fatal error'); } const { routers, routes } = this; const len = routers.length; let i = 0; let res; for (; i < len; i++) { const router = routers[i]; try { routes.forEach((args) => { router.add(...args); }); res = router.match(method, path); } catch (e) { if (e instanceof UnsupportedPathError) { continue; } throw e; } this.match = router.match.bind(router); this.routers = [router]; this.routes = void 0; break; } if (i === len) { throw new Error('Fatal error'); } this.name = `SmartRouter + ${this.activeRouter.name}`; return res; } get activeRouter() { if (this.routes || this.routers.length !== 1) { throw new Error('No active router has been determined yet.'); } return this.routers[0]; } }; // node_modules/hono/dist/router/trie-router/node.js var Node2 = class { methods; children; patterns; order = 0; name; params = /* @__PURE__ */ Object.create(null); constructor(method, handler, children) { this.children = children || /* @__PURE__ */ Object.create(null); this.methods = []; this.name = ''; if (method && handler) { const m = /* @__PURE__ */ Object.create(null); m[method] = { handler, possibleKeys: [], score: 0, name: this.name }; this.methods = [m]; } this.patterns = []; } insert(method, path, handler) { this.name = `${method} ${path}`; this.order = ++this.order; let curNode = this; const parts = splitRoutingPath(path); const possibleKeys = []; for (let i = 0, len = parts.length; i < len; i++) { const p = parts[i]; if (Object.keys(curNode.children).includes(p)) { curNode = curNode.children[p]; const pattern2 = getPattern(p); if (pattern2) { possibleKeys.push(pattern2[1]); } continue; } curNode.children[p] = new Node2(); const pattern = getPattern(p); if (pattern) { curNode.patterns.push(pattern); possibleKeys.push(pattern[1]); } curNode = curNode.children[p]; } if (!curNode.methods.length) { curNode.methods = []; } const m = /* @__PURE__ */ Object.create(null); const handlerSet = { handler, possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i), name: this.name, score: this.order, }; m[method] = handlerSet; curNode.methods.push(m); return curNode; } gHSets(node, method, nodeParams, params) { const handlerSets = []; for (let i = 0, len = node.methods.length; i < len; i++) { const m = node.methods[i]; const handlerSet = m[method] || m[METHOD_NAME_ALL]; const processedSet = /* @__PURE__ */ Object.create(null); if (handlerSet !== void 0) { handlerSet.params = /* @__PURE__ */ Object.create(null); handlerSet.possibleKeys.forEach((key) => { const processed = processedSet[handlerSet.name]; handlerSet.params[key] = params[key] && !processed ? params[key] : (nodeParams[key] ?? params[key]); processedSet[handlerSet.name] = true; }); handlerSets.push(handlerSet); } } return handlerSets; } search(method, path) { const handlerSets = []; this.params = /* @__PURE__ */ Object.create(null); const curNode = this; let curNodes = [curNode]; const parts = splitPath(path); for (let i = 0, len = parts.length; i < len; i++) { const part = parts[i]; const isLast = i === len - 1; const tempNodes = []; for (let j = 0, len2 = curNodes.length; j < len2; j++) { const node = curNodes[j]; const nextNode = node.children[part]; if (nextNode) { nextNode.params = node.params; if (isLast === true) { if (nextNode.children['*']) { handlerSets.push( ...this.gHSets( nextNode.children['*'], method, node.params, /* @__PURE__ */ Object.create(null), ), ); } handlerSets.push( ...this.gHSets( nextNode, method, node.params, /* @__PURE__ */ Object.create(null), ), ); } else { tempNodes.push(nextNode); } } for (let k = 0, len3 = node.patterns.length; k < len3; k++) { const pattern = node.patterns[k]; const params = { ...node.params }; if (pattern === '*') { const astNode = node.children['*']; if (astNode) { handlerSets.push( ...this.gHSets( astNode, method, node.params, /* @__PURE__ */ Object.create(null), ), ); tempNodes.push(astNode); } continue; } if (part === '') { continue; } const [key, name, matcher] = pattern; const child = node.children[key]; const restPathString = parts.slice(i).join('/'); if (matcher instanceof RegExp && matcher.test(restPathString)) { params[name] = restPathString; handlerSets.push( ...this.gHSets(child, method, node.params, params), ); continue; } if ( matcher === true || (matcher instanceof RegExp && matcher.test(part)) ) { if (typeof key === 'string') { params[name] = part; if (isLast === true) { handlerSets.push( ...this.gHSets(child, method, params, node.params), ); if (child.children['*']) { handlerSets.push( ...this.gHSets( child.children['*'], method, params, node.params, ), ); } } else { child.params = params; tempNodes.push(child); } } } } } curNodes = tempNodes; } const results = handlerSets.sort((a, b) => { return a.score - b.score; }); return [results.map(({ handler, params }) => [handler, params])]; } }; // node_modules/hono/dist/router/trie-router/router.js var TrieRouter = class { name = 'TrieRouter'; node; constructor() { this.node = new Node2(); } add(method, path, handler) { const results = checkOptionalParameter(path); if (results) { for (const p of results) { this.node.insert(method, p, handler); } return; } this.node.insert(method, path, handler); } match(method, path) { return this.node.search(method, path); } }; // node_modules/hono/dist/hono.js var Hono2 = class extends Hono { constructor(options = {}) { super(options); this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()], }); } }; ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/http-cache.js ================================================ /// /* eslint-env serviceworker */ import { assert, strictEqual, deepStrictEqual, assertRejects, } from './assertions.js'; import { routes } from './routes.js'; import { CacheOverride } from 'fastly:cache-override'; // generate a unique URL everytime so that we never work on a populated cache const getTestUrl = (path = `/${Math.random().toString().slice(2)}`) => 'https://http-me.fastly.dev/anything' + path; // afterSend error handling { routes.set('/http-cache/hook-errors', async () => { const url = getTestUrl(); await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ beforeSend() { throw new Error('before send error'); }, }), }), Error, 'before send error', ); await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ afterSend() { throw new Error('after send error'); }, }), }), Error, 'after send error', ); }); // Test invalid property assignments routes.set('/http-cache/invalid-properties', async () => { const url = getTestUrl(); await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ afterSend(res) { res.status = 'invalid'; // Should throw type error }, }), }), RangeError, ); await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ afterSend(res) { res.ttl = 'invalid'; // Should throw type error }, }), }), TypeError, ); }); // Test invalid property assignments routes.set('/http-cache/property-errors', async () => { const url = getTestUrl(); // Test invalid swr assignment await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ afterSend(res) { res.swr = 'invalid'; }, }), }), TypeError, ); // Test invalid vary assignment await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ afterSend(res) { res.vary = new Set(['not-an-array']); }, }), }), TypeError, ); // Test invalid surrogateKeys assignment await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ afterSend(res) { res.surrogateKeys = new Set(['not-an-array']); }, }), }), TypeError, ); // Test invalid pci assignment await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ afterSend(res) { res.pci = 'invalid'; }, }), }), TypeError, ); // Test invalid Set contents for vary await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ afterSend(res) { res.vary = [1, 2, 3]; // Should only accept strings }, }), }), TypeError, ); // Test invalid Set contents for surrogateKeys await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ afterSend(res) { res.surrogateKeys = [1, 2, 3]; // Should only accept strings }, }), }), TypeError, ); }); routes.set('/http-cache/candidate-response-properties-uncached', async () => { const url = getTestUrl(); // Test accessing cache properties on non-cached candidate response // (before and after hooks lifecycle) & response let candidateRes; const cacheOverride = new CacheOverride({ afterSend(res) { candidateRes = res; strictEqual(candidateRes.cached, false); strictEqual(candidateRes.stale, false); strictEqual(candidateRes.ttl, 3600); strictEqual(candidateRes.age, 0); deepStrictEqual(candidateRes.vary, []); strictEqual(candidateRes.surrogateKeys.length, 1); strictEqual(typeof candidateRes.surrogateKeys[0], 'string'); strictEqual(candidateRes.surrogateKeys[0].length > 10, true); return { cache: false }; }, }); const res = await fetch(url, { cacheOverride }); strictEqual(res.cached, false); strictEqual(res.stale, false); strictEqual(res.ttl, 3600); strictEqual(res.age, 0); deepStrictEqual(res.vary, []); strictEqual(res.surrogateKeys.length, 1); strictEqual(typeof res.surrogateKeys[0], 'string'); strictEqual(res.surrogateKeys[0].length > 10, true); // in the do not store / no cache cases, the candidate response is directly // promoted into the response. We could possibly consider reinstancing in future, but // semantically this is what is defined by the caching APIs. assert(res === candidateRes); }); routes.set('/http-cache/candidate-response-properties-cached', async () => { const url = getTestUrl(); let candidateRes; const cacheOverride = new CacheOverride({ afterSend(res) { candidateRes = res; return { cache: true }; }, }); const res = await fetch(url, { cacheOverride }); // in the cache case, a new response is read back from the cache for the origin request strictEqual(res !== candidateRes, true); // the response info is then taken out of the candidate response, and moved into the response strictEqual(candidateRes.cached, false); strictEqual(candidateRes.stale, false); strictEqual(candidateRes.ttl, undefined); strictEqual(candidateRes.age, undefined); strictEqual(candidateRes.vary, undefined); strictEqual(candidateRes.surrogateKeys, undefined); strictEqual(res.cached, false); strictEqual(res.stale, false); strictEqual(res.ttl, 3600); strictEqual(res.age, 0); deepStrictEqual(res.vary, []); strictEqual(res.surrogateKeys.length, 1); strictEqual(typeof res.surrogateKeys[0], 'string'); strictEqual(res.surrogateKeys[0].length > 10, true); }); // Test readonly properties routes.set('/http-cache/readonly-properties', async () => { const url = getTestUrl(); const cacheOverride = new CacheOverride({ afterSend(res) { res.ttl = 3600; return { cache: true }; }, }); // Initial request const res1 = await fetch(url, { cacheOverride }); strictEqual(res1.age, 0); // Wait a bit and verify age increased await new Promise((resolve) => setTimeout(resolve, 1000)); const res2 = await fetch(url, { cacheOverride }); strictEqual(res2.cached, true); strictEqual(res2.stale, false); strictEqual(res2.age > 0, true); // Verify readonly properties cannot be modified assertRejects(() => { res2.cached = false; }, TypeError); assertRejects(() => { res2.stale = true; }, TypeError); assertRejects(() => { res2.age = 0; }, TypeError); }); } // beforeSend { routes.set('/http-cache/before-send-errors', async () => { { const url = getTestUrl(); try { await fetch(url, { cacheOverride: { beforeSend(_req) { throw new Error('before send error'); }, }, }); assert(false, 'expected an error'); } catch (e) { strictEqual(e.message, 'before send error'); } } { const url = getTestUrl(); try { await fetch(url, { cacheOverride: { beforeSend(_req) { return Promise.reject(new Error('before send reject')); }, }, }); assert(false, 'expected an error'); } catch (e) { strictEqual(e.message, 'before send reject'); } } }); // Test basic request mutation via beforeSend routes.set('/http-cache/before-send', async () => { const url = getTestUrl(); let calledBeforeSend = false; const res = await fetch(url, { cacheOverride: { beforeSend(req) { calledBeforeSend = true; req.headers.set('X-Test', 'modified value'); }, }, }); strictEqual(calledBeforeSend, true); const body = await res.text(); strictEqual(body.includes('modified value'), true); }); } // afterSend cases { routes.set('/http-cache/after-send-no-cache', async () => { const url = getTestUrl(); let calledAfterSend = false; const cacheOverride = new CacheOverride({ afterSend(res) { calledAfterSend = true; res.headers.set('Cache-Control', 'private, no-store'); res.ttl = 3600 - res.age; return { cache: false }; }, }); let res = await fetch(url, { cacheOverride }); strictEqual(calledAfterSend, true); strictEqual(res.headers.get('Cache-Control'), 'private, no-store'); calledAfterSend = false; res = await fetch(url, { cacheOverride }); strictEqual(calledAfterSend, true); strictEqual(res.headers.get('Cache-Control'), 'private, no-store'); strictEqual(res.headers.get('x-cache'), 'MISS'); }); routes.set('/http-cache/after-send-header-remove', async () => { const url = getTestUrl(); const res = await fetch(url, { cacheOverride: { afterSend(res) { res.headers.set('Custom', 'custom-header'); res.headers.delete('access-control-allow-origin'); res.headers.delete('access-control-allow-credentials'); return { cache: 'uncacheable' }; }, }, }); strictEqual(res.headers.get('Custom'), 'custom-header'); strictEqual(res.headers.get('access-control-allow-origin'), null); return res; }); routes.set('/http-cache/after-send-cache', async () => { const url = getTestUrl(); let calledAfterSend = false; const cacheOverride = new CacheOverride({ afterSend(res) { calledAfterSend = true; res.headers.set('Cache-Control', 'private, no-store'); res.ttl = 3600 - res.age; return { cache: true }; }, }); let res = await fetch(url, { cacheOverride }); strictEqual(calledAfterSend, true); strictEqual(res.headers.get('Cache-Control'), 'private, no-store'); calledAfterSend = false; res = await fetch(url, { cacheOverride }); // afterSend not called as response is cached strictEqual(res.cached, true); strictEqual(res.headers.get('x-cache'), 'HIT'); strictEqual(calledAfterSend, false); strictEqual(res.headers.get('Cache-Control'), 'private, no-store'); }); routes.set('/http-cache/after-send-cache-expire', async () => { const url = getTestUrl(); let calledAfterSend = false; let res = await fetch(url, { cacheOverride: { afterSend(res) { calledAfterSend = true; res.headers.set('Cache-Control', 'max-age=2'); return { cache: true }; }, }, }); strictEqual(calledAfterSend, true); strictEqual(res.cached, false); strictEqual(res.headers.get('x-cache'), 'MISS'); strictEqual(res.headers.get('Cache-Control'), 'max-age=2'); await new Promise((resolve) => setTimeout(resolve, 500)); calledAfterSend = false; res = await fetch(url, { cacheOverride: { afterSend(res) { calledAfterSend = true; }, }, }); // should still be cached strictEqual(calledAfterSend, false); strictEqual(res.age > 0, true); strictEqual(res.age < 2, true); strictEqual(res.cached, true); strictEqual(res.headers.get('x-cache'), 'HIT'); strictEqual(res.headers.get('Cache-Control'), 'max-age=2'); // should then expire await new Promise((resolve) => setTimeout(resolve, 2000)); res = await fetch(url, { cacheOverride: { afterSend(res) { calledAfterSend = true; }, }, }); strictEqual(calledAfterSend, true); strictEqual(res.cached, false); strictEqual(res.age, 0); }); routes.set('/http-cache/after-send-pass', async () => { const url = getTestUrl(); let res = await fetch(url, { cacheOverride: { afterSend(res) { res.headers.set('x-hooked', ''); }, }, }); res = await fetch(url); strictEqual(res.headers.has('x-hooked'), true); res = await fetch(url, { cacheOverride: 'pass' }); strictEqual(res.headers.has('x-hooked'), false); }); routes.set('/http-cache/after-send-res-no-body', async () => { const url = getTestUrl(); let calledAfterSend = false; const res = await fetch(url, { cacheOverride: { async afterSend(res) { calledAfterSend = true; strictEqual(res.body, null); // empty text gets given for opaque body strictEqual(await res.text(), ''); // not cached -> this candidate response is promoted into the final resposne return { cache: false }; }, }, }); strictEqual(calledAfterSend, true); // verify we get a proper response (url included in response) strictEqual('https://http-me.fastly.dev' + (await res.json()).url, url); }); // Test response property mutations routes.set('/http-cache/response-mutations', async () => { const url = getTestUrl(); let afterSendCalled = false; const res = await fetch(url, { cacheOverride: { afterSend(res) { afterSendCalled = true; // Test mutating various response properties res.status = 201; // can change headers res.headers.set('X-Custom', 'test'); // can change cache options res.ttl = 4000; res.swr = 400; res.pci = true; res.surrogateKeys = ['key1', 'key2']; res.vary = ['Accept', 'User-Agent']; }, }, }); strictEqual(afterSendCalled, true); strictEqual(res.status, 201); strictEqual(res.headers.get('X-Custom'), 'test'); strictEqual(res.ttl, 4000); strictEqual(res.swr, 400); strictEqual(res.pci, true); strictEqual(res.surrogateKeys.sort().join(','), 'key1,key2'); strictEqual(res.vary.sort().join(','), 'Accept,User-Agent'); }); // Test stale response handling routes.set('/http-cache/stale-responses', async () => { const url = getTestUrl(); // Initial fetch const res1 = await fetch(url, { cacheOverride: { afterSend(res) { res.ttl = 1; // Very short TTL res.swr = 2; // Long stale-while-revalidate }, }, }); strictEqual(res1.cached, false); strictEqual(res1.stale, false); await res1.arrayBuffer(); // Wait for response to become stale await new Promise((resolve) => setTimeout(resolve, 1500)); // Fetch stale response let calledAfterSendStale = false; const res2 = await fetch(url, { cacheOverride: { // aftersend will be performed for background revalidation afterSend(res) { calledAfterSendStale = true; }, }, }); // stale response is returned while background revalidation happens strictEqual(calledAfterSendStale, false); strictEqual(res2.cached, true); strictEqual(res2.stale, true); await res2.arrayBuffer(); // Wait for stale response to be invalidated too await new Promise((resolve) => setTimeout(resolve, 1500)); // // Now we should get back the background revalidation we just performed let calledAfterSend = false; const res3 = await fetch(url, { cacheOverride: { afterSend(res) { calledAfterSend = true; }, }, }); strictEqual(res3.cached, true); strictEqual(res3.stale, false); strictEqual(calledAfterSend, false); strictEqual(calledAfterSendStale, true); }); } // Test suite: Body transform { // Test invalid transform stream routes.set('/http-cache/invalid-transform', async () => { const url = getTestUrl(); await assertRejects( () => fetch(url, { cacheOverride: new CacheOverride({ afterSend() { return { bodyTransformFn: 'not a transform function', }; }, }), }), TypeError, ); }); routes.set('/http-cache/body-transform', async () => { const url = getTestUrl(); const cacheOverride = new CacheOverride({ afterSend(res) { return { bodyTransformFn: (buffer) => { const text = new TextDecoder().decode(buffer); const upperText = text.toUpperCase(); return new TextEncoder().encode(upperText); }, cache: true, }; }, }); const res = await fetch(url, { cacheOverride }); const text = await res.text(); strictEqual(text.length > 200, true); strictEqual(text, text.toUpperCase()); }); routes.set('/http-cache/body-transform-delay', async () => { const url = getTestUrl(); const cacheOverride = new CacheOverride({ afterSend(res) { return { async bodyTransformFn(buffer) { // wait one second before returning the result await new Promise((resolve) => setTimeout(resolve, 1000)); const text = new TextDecoder().decode(buffer); const upperText = text.toUpperCase(); return new TextEncoder().encode(upperText); }, cache: true, }; }, }); const res = await fetch(url, { cacheOverride }); const text = await res.text(); strictEqual(text.length > 200, true); strictEqual(text, text.toUpperCase()); }); // Test transform that throws an error routes.set('/http-cache/body-transform-error', async () => { const url = getTestUrl(); const cacheOverride = new CacheOverride({ afterSend() { return { bodyTransformFn() { throw new Error('Transform failed'); }, }; }, }); // Should reject due to transform error await assertRejects( () => fetch(url, { cacheOverride }).then((res) => res.text()), Error, 'Transform failed', ); }); // Test transform that throws an error routes.set('/http-cache/body-transform-error-delay', async () => { const url = getTestUrl(); const cacheOverride = new CacheOverride({ afterSend() { return { async bodyTransformFn() { await new Promise((resolve) => setTimeout(resolve, 1000)); throw new Error('Transform failed'); }, }; }, }); // Should reject due to transform error await assertRejects( () => fetch(url, { cacheOverride }).then((res) => res.text()), Error, 'Transform failed', ); }); // Test transform with invalid chunk type routes.set('/http-cache/body-transform-invalid-chunk', async () => { const url = getTestUrl(); const cacheOverride = new CacheOverride({ afterSend() { return { bodyTransformFn() { return 'string instead of uint8array'; }, }; }, }); // Should reject due to invalid chunk type await assertRejects( () => fetch(url, { cacheOverride }).then((res) => res.text()), Error, ); }); // Concurrent body transforms routes.set('/http-cache/concurrent-transforms', async () => { const url1 = getTestUrl(); const url2 = getTestUrl(); const cacheOverride1 = new CacheOverride({ afterSend() { return { bodyTransformFn(buffer) { const text = new TextDecoder().decode(buffer); return new TextEncoder().encode(text.toUpperCase()); }, cache: true, }; }, }); const cacheOverride2 = new CacheOverride({ afterSend() { return { bodyTransformFn(buffer) { const text = new TextDecoder().decode(buffer); return new TextEncoder().encode(text.toLowerCase()); }, cache: true, }; }, }); // Make concurrent requests with different transforms const [res1, res2] = await Promise.all([ fetch(url1, { cacheOverride: cacheOverride1 }), fetch(url2, { cacheOverride: cacheOverride2 }), ]); // Check that transforms were applied correctly const text1 = await res1.text(); const text2 = await res2.text(); strictEqual(text1.length > 200, true); strictEqual(text1, text1.toUpperCase()); strictEqual(text2.length > 200, true); strictEqual(text2, text2.toLowerCase()); }); } // Test suite: Concurrent / Request Collapsing Behaviors { // Test request mutation order with multiple concurrent requests routes.set('/http-cache/sequential', async () => { const url = getTestUrl(); let beforeSendCount = 0; const cacheOverride = new CacheOverride({ beforeSend(req) { beforeSendCount++; req.headers.set('X-Count', 'COUNT ' + beforeSendCount.toString()); }, }); const res1 = await fetch(url, { cacheOverride }); const res2 = await fetch(url, { cacheOverride }); // Only one beforeSend should execute due to request collapsing strictEqual(beforeSendCount, 1); strictEqual(res1.cached || res2.cached, true); strictEqual(res1.cached && res2.cached, false); strictEqual((await res1.text()).includes('COUNT 1'), true); strictEqual((await res2.text()).includes('COUNT 1'), true); }); // Test request collapsing with different cache options routes.set('/http-cache/sequential-three', async () => { const url = getTestUrl(); let backendCalls = 0; const cacheOverride = new CacheOverride({ beforeSend() { backendCalls++; }, afterSend(res) { // Simulate slow backend return new Promise((resolve) => setTimeout(() => { resolve({ cache: true }); }, 100), ); }, }); const res1 = await fetch(url, { cacheOverride }); const res2 = await fetch(url, { cacheOverride }); const res3 = await fetch(url, { cacheOverride }); // Only one backend call should occur due to request collapsing strictEqual(backendCalls, 1); strictEqual(res1.cached, false); strictEqual(res2.cached, true); strictEqual(res3.cached, true); }); // Test request collapsing with uncacheable responses routes.set( '/http-cache/sequential-request-collapsing-uncacheable', async () => { const url = getTestUrl(); let backendCalls = 0; const cacheOverride = new CacheOverride({ beforeSend() { backendCalls++; }, afterSend() { return { cache: 'uncacheable' }; }, }); // First batch of concurrent requests const res1 = await fetch(url, { cacheOverride }); const res2 = await fetch(url, { cacheOverride }); const res3 = await fetch(url, { cacheOverride }); // Should have collapsed to one backend call strictEqual(backendCalls, 3); strictEqual(res1.cached, false); strictEqual(res2.cached, false); strictEqual(res3.cached, false); // Second request after small delay await new Promise((resolve) => setTimeout(resolve, 50)); const res4 = await fetch(url, { cacheOverride }); // Should trigger new backend call since previous response was marked uncacheable strictEqual(backendCalls, 4); strictEqual(res4.cached, false); }, ); // TODO (skipped, due to host behaviours not seeming as expected) // Test request collapsing with varying headers routes.set('/http-cache/sequential-request-collapsing-vary', async () => { const url = getTestUrl(); let backendCalls = 0; const cacheOverride = new CacheOverride({ beforeSend() { backendCalls++; }, afterSend(res) { res.vary = ['User-Agent']; return { cache: true }; }, }); // Concurrent requests with same User-Agent const headers1 = { 'User-Agent': 'bot1' }; const res1 = await fetch(url, { cacheOverride, headers: headers1 }); const res2 = await fetch(url, { cacheOverride, headers: headers1 }); strictEqual(backendCalls, 1); // Should collapse strictEqual(res1.cached, false); strictEqual(res2.cached, true); // Concurrent requests with different User-Agent const headers2 = { 'User-Agent': 'bot2' }; const res3 = await fetch(url, { cacheOverride, headers: headers2 }); const res4 = await fetch(url, { cacheOverride, headers: headers2 }); strictEqual(backendCalls, 2); // Should trigger new backend call strictEqual(res3.cached, false); strictEqual(res4.cached, true); }); // TODO (skipped, due to unknown blocking from host) routes.set('/http-cache/parallel', async () => { const url = getTestUrl(); let beforeSendCount = 0; const cacheOverride = new CacheOverride({ beforeSend(req) { beforeSendCount++; req.headers.set('X-Count', 'COUNT ' + beforeSendCount.toString()); }, }); const [res1, res2] = await Promise.all([ fetch(url, { cacheOverride }), fetch(url, { cacheOverride }), ]); // Only one beforeSend should execute due to request collapsing strictEqual(beforeSendCount, 1); strictEqual(res1.cached || res2.cached, true); strictEqual(res1.cached && res2.cached, false); strictEqual((await res1.text()).includes('COUNT 1'), true); strictEqual((await res2.text()).includes('COUNT 1'), true); }); // TODO (skipped, due to unknown blocking from host) routes.set('/http-cache/parallel-three', async () => { const url = getTestUrl(); let backendCalls = 0; const cacheOverride = new CacheOverride({ beforeSend() { backendCalls++; }, afterSend(res) { // Simulate slow backend return new Promise((resolve) => setTimeout(() => { resolve({ cache: true }); }, 100), ); }, }); // Make multiple concurrent requests const results = await Promise.all([ fetch(url, { cacheOverride }), fetch(url, { cacheOverride }), fetch(url, { cacheOverride }), ]); // Only one backend call should occur due to request collapsing strictEqual(backendCalls, 1); strictEqual(results[0].cached, false); strictEqual(results[1].cached, true); strictEqual(results[2].cached, true); }); // TODO (skipped, due to unknown blocking from host) routes.set( '/http-cache/parallel-request-collapsing-uncacheable', async () => { const url = getTestUrl(); let backendCalls = 0; const cacheOverride = new CacheOverride({ beforeSend() { backendCalls++; }, afterSend() { return { cache: 'uncacheable' }; }, }); // First batch of concurrent requests const results1 = await Promise.all([ fetch(url, { cacheOverride }), fetch(url, { cacheOverride }), fetch(url, { cacheOverride }), ]); // Should have collapsed to one backend call strictEqual(backendCalls, 3); results1.forEach((res) => strictEqual(res.cached, false)); // Second request after small delay await new Promise((resolve) => setTimeout(resolve, 50)); const res = await fetch(url, { cacheOverride }); // Should trigger new backend call since previous response was marked uncacheable strictEqual(backendCalls, 4); strictEqual(res.cached, false); }, ); // TODO (skipped, due to unknown blocking from host) routes.set('/http-cache/parallel-request-collapsing-vary', async () => { const url = getTestUrl(); let backendCalls = 0; const cacheOverride = new CacheOverride({ beforeSend() { backendCalls++; }, afterSend(res) { res.vary = ['User-Agent']; return { cache: true }; }, }); // Concurrent requests with same User-Agent const headers1 = { 'User-Agent': 'bot1' }; const results1 = await Promise.all([ fetch(url, { cacheOverride, headers: headers1 }), fetch(url, { cacheOverride, headers: headers1 }), ]); strictEqual(backendCalls, 1); // Should collapse strictEqual(results1[0].cached, false); strictEqual(results1[1].cached, true); // Concurrent requests with different User-Agent const headers2 = { 'User-Agent': 'bot2' }; const results2 = await Promise.all([ fetch(url, { cacheOverride, headers: headers2 }), fetch(url, { cacheOverride, headers: headers2 }), ]); strictEqual(backendCalls, 2); // Should trigger new backend call strictEqual(results2[0].cached, false); strictEqual(results2[1].cached, true); }); } routes.set('/http-cache/cache-key-on-request', async () => { const url = getTestUrl(); let backendCalls = 0; const cacheOverride = new CacheOverride({ beforeSend(req) { backendCalls++; }, }); const key = `custom-cache-key-${Math.random().toString().slice(2)}`; let req1 = new Request(url + '?req=1'); req1.setCacheKey(key); const res1 = await fetch(req1, { cacheOverride }); strictEqual(backendCalls, 1); strictEqual(res1.cached, false); let req2 = new Request(url + '?req=2'); req2.setCacheKey(key); const res2 = await fetch(req2, { cacheOverride }); strictEqual(backendCalls, 1); strictEqual(res2.cached, true); strictEqual(await res1.text(), await res2.text()); }); ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/index.js ================================================ /// /* eslint-env serviceworker */ import { routes } from './routes.js'; import { env } from 'fastly:env'; import { enableDebugLogging } from 'fastly:experimental'; import './acl.js'; import './console.js'; import './dynamic-backend.js'; import './hello-world.js'; import './hono.js'; import './http-cache.js'; import './kv-store.js'; import './transform-stream.js'; addEventListener('fetch', (event) => { const responsePromise = app(event); if (responsePromise) event.respondWith(responsePromise); }); if (env('FASTLY_DEBUG_LOGGING') === '1') { if (fastly.debugMessages) { const { debug: consoleDebug } = console; console.debug = function debug(...args) { fastly.debugLog(...args); consoleDebug(...args); }; } enableDebugLogging(true); } /** * @param {FetchEvent} event * @returns {Response} */ async function app(event) { const FASTLY_SERVICE_VERSION = env('FASTLY_SERVICE_VERSION') || 'local'; console.log(`FASTLY_SERVICE_VERSION: ${FASTLY_SERVICE_VERSION}`); const path = new URL(event.request.url).pathname; console.log(`path: ${path}`); let res; try { const routeHandler = routes.get(path); if (routeHandler) { res = await routeHandler(event); if (res !== null) { res = res || new Response('ok'); } } else { return (res = new Response(`${path} endpoint does not exist`, { status: 500, })); } } catch (error) { if (error instanceof Response) { res = error; } else { try { return (res = new Response( `The routeHandler for ${path} threw a [${error.constructor?.name ?? error.name}] error: ${error.message || error}` + '\n' + error.stack + (fastly.debugMessages ? '\n[DEBUG BUILD MESSAGES]:\n\n - ' + fastly.debugMessages.join('\n - ') : ''), { status: 500 }, )); } catch (errRes) { res = errRes; } } } finally { res.headers.set('fastly_service_version', FASTLY_SERVICE_VERSION); } return res; } ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/kv-store.js ================================================ /// import { strictEqual, assertThrows, assertRejects, assertResolves, deepStrictEqual, } from './assertions.js'; import { KVStore } from 'fastly:kv-store'; import { routes, isRunningLocally } from './routes.js'; import { sdkVersion } from 'fastly:experimental'; import { env } from 'fastly:env'; const KV_STORE_NAME = env('KV_STORE_NAME'); const debug = sdkVersion.endsWith('-debug'); // kvstore e2e tests { routes.set('/kv-store/debug-error', async () => { if (!debug) return; // special debug function to create a kv entry with an invalid handle const entry = fastly.dump(null, 'invalidkv'); // we can then test the invalid handle error try { await entry.text(); } catch (e) { strictEqual(e.message.includes('Invalid handle'), true); } }); routes.set('/kv-store-e2e/list', async () => { const store = new KVStore(KV_STORE_NAME); try { await store.delete('c'); } catch {} // bad metadata await store.put('a', 'b'); const aEntry = await store.get('a'); strictEqual(aEntry.metadata(), null); for (let i = 0; i < 100; i++) { await store.put('c' + i, 'd', { mode: 'overwrite', metadata: i % 2 === 0 ? '42' : new Uint8Array([42]), }); } const cEntry = await store.get('c1'); strictEqual(await cEntry.text(), 'd'); const metadata = await cEntry.metadata(); strictEqual(metadata.byteLength, 1); strictEqual(metadata[0], 42); const cEntry2 = await store.get('c2'); strictEqual(await cEntry2.metadataText(), '42'); const metadataText = await cEntry.metadataText(); strictEqual(metadataText, '*'); await store.put('c5', 'cba', { mode: 'prepend', metadata: 'cbad', }); const c5Entry = await store.get('c5'); strictEqual(await c5Entry.text(), 'cbad'); assertRejects(async () => await c5Entry.metadataText(), TypeError); // TTL only supported on compute not viceroy if (!isRunningLocally()) { await store.put('t', 't', { ttl: 2 }); const tEntry = await store.get('t'); strictEqual(await tEntry.text(), 't'); const metadata = await tEntry.metadata(); strictEqual(metadata, null); await new Promise((resolve) => setTimeout(resolve, 2000)); strictEqual(await store.get('t'), null); } // bad cursor gives a "bad request" error assertRejects(async () => { await store.list({ cursor: 'boooo' }); }, TypeError); assertThrows(() => { store.list({ limit: 'booooo' }); }, TypeError); assertThrows(() => { store.list({ limit: 5.5 }); }, TypeError); strictEqual(await store.get('noone'), null); let { list, cursor } = await store.list({ limit: 10, prefix: 'c' }); deepStrictEqual(list, [ 'c0', 'c1', 'c10', 'c11', 'c12', 'c13', 'c14', 'c15', 'c16', 'c17', ]); ({ list, cursor } = await store.list({ limit: 10, prefix: 'c', cursor })); deepStrictEqual(list, [ 'c18', 'c19', 'c2', 'c20', 'c21', 'c22', 'c23', 'c24', 'c25', 'c26', ]); ({ list, cursor } = await store.list({ limit: 70, prefix: 'c', cursor })); deepStrictEqual(list, [ 'c27', 'c28', 'c29', 'c3', 'c30', 'c31', 'c32', 'c33', 'c34', 'c35', 'c36', 'c37', 'c38', 'c39', 'c4', 'c40', 'c41', 'c42', 'c43', 'c44', 'c45', 'c46', 'c47', 'c48', 'c49', 'c5', 'c50', 'c51', 'c52', 'c53', 'c54', 'c55', 'c56', 'c57', 'c58', 'c59', 'c6', 'c60', 'c61', 'c62', 'c63', 'c64', 'c65', 'c66', 'c67', 'c68', 'c69', 'c7', 'c70', 'c71', 'c72', 'c73', 'c74', 'c75', 'c76', 'c77', 'c78', 'c79', 'c8', 'c80', 'c81', 'c82', 'c83', 'c84', 'c85', 'c86', 'c87', 'c88', 'c89', 'c9', ]); ({ list, cursor } = await store.list({ limit: 15, prefix: 'c', cursor })); deepStrictEqual(list, [ 'c90', 'c91', 'c92', 'c93', 'c94', 'c95', 'c96', 'c97', 'c98', 'c99', ]); strictEqual(cursor, undefined); }); } // KVStore { routes.set('/kv-store/exposed-as-global', async () => { strictEqual(typeof KVStore, 'function', `typeof KVStore`); }); routes.set('/kv-store/interface', kvStoreInterfaceTests); // KVStore constructor { routes.set('/kv-store/constructor/called-as-regular-function', async () => { assertThrows( () => { KVStore(); }, TypeError, `calling a builtin KVStore constructor without new is forbidden`, ); }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/kv-store/constructor/parameter-calls-7.1.17-ToString', async () => { let sentinel; const test = () => { sentinel = Symbol(); const name = { toString() { throw sentinel; }, }; new KVStore(name); }; assertThrows(test); try { test(); } catch (thrownError) { strictEqual(thrownError, sentinel, 'thrownError === sentinel'); } assertThrows( () => new KVStore(Symbol()), TypeError, `can't convert symbol to string`, ); }, ); routes.set('/kv-store/constructor/empty-parameter', async () => { assertThrows( () => { new KVStore(); }, TypeError, `KVStore constructor: At least 1 argument required, but only 0 passed`, ); }); routes.set('/kv-store/constructor/found-store', async () => { const store = new KVStore(KV_STORE_NAME); strictEqual(store instanceof KVStore, true, `store instanceof KVStore`); }); routes.set('/kv-store/constructor/missing-store', async () => { assertThrows( () => { new KVStore('missing'); }, Error, `KVStore constructor: No KVStore named 'missing' exists`, ); }); routes.set('/kv-store/constructor/invalid-name', async () => { // control Characters (\\u0000-\\u001F) are not allowed const controlCharacters = [ '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', ]; for (const character of controlCharacters) { assertThrows( () => { new KVStore(character); }, TypeError, `KVStore constructor: name can not contain control characters (\\u0000-\\u001F)`, ); } // must be less than 256 characters assertThrows( () => { new KVStore('1'.repeat(256)); }, TypeError, `KVStore constructor: name can not be more than 255 characters`, ); // empty string not allowed assertThrows( () => { new KVStore(''); }, TypeError, `KVStore constructor: name can not be an empty string`, ); }); } // KVStore put method { routes.set('/kv-store/put/called-as-constructor', async () => { assertThrows(() => { new KVStore.prototype.put('1', '1'); }, TypeError); }); routes.set('/kv-store/put/called-unbound', async () => { assertThrows(() => { KVStore.prototype.put.call(undefined, '1', '2'); }, TypeError); }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/kv-store/put/key-parameter-calls-7.1.17-ToString', async () => { let sentinel; const test = async () => { sentinel = Symbol(); const key = { toString() { throw sentinel; }, }; const store = new KVStore(KV_STORE_NAME); await store.put(key, ''); }; await assertRejects(test); try { await test(); } catch (thrownError) { strictEqual(thrownError, sentinel, 'thrownError === sentinel'); } await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.put(Symbol(), ''); }, Error, `can't convert symbol to string`, ); }, ); routes.set('/kv-store/put/key-parameter-not-supplied', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.put(); }, TypeError, `put: At least 2 arguments required, but only 0 passed`, ); }); routes.set('/kv-store/put/key-parameter-empty-string', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.put('', ''); }, TypeError, `KVStore key can not be an empty string`, ); }); routes.set( '/kv-store/put/key-parameter-1024-character-string', async () => { await assertResolves(async () => { const store = new KVStore(KV_STORE_NAME); const key = 'a'.repeat(1024); await store.put(key, ''); }); }, ); routes.set( '/kv-store/put/key-parameter-1025-character-string', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); const key = 'a'.repeat(1025); await store.put(key, ''); }, TypeError, `KVStore key can not be more than 1024 characters`, ); }, ); routes.set('/kv-store/put/key-parameter-containing-newline', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.put('\n', ''); }, TypeError, `KVStore key can not contain newline character`, ); }); routes.set( '/kv-store/put/key-parameter-containing-carriage-return', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.put('\r', ''); }, TypeError, `KVStore key can not contain carriage return character`, ); }, ); routes.set( '/kv-store/put/key-parameter-starting-with-well-known-acme-challenge', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.put('.well-known/acme-challenge/', ''); }, TypeError, `KVStore key can not start with .well-known/acme-challenge/`, ); }, ); routes.set('/kv-store/put/key-parameter-single-dot', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.put('.', ''); }, TypeError, `KVStore key can not be '.' or '..'`, ); }); routes.set('/kv-store/put/key-parameter-double-dot', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.put('..', ''); }, TypeError, `KVStore key can not be '.' or '..'`, ); }); routes.set( '/kv-store/put/key-parameter-containing-special-characters', async () => { const specialCharacters = [';', '^', '|', '#', '?']; for (const character of specialCharacters) { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.put(character, ''); }, TypeError, `KVStore key can not contain ${character} character`, ); } }, ); routes.set('/kv-store/put/value-parameter-as-undefined', async () => { const store = new KVStore(KV_STORE_NAME); let result = store.put('undefined', undefined); strictEqual( result instanceof Promise, true, 'store.put("undefined", undefined) instanceof Promise', ); strictEqual( await result, undefined, 'await store.put("undefined", undefined)', ); }); routes.set('/kv-store/put/value-parameter-not-supplied', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.put('test'); }, TypeError, `put: At least 2 arguments required, but only 1 passed`, ); }); // - ReadableStream routes.set( '/kv-store/put/value-parameter-readablestream-empty', async () => { // TODO: remove this when streams are supported await assertRejects( async () => { const stream = iteratableToStream([]); const store = new KVStore(KV_STORE_NAME); await store.put('readablestream-empty', stream); }, TypeError, `Content-provided streams are not yet supported for streaming into KVStore`, ); // TODO: uncomment this when conte-provided (guest) streams are supported // const stream = iteratableToStream([]) // const store = new KVStore(KV_STORE_NAME) // let result = store.put('readablestream-empty', stream) // strictEqual(result instanceof Promise, true, `store.put('readablestream-empty', stream) instanceof Promise`) // strictEqual(await result, undefined, `await store.put('readablestream-empty', stream)`) }, ); routes.set( '/kv-store/put/value-parameter-readablestream-under-30mb', async () => { const res = await fetch( 'https://compute-sdk-test-backend.edgecompute.app/', { backend: 'TheOrigin', }, ); const store = new KVStore(KV_STORE_NAME); let result = store.put('readablestream-under-30mb', res.body); strictEqual( result instanceof Promise, true, `store.put('readablestream-under-30mb', stream) instanceof Promise`, ); strictEqual( await result, undefined, `await store.put('readablestream-under-30mb', stream)`, ); }, ); routes.set('/kv-store/put/request-body', async ({ request }) => { const store = new KVStore(KV_STORE_NAME); let result = store.put('readablestream-req', request.body); strictEqual( result instanceof Promise, true, `store.put('readablestream-req', request.body) instanceof Promise`, ); strictEqual( await result, undefined, `await store.put('readablestream-req', request.body)`, ); }); routes.set( '/kv-store/put/value-parameter-readablestream-over-30mb', async () => { // TODO: remove this when streams are supported await assertRejects( async () => { const stream = iteratableToStream([ 'x'.repeat(30 * 1024 * 1024) + 'x', ]); const store = new KVStore(KV_STORE_NAME); await store.put('readablestream-over-30mb', stream); }, Error, `Content-provided streams are not yet supported for streaming into KVStore`, ); // TODO: uncomment this when conte-provided (guest) streams are supported // const stream = iteratableToStream(['x'.repeat(30*1024*1024) + 'x']) // const store = new KVStore(KV_STORE_NAME) // let result = store.put('readablestream-over-30mb', stream) // strictEqual(result instanceof Promise, true, `store.put('readablestream-over-30mb', stream) instanceof Promise`) // strictEqual(await result, undefined, `await store.put('readablestream-over-30mb', stream)`) }, ); routes.set( '/kv-store/put/value-parameter-readablestream-locked', async () => { const stream = iteratableToStream([]); // getReader() causes the stream to become locked stream.getReader(); const store = new KVStore(KV_STORE_NAME); await assertRejects( async () => { await store.put('readablestream-locked', stream); // await store.put("test", stream) }, TypeError, `Can't use a ReadableStream that's locked or has ever been read from or canceled`, ); }, ); // - URLSearchParams routes.set('/kv-store/put/value-parameter-URLSearchParams', async () => { const items = [ new URLSearchParams(), new URLSearchParams({ a: 'b', c: 'd' }), ]; const store = new KVStore(KV_STORE_NAME); for (const searchParams of items) { let result = store.put('URLSearchParams', searchParams); strictEqual( result instanceof Promise, true, `store.put('URLSearchParams', searchParams) instanceof Promise`, ); strictEqual( await result, undefined, `await store.put('URLSearchParams', searchParams)`, ); } }); // - USV strings routes.set('/kv-store/put/value-parameter-strings', async () => { const strings = [ // empty '', // lone surrogate '\uD800', // surrogate pair '𠈓', String('carrot'), ]; const store = new KVStore(KV_STORE_NAME); for (const string of strings) { let result = store.put('string', string); strictEqual( result instanceof Promise, true, `store.put('string', string) instanceof Promise`, ); strictEqual( await result, undefined, `await store.put('string', string)`, ); } }); routes.set('/kv-store/put/value-parameter-string-over-30mb', async () => { const string = 'x'.repeat(35 * 1024 * 1024) + 'x'; const store = new KVStore(KV_STORE_NAME); await assertRejects( () => store.put('string-over-30mb', string), TypeError, `KVStore value can not be more than 30 Megabytes in size`, ); }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/kv-store/put/value-parameter-calls-7.1.17-ToString', async () => { let sentinel; const test = async () => { sentinel = Symbol(); const value = { toString() { throw sentinel; }, }; const store = new KVStore(KV_STORE_NAME); await store.put('toString', value); }; await assertRejects(test); try { await test(); } catch (thrownError) { strictEqual(thrownError, sentinel, 'thrownError === sentinel'); } await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.put('Symbol()', Symbol()); }, TypeError, `can't convert symbol to string`, ); }, ); // - buffer source routes.set('/kv-store/put/value-parameter-buffer', async () => { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; const store = new KVStore(KV_STORE_NAME); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = store.put(constructor.name, typedArray.buffer); strictEqual( result instanceof Promise, true, `store.put(${constructor.name}, typedArray.buffer) instanceof Promise`, ); strictEqual( await result, undefined, `await store.put(${constructor.name}, typedArray.buffer)`, ); } }); routes.set('/kv-store/put/value-parameter-arraybuffer', async () => { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; const store = new KVStore(KV_STORE_NAME); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = store.put(constructor.name, typedArray.buffer); strictEqual( result instanceof Promise, true, `store.put(${constructor.name}, typedArray.buffer) instanceof Promise`, ); strictEqual( await result, undefined, `await store.put(${constructor.name}, typedArray.buffer)`, ); } }); routes.set('/kv-store/put/value-parameter-typed-arrays', async () => { const typedArrayConstructors = [ Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, BigInt64Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, ]; const store = new KVStore(KV_STORE_NAME); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); let result = store.put(constructor.name, typedArray); strictEqual( result instanceof Promise, true, `store.put(${constructor.name}, typedArray) instanceof Promise`, ); strictEqual( await result, undefined, `await store.put(${constructor.name}, typedArray)`, ); } }); routes.set('/kv-store/put/value-parameter-dataview', async () => { const typedArrayConstructors = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array, ]; const store = new KVStore(KV_STORE_NAME); for (const constructor of typedArrayConstructors) { const typedArray = new constructor(8); const view = new DataView(typedArray.buffer); let result = store.put(`new DataView(${constructor.name})`, view); strictEqual( result instanceof Promise, true, `store.put(new DataView(${constructor.name}), typedArray) instanceof Promise`, ); strictEqual( await result, undefined, `await store.put(new DataView(${constructor.name}), typedArray)`, ); } }); } // KVStore delete method { routes.set('/kv-store/delete/called-as-constructor', async () => { assertThrows(() => { new KVStore.prototype.delete('1'); }, TypeError); }); routes.set('/kv-store/delete/called-unbound', async () => { await assertRejects(async () => { await KVStore.prototype.delete.call(undefined, '1'); }, TypeError); }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/kv-store/delete/key-parameter-calls-7.1.17-ToString', async () => { let sentinel; const test = async () => { sentinel = Symbol(); const key = { toString() { throw sentinel; }, }; const store = new KVStore(KV_STORE_NAME); await store.delete(key); }; await assertRejects(test); try { await test(); } catch (thrownError) { strictEqual(thrownError, sentinel, 'thrownError === sentinel'); } await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.delete(Symbol()); }, TypeError, `can't convert symbol to string`, ); }, ); routes.set('/kv-store/delete/key-parameter-not-supplied', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.delete(); }, TypeError, `delete: At least 1 argument required, but only 0 passed`, ); }); routes.set('/kv-store/delete/key-parameter-empty-string', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.delete(''); }, TypeError, `KVStore key can not be an empty string`, ); }); routes.set( '/kv-store/delete/key-parameter-1024-character-string', async () => { await assertResolves(async () => { const store = new KVStore(KV_STORE_NAME); const key = 'a'.repeat(1024); await store.put(key, ''); await store.delete(key); }); }, ); routes.set( '/kv-store/delete/key-parameter-1025-character-string', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); const key = 'a'.repeat(1025); await store.delete(key); }, TypeError, `KVStore key can not be more than 1024 characters`, ); }, ); routes.set( '/kv-store/delete/key-parameter-containing-newline', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.delete('\n'); }, TypeError, `KVStore key can not contain newline character`, ); }, ); routes.set( '/kv-store/delete/key-parameter-containing-carriage-return', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.delete('\r'); }, TypeError, `KVStore key can not contain carriage return character`, ); }, ); routes.set( '/kv-store/delete/key-parameter-starting-with-well-known-acme-challenge', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.delete('.well-known/acme-challenge/'); }, TypeError, `KVStore key can not start with .well-known/acme-challenge/`, ); }, ); routes.set('/kv-store/delete/key-parameter-single-dot', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.delete('.'); }, TypeError, `KVStore key can not be '.' or '..'`, ); }); routes.set('/kv-store/delete/key-parameter-double-dot', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.delete('..'); }, TypeError, `KVStore key can not be '.' or '..'`, ); }); routes.set( '/kv-store/delete/key-parameter-containing-special-characters', async () => { const specialCharacters = [';', '^', '|', '#', '?']; for (const character of specialCharacters) { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.delete(character); }, TypeError, `KVStore key can not contain ${character} character`, ); } }, ); routes.set( '/kv-store/delete/key-does-not-exist-returns-undefined', async () => { if (isRunningLocally()) { return; } let store = new KVStore(KV_STORE_NAME); await assertRejects( () => store.delete(Math.random()), TypeError, 'KVStore delete: Not found.', ); }, ); routes.set('/kv-store/delete/key-exists', async () => { let store = new KVStore(KV_STORE_NAME); let key = `key-exists-${Math.random()}`; await store.put(key, 'hello'); let result = store.delete(key); strictEqual( result instanceof Promise, true, `store.delete(key) instanceof Promise`, ); result = await result; strictEqual(result, undefined, `(await store.delete(key) === undefined)`); }); routes.set('/kv-store/delete/delete-key-twice', async () => { if (isRunningLocally()) { return; } let store = new KVStore(KV_STORE_NAME); let key = `key-exists-${Math.random()}`; await store.put(key, 'hello'); let result = store.delete(key); strictEqual( result instanceof Promise, true, `store.delete(key) instanceof Promise`, ); result = await result; strictEqual(result, undefined, `(await store.delete(key) === undefined)`); await assertRejects( () => store.delete(key), TypeError, 'KVStore delete: Not found.', ); }); routes.set('/kv-store/delete/multiple-deletes-at-once', async () => { let store = new KVStore(KV_STORE_NAME); let key1 = `key-exists-${Math.random()}`; await store.put(key1, '1hello1'); let key2 = `key-exists-${Math.random()}`; await store.put(key2, '2hello2'); let key3 = `key-exists-${Math.random()}`; await store.put(key3, '3hello3'); let key4 = `key-exists-${Math.random()}`; await store.put(key4, '4hello4'); let key5 = `key-exists-${Math.random()}`; await store.put(key5, '5hello5'); await assertResolves(() => { return Promise.all([ store.delete(key1), store.delete(key2), store.delete(key3), store.delete(key4), store.delete(key5), ]); }); }); } // KVStore get method { routes.set('/kv-store/get/called-as-constructor', async () => { assertThrows(() => { new KVStore.prototype.get('1'); }, TypeError); }); routes.set('/kv-store/get/called-unbound', async () => { await assertRejects(async () => { await KVStore.prototype.get.call(undefined, '1'); }, TypeError); }); // https://tc39.es/ecma262/#sec-tostring routes.set( '/kv-store/get/key-parameter-calls-7.1.17-ToString', async () => { let sentinel; const test = async () => { sentinel = Symbol(); const key = { toString() { throw sentinel; }, }; const store = new KVStore(KV_STORE_NAME); await store.get(key); }; await assertRejects(test); try { await test(); } catch (thrownError) { strictEqual(thrownError, sentinel, 'thrownError === sentinel'); } await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.get(Symbol()); }, TypeError, `can't convert symbol to string`, ); }, ); routes.set('/kv-store/get/key-parameter-not-supplied', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.get(); }, TypeError, `get: At least 1 argument required, but only 0 passed`, ); }); routes.set('/kv-store/get/key-parameter-empty-string', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); await store.get(''); }, TypeError, `KVStore key can not be an empty string`, ); }); routes.set( '/kv-store/get/key-parameter-1024-character-string', async () => { await assertResolves(async () => { const store = new KVStore(KV_STORE_NAME); const key = 'a'.repeat(1024); await store.get(key); }); }, ); routes.set( '/kv-store/get/key-parameter-1025-character-string', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); const key = 'a'.repeat(1025); await store.get(key); }, TypeError, `KVStore key can not be more than 1024 characters`, ); }, ); routes.set('/kv-store/get/key-parameter-containing-newline', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.get('\n'); }, TypeError, `KVStore key can not contain newline character`, ); }); routes.set( '/kv-store/get/key-parameter-containing-carriage-return', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.get('\r'); }, TypeError, `KVStore key can not contain carriage return character`, ); }, ); routes.set( '/kv-store/get/key-parameter-starting-with-well-known-acme-challenge', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.get('.well-known/acme-challenge/'); }, TypeError, `KVStore key can not start with .well-known/acme-challenge/`, ); }, ); routes.set('/kv-store/get/key-parameter-single-dot', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.get('.'); }, TypeError, `KVStore key can not be '.' or '..'`, ); }); routes.set('/kv-store/get/key-parameter-double-dot', async () => { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.get('..'); }, TypeError, `KVStore key can not be '.' or '..'`, ); }); routes.set( '/kv-store/get/key-parameter-containing-special-characters', async () => { const specialCharacters = [';', '^', '|', '#', '?']; for (const character of specialCharacters) { await assertRejects( async () => { let store = new KVStore(KV_STORE_NAME); await store.get(character); }, TypeError, `KVStore key can not contain ${character} character`, ); } }, ); routes.set('/kv-store/get/key-does-not-exist-returns-null', async () => { let store = new KVStore(KV_STORE_NAME); let result = store.get(Math.random()); strictEqual( result instanceof Promise, true, `store.get(Math.random()) instanceof Promise`, ); strictEqual(await result, null, `await store.get(Math.random())`); }); routes.set('/kv-store/get/key-does-not-exist-returns-null', async () => { let store = new KVStore(KV_STORE_NAME); let result = store.get(Math.random()); strictEqual( result instanceof Promise, true, `store.get(Math.random()) instanceof Promise`, ); strictEqual(await result, null, `await store.get(Math.random())`); }); routes.set('/kv-store/get/key-exists', async () => { let store = new KVStore(KV_STORE_NAME); let key = `key-exists-${Math.random()}`; await store.put(key, 'hello'); let result = store.get(key); strictEqual( result instanceof Promise, true, `store.get(key) instanceof Promise`, ); result = await result; strictEqual( result instanceof KVStoreEntry, true, `(await store.get(key) instanceof KVStoreEntry)`, ); }); routes.set('/kv-store/get/multiple-lookups-at-once', async () => { let store = new KVStore(KV_STORE_NAME); let key1 = `key-exists-${Math.random()}`; await store.put(key1, '1hello1'); let key2 = `key-exists-${Math.random()}`; await store.put(key2, '2hello2'); let key3 = `key-exists-${Math.random()}`; await store.put(key3, '3hello3'); let key4 = `key-exists-${Math.random()}`; await store.put(key4, '4hello4'); let key5 = `key-exists-${Math.random()}`; await store.put(key5, '5hello5'); let results = await Promise.all([ store.get(key1), store.get(key2), store.get(key3), store.get(key4), store.get(key5), ]); strictEqual( await results[0].text(), '1hello1', `await results[0].text()`, ); strictEqual( await results[1].text(), '2hello2', `await results[1].text()`, ); strictEqual( await results[2].text(), '3hello3', `await results[2].text()`, ); strictEqual( await results[3].text(), '4hello4', `await results[3].text()`, ); strictEqual( await results[4].text(), '5hello5', `await results[4].text()`, ); }); } } // KVStoreEntry { routes.set('/kv-store-entry/interface', async () => { return kvStoreEntryInterfaceTests(); }); routes.set('/kv-store-entry/text/valid', async () => { let store = new KVStore(KV_STORE_NAME); let key = `entry-text-valid`; await store.put(key, 'hello'); let entry = await store.get(key); let result = entry.text(); strictEqual( result instanceof Promise, true, `entry.text() instanceof Promise`, ); result = await result; strictEqual(result, 'hello', `await entry.text())`); }); routes.set('/kv-store-entry/json/valid', async () => { let store = new KVStore(KV_STORE_NAME); let key = `entry-json-valid`; const obj = { a: 1, b: 2, c: 3 }; await store.put(key, JSON.stringify(obj)); let entry = await store.get(key); let result = entry.json(); strictEqual( result instanceof Promise, true, `entry.json() instanceof Promise`, ); result = await result; deepStrictEqual(result, obj, `await entry.json())`); }); routes.set('/kv-store-entry/json/invalid', async () => { let store = new KVStore(KV_STORE_NAME); let key = `entry-json-invalid`; await store.put(key, "132abc;['-=9"); let entry = await store.get(key); await assertRejects( () => entry.json(), SyntaxError, `JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 4 of the JSON data`, ); }); routes.set('/kv-store-entry/arrayBuffer/valid', async () => { let store = new KVStore(KV_STORE_NAME); let key = `entry-arraybuffer-valid`; await store.put(key, new Int8Array([0, 1, 2, 3])); let entry = await store.get(key); let result = entry.arrayBuffer(); strictEqual( result instanceof Promise, true, `entry.arrayBuffer() instanceof Promise`, ); result = await result; strictEqual( result instanceof ArrayBuffer, true, `(await entry.arrayBuffer()) instanceof ArrayBuffer`, ); }); routes.set('/kv-store-options/gen', async () => { let store = new KVStore(KV_STORE_NAME); let key = `entry-options`; await store.put(key, 'body op', { gen: 2, }); let entry = await store.get(key); let result = entry.body; strictEqual( result instanceof ReadableStream, true, `entry.options instanceof ReadableStream`, ); let text = await streamToString(result); strictEqual(text, 'body op', `entry.body contents as string`); }); routes.set('/kv-store-options/gen-invalid', async () => { await assertRejects( async () => { const store = new KVStore(KV_STORE_NAME); let key = `entry-options-gen-invalid`; await store.put(key, 'body Nan', { gen: '2' }); }, TypeError, `KVStore.insert: gen must be an integer`, ); }); routes.set('/kv-store-entry/body', async () => { let store = new KVStore(KV_STORE_NAME); let key = `entry-body`; await store.put(key, 'body body body'); let entry = await store.get(key); let result = entry.body; strictEqual( result instanceof ReadableStream, true, `entry.body instanceof ReadableStream`, ); let text = await streamToString(result); strictEqual(text, 'body body body', `entry.body contents as string`); }); routes.set('/kv-store-entry/bodyUsed', async () => { let store = new KVStore(KV_STORE_NAME); let key = `entry-bodyUsed`; await store.put(key, 'body body body'); let entry = await store.get(key); strictEqual(entry.bodyUsed, false, `entry.bodyUsed`); await entry.text(); strictEqual(entry.bodyUsed, true, `entry.bodyUsed`); }); } async function kvStoreEntryInterfaceTests() { let actual = Reflect.ownKeys(KVStoreEntry); let expected = ['prototype', 'length', 'name']; deepStrictEqual(actual, expected, `Reflect.ownKeys(KVStoreEntry)`); actual = Reflect.getOwnPropertyDescriptor(KVStoreEntry, 'prototype'); expected = { value: KVStoreEntry.prototype, writable: false, enumerable: false, configurable: false, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry, 'prototype')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStoreEntry, 'length'); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStoreEntry, 'name'); expected = { value: 'KVStoreEntry', writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry, 'name')`, ); actual = Reflect.ownKeys(KVStoreEntry.prototype); expected = [ 'constructor', 'body', 'bodyUsed', 'arrayBuffer', 'json', 'text', 'metadata', 'metadataText', ]; deepStrictEqual(actual, expected, `Reflect.ownKeys(KVStoreEntry.prototype)`); actual = Reflect.getOwnPropertyDescriptor( KVStoreEntry.prototype, 'constructor', ); expected = { writable: true, enumerable: false, configurable: true, value: KVStoreEntry.prototype.constructor, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'constructor')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'text'); expected = { writable: true, enumerable: true, configurable: true, value: KVStoreEntry.prototype.text, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'text')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'json'); expected = { writable: true, enumerable: true, configurable: true, value: KVStoreEntry.prototype.json, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'json')`, ); actual = Reflect.getOwnPropertyDescriptor( KVStoreEntry.prototype, 'arrayBuffer', ); expected = { writable: true, enumerable: true, configurable: true, value: KVStoreEntry.prototype.arrayBuffer, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'arrayBuffer')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'body'); strictEqual( actual.enumerable, true, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'body').enumerable`, ); strictEqual( actual.configurable, true, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'body').configurable`, ); strictEqual( 'set' in actual, true, `'set' in Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'body')`, ); strictEqual( actual.set, undefined, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'body').set`, ); strictEqual( typeof actual.get, 'function', `typeof Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'body').get`, ); actual = Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'bodyUsed'); strictEqual( actual.enumerable, true, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'bodyUsed').enumerable`, ); strictEqual( actual.configurable, true, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'bodyUsed').configurable`, ); strictEqual( 'set' in actual, true, `'set' in Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'bodyUsed')`, ); strictEqual( actual.set, undefined, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'bodyUsed').set`, ); strictEqual( typeof actual.get, 'function', `typeof Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype, 'bodyUsed').get`, ); strictEqual( typeof KVStoreEntry.prototype.constructor, 'function', `typeof KVStoreEntry.prototype.constructor`, ); strictEqual( typeof KVStoreEntry.prototype.text, 'function', `typeof KVStoreEntry.prototype.text`, ); strictEqual( typeof KVStoreEntry.prototype.json, 'function', `typeof KVStoreEntry.prototype.json`, ); strictEqual( typeof KVStoreEntry.prototype.arrayBuffer, 'function', `typeof KVStoreEntry.prototype.arrayBuffer`, ); actual = Reflect.getOwnPropertyDescriptor( KVStoreEntry.prototype.constructor, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( KVStoreEntry.prototype.constructor, 'name', ); expected = { value: 'KVStoreEntry', writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype.constructor, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor( KVStoreEntry.prototype.text, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype.text, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( KVStoreEntry.prototype.text, 'name', ); expected = { value: 'text', writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype.text, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor( KVStoreEntry.prototype.json, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype.json, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( KVStoreEntry.prototype.json, 'name', ); expected = { value: 'json', writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype.json, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor( KVStoreEntry.prototype.arrayBuffer, 'length', ); expected = { value: 0, writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype.arrayBuffer, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( KVStoreEntry.prototype.arrayBuffer, 'name', ); expected = { value: 'arrayBuffer', writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStoreEntry.prototype.arrayBuffer, 'name')`, ); } async function kvStoreInterfaceTests() { let actual = Reflect.ownKeys(KVStore); let expected = ['prototype', 'length', 'name']; deepStrictEqual(actual, expected, `Reflect.ownKeys(KVStore)`); actual = Reflect.getOwnPropertyDescriptor(KVStore, 'prototype'); expected = { value: KVStore.prototype, writable: false, enumerable: false, configurable: false, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore, 'prototype')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore, 'length'); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore, 'name'); expected = { value: 'KVStore', writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore, 'name')`, ); actual = Reflect.ownKeys(KVStore.prototype); expected = ['constructor', 'delete', 'get', 'put', 'list']; deepStrictEqual(actual, expected, `Reflect.ownKeys(KVStore.prototype)`); actual = Reflect.getOwnPropertyDescriptor(KVStore.prototype, 'constructor'); expected = { writable: true, enumerable: false, configurable: true, value: KVStore.prototype.constructor, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype, 'constructor')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore.prototype, 'delete'); expected = { writable: true, enumerable: true, configurable: true, value: KVStore.prototype.delete, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype, 'delete')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore.prototype, 'get'); expected = { writable: true, enumerable: true, configurable: true, value: KVStore.prototype.get, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype, 'get')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore.prototype, 'put'); expected = { writable: true, enumerable: true, configurable: true, value: KVStore.prototype.put, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype, 'put')`, ); strictEqual( typeof KVStore.prototype.constructor, 'function', `typeof KVStore.prototype.constructor`, ); strictEqual( typeof KVStore.prototype.delete, 'function', `typeof KVStore.prototype.delete`, ); strictEqual( typeof KVStore.prototype.get, 'function', `typeof KVStore.prototype.get`, ); strictEqual( typeof KVStore.prototype.put, 'function', `typeof KVStore.prototype.put`, ); actual = Reflect.getOwnPropertyDescriptor( KVStore.prototype.constructor, 'length', ); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype.constructor, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor( KVStore.prototype.constructor, 'name', ); expected = { value: 'KVStore', writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype.constructor, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore.prototype.delete, 'length'); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype.delete, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore.prototype.delete, 'name'); expected = { value: 'delete', writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype.delete, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore.prototype.get, 'length'); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype.get, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore.prototype.get, 'name'); expected = { value: 'get', writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype.get, 'name')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore.prototype.put, 'length'); expected = { value: 1, writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype.put, 'length')`, ); actual = Reflect.getOwnPropertyDescriptor(KVStore.prototype.put, 'name'); expected = { value: 'put', writable: false, enumerable: false, configurable: true, }; deepStrictEqual( actual, expected, `Reflect.getOwnPropertyDescriptor(KVStore.prototype.put, 'name')`, ); } // Test that HttpBody::read_all() correctly handles large list responses // (i.e. that it uses a growable buffer and doesn't overflow). // We populate the store with enough 1024-char keys that the list response JSON // would have exceeded the old 500000-byte fixed buffer. routes.set('/kv-store/list/large-response', async () => { const store = new KVStore(KV_STORE_NAME); // 490 keys × ~1024-char names ≈ 507 KB of JSON const prefix = 'large-list-' + 'a'.repeat(1009); await Promise.all( Array.from({ length: 490 }, (_, i) => store.put(prefix + String(i).padStart(4, '0'), 'x'), ), ); const result = await store.list({}); strictEqual(typeof result, 'object', 'list result is an object'); return new Response('ok'); }); function iteratableToStream(iterable) { return new ReadableStream({ async pull(controller) { for await (const value of iterable) { controller.enqueue(value); } controller.close(); }, }); } // TODO: Implement ReadableStream getIterator() and [@@asyncIterator]() methods async function streamToString(stream) { const decoder = new TextDecoder(); let string = ''; let reader = stream.getReader(); // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await reader.read(); if (done) { return string; } string += decoder.decode(value); } } ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/routes.js ================================================ import { env } from 'fastly:env'; /** * @type {Map Promise>} */ export const routes = new Map(); routes.set('/', () => { routes.delete('/'); let test_routes = Array.from(routes.keys()); return new Response(JSON.stringify(test_routes), { headers: { 'content-type': 'application/json' }, }); }); export function isRunningLocally() { return ( env('FASTLY_SERVICE_VERSION') === '' || env('FASTLY_SERVICE_VERSION') === '0' ); } ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/src/transform-stream.js ================================================ import { routes } from './routes.js'; function upperCase() { const decoder = new TextDecoder(); const encoder = new TextEncoder(); return new TransformStream({ transform(chunk, controller) { controller.enqueue(encoder.encode(decoder.decode(chunk).toUpperCase())); }, }); } routes.set('/transform-stream/identity', () => { return fetch('https://http-me.fastly.dev/test?body=hello').then( (response) => { return new Response(response.body.pipeThrough(new TransformStream())); }, ); }); routes.set('/transform-stream/uppercase', () => { return fetch('https://http-me.fastly.dev/test?body=hello').then( (response) => { return new Response(response.body.pipeThrough(upperCase())); }, ); }); routes.set('/transform-stream/parallel-uppercase', () => { return fetch('https://http-me.fastly.dev/test?body=hello').then( (response) => { return new Response(response.body.pipeThrough(upperCase())); }, ); }); // This is not a test, but the nested stream we loop back to in testing routes.set( '/transform-stream/multi-stream-forwarding/nested', async (event) => { let encoder = new TextEncoder(); let body = new TransformStream({ start(controller) {}, transform(chunk, controller) { controller.enqueue(encoder.encode(chunk)); }, flush(controller) {}, }); let writer = body.writable.getWriter(); event.respondWith(new Response(body.readable)); let word = new URL(event.request.url).searchParams.get('word'); console.log(`streaming word: ${word}`); for (let letter of word) { console.log(`Writing letter ${letter}`); await writer.write(letter); } if (word.endsWith('.')) { await writer.write('\n'); } await writer.close(); // tell the route handler not to call respondWith as we already did return false; }, ); routes.set('/transform-stream/multi-stream-forwarding', async (event) => { let fullBody = 'This sentence will be streamed in chunks.'; let responses = []; for (let word of fullBody.split(' ').join('+ ').split(' ')) { responses.push( (await fetch(`${event.request.url}/nested?word=${word}`)).body, ); } return new Response(concatStreams(responses)); }); function concatStreams(streams) { let { readable, writable } = new TransformStream(); async function iter() { for (let stream of streams) { try { await stream.pipeTo(writable, { preventClose: true }); } catch (e) { console.error(`error during pipeline execution: ${e}`); } } console.log('closing writable'); await writable.close(); } iter(); return readable; } ================================================ FILE: integration-tests/js-compute/fixtures/module-mode/tests.json ================================================ { "GET /acl": { "environments": ["compute"] }, "GET /backend/timeout": { "environments": ["compute"], "downstream_response": { "status": 200, "body": "ok" } }, "GET /implicit-dynamic-backend/dynamic-backends-disabled": {}, "GET /implicit-dynamic-backend/dynamic-backends-enabled": {}, "GET /implicit-dynamic-backend/dynamic-backends-enabled-called-twice": {}, "GET /explicit-dynamic-backend/dynamic-backends-enabled-all-fields": {}, "GET /explicit-dynamic-backend/dynamic-backends-enabled-minimal-fields": {}, "GET /backend/interface": {}, "GET /backend/constructor/called-as-regular-function": {}, "GET /backend/constructor/empty-parameter": {}, "GET /backend/constructor/parameter-not-an-object": {}, "GET /backend/constructor/parameter-name-property-null": {}, "GET /backend/constructor/parameter-name-property-undefined": {}, "GET /backend/constructor/parameter-name-property-too-long": {}, "GET /backend/constructor/parameter-name-property-empty-string": {}, "GET /backend/constructor/parameter-name-property-calls-7.1.17-ToString": {}, "GET /backend/constructor/parameter-target-property-null": {}, "GET /backend/constructor/parameter-target-property-undefined": {}, "GET /backend/constructor/parameter-target-property-empty-string": {}, "GET /backend/constructor/parameter-target-property-calls-7.1.17-ToString": {}, "GET /backend/constructor/parameter-target-property-valid-host": {}, "GET /backend/constructor/parameter-target-property-invalid-host": {}, "GET /backend/constructor/parameter-ciphers-property-empty-string": {}, "GET /backend/constructor/parameter-ciphers-property-invalid-cipherlist-string": {}, "GET /backend/constructor/parameter-ciphers-property-valid-cipherlist-strings-supported-by-fastly": {}, "GET /backend/constructor/parameter-ciphers-property-valid-cipherlist-strings-but-not-supported-by-fastly": {}, "GET /backend/constructor/parameter-ciphers-property-calls-7.1.17-ToString": {}, "GET /backend/constructor/parameter-ciphers-property-and-operator": {}, "GET /backend/constructor/parameter-hostOverride-property-empty-string": {}, "GET /backend/constructor/parameter-hostOverride-property-calls-7.1.17-ToString": {}, "GET /backend/constructor/parameter-hostOverride-property-valid-string": {}, "GET /backend/constructor/parameter-connectTimeout-property-negative-number": {}, "GET /backend/constructor/parameter-connectTimeout-property-too-big": {}, "GET /backend/constructor/parameter-connectTimeout-property-calls-7.1.4-ToNumber": {}, "GET /backend/constructor/parameter-connectTimeout-property-valid-number": {}, "GET /backend/constructor/parameter-firstByteTimeout-property-negative-number": {}, "GET /backend/constructor/parameter-firstByteTimeout-property-too-big": {}, "GET /backend/constructor/parameter-firstByteTimeout-property-calls-7.1.4-ToNumber": {}, "GET /backend/constructor/parameter-firstByteTimeout-property-valid-number": {}, "GET /backend/constructor/parameter-firstByteTimeout-property-invalid-number": {}, "GET /backend/constructor/parameter-betweenBytesTimeout-property-negative-number": {}, "GET /backend/constructor/parameter-betweenBytesTimeout-property-too-big": {}, "GET /backend/constructor/parameter-betweenBytesTimeout-property-calls-7.1.4-ToNumber": {}, "GET /backend/constructor/parameter-betweenBytesTimeout-property-valid-number": {}, "GET /backend/constructor/parameter-useSSL-property-valid-boolean": {}, "GET /backend/constructor/parameter-dontPool-property-valid-boolean": {}, "GET /backend/constructor/parameter-tlsMinVersion-property-nan": {}, "GET /backend/constructor/parameter-tlsMinVersion-property-invalid-number": {}, "GET /backend/constructor/parameter-tlsMinVersion-property-calls-7.1.4-ToNumber": {}, "GET /backend/constructor/parameter-tlsMinVersion-property-valid-number": {}, "GET /backend/constructor/parameter-tlsMinVersion-greater-than-tlsMaxVersion": {}, "GET /backend/constructor/parameter-tlsMaxVersion-property-nan": {}, "GET /backend/constructor/parameter-tlsMaxVersion-property-invalid-number": {}, "GET /backend/constructor/parameter-tlsMaxVersion-property-calls-7.1.4-ToNumber": {}, "GET /backend/constructor/parameter-tlsMaxVersion-property-valid-number": {}, "GET /backend/constructor/parameter-certificateHostname-property-empty-string": {}, "GET /backend/constructor/parameter-certificateHostname-property-calls-7.1.17-ToString": {}, "GET /backend/constructor/parameter-certificateHostname-property-valid-string": {}, "GET /backend/constructor/parameter-caCertificate-property-empty-string": {}, "GET /backend/constructor/parameter-caCertificate-property-calls-7.1.17-ToString": {}, "GET /backend/constructor/parameter-caCertificate-property-valid-string": {}, "GET /backend/constructor/parameter-sniHostname-property-empty-string": {}, "GET /backend/constructor/parameter-sniHostname-property-calls-7.1.17-ToString": {}, "GET /backend/constructor/parameter-sniHostname-property-valid-string": {}, "GET /backend/constructor/parameter-clientCertificate-property-invalid": {}, "GET /backend/constructor/parameter-clientCertificate-certificate-property-missing": {}, "GET /backend/constructor/parameter-clientCertificate-certificate-property-invalid": {}, "GET /backend/constructor/parameter-clientCertificate-key-property-missing": {}, "GET /backend/constructor/parameter-clientCertificate-key-property-invalid": {}, "GET /backend/constructor/parameter-clientCertificate-key-property-fake": {}, "GET /backend/constructor/parameter-clientCertificate-valid": {}, "GET /backend/constructor/parameter-grpc-property-falsy": {}, "GET /backend/constructor/parameter-grpc-enabled": {}, "GET /backend/constructor/http-keepalive-invalid": {}, "GET /backend/constructor/http-keepalive": {}, "GET /backend/constructor/tcp-keepalive-invalid": {}, "GET /backend/constructor/tcp-keepalive": {}, "GET /backend/set-default-backend-configuration": {}, "GET /backend/health/called-as-constructor-function": {}, "GET /backend/health/empty-parameter": {}, "GET /backend/health/parameter-calls-7.1.17-ToString": {}, "GET /backend/health/parameter-invalid": {}, "GET /backend/health/happy-path-backend-exists": {}, "GET /backend/health/happy-path-backend-does-not-exist": {}, "GET /backend/port-ip-defined": {}, "GET /backend/port-ip-cached": {}, "GET /backend/props": {}, "GET /console": { "environments": ["viceroy"], "logs": [ "stdout :: Log: Happy birthday Aki and Yuki!", "stdout :: Log: Map: Map(2) { { a: 1, b: { c: 2 } } => 2, [ function foo() {\n }] => {} }", "stdout :: Log: Set: Set(3) { { a: 1, b: { c: 2 } }, 2, 3 }", "stdout :: Log: Array: [1, 2, 3, [], 5]", "stdout :: Log: Object: { a: 1, b: 2, c: 3, d: [ d() {\n }], f: [Getter], g: [ function bar() {\n}], h: [ function from() {\n[native code]\n}] }", "stdout :: Log: function: [ function() {\n }]", "stdout :: Log: boolean: true", "stdout :: Log: undefined: undefined", "stdout :: Log: null: null", "stdout :: Log: proxy: { a: 21 }", "stdout :: Log: Infinity: Infinity", "stdout :: Log: NaN: NaN", "stdout :: Log: Symbol: Symbol(\"wow\")", "stdout :: Log: Error: (new Error(\"uh oh\", \"\", 7644))", "stdout :: Log: Number: 1", "stdout :: Log: Number: 1.111", "stdout :: Log: BigInt: 10n", "stdout :: Log: Date: new Date(1660816667120)", "stdout :: Log: string: cake", "stdout :: Log: RegExp: /magic/", "stdout :: Log: Int8Array: Int8Array [1, 3, 4, 2, 5, 6, -97]", "stdout :: Log: Uint8Array: Uint8Array [1, 3, 4, 2, 5, 6, 159]", "stdout :: Log: Uint8ClampedArray: Uint8ClampedArray [1, 3, 4, 2, 5, 6, 255]", "stdout :: Log: Int16Array: Int16Array [1, 3, 4, 2, 5, 6, -31073]", "stdout :: Log: Uint16Array: Uint16Array [1, 3, 4, 2, 5, 6, 34463]", "stdout :: Log: Int32Array: Int32Array [1, 3, 4, 2, 5, 6, 99999]", "stdout :: Log: Uint32Array: Uint32Array [1, 3, 4, 2, 5, 6, 99999]", "stdout :: Log: Float32Array: Float32Array [1, 3, 4, 2, 5, 6, 99999]", "stdout :: Log: Float64Array: Float64Array [1, 3, 4, 2, 5, 6, 99999]", "stdout :: Log: BigInt64Array: BigInt64Array [1n, 3n, 4n, 2n, 5n, 6n, 99999n]", "stdout :: Log: BigUint64Array: BigUint64Array [1n, 3n, 4n, 2n, 5n, 6n, 99999n]", "stdout :: Log: WeakMap: WeakMap { }", "stdout :: Log: WeakSet: WeakSet { }", "stdout :: Log: Promise: Promise { }", "stdout :: Log: resolved promise: Promise { 9 }", "stdout :: Log: rejected promise: Promise { (new Error(\"oops\", \"\", 7689)) }", "stdout :: Log: Response: Response { redirected: false, type: \"default\", url: \"\", status: 200, ok: true, statusText: \"\", version: 2, headers: Headers {}, body: ReadableStream { locked: false }, bodyUsed: false }", "stdout :: Log: Request: Request { method: \"POST\", url: \"https://www.fastly.com/\", version: 2, headers: Headers {}, backend: undefined, body: null, bodyUsed: false }", "stdout :: Log: ReadableStream: ReadableStream { locked: false }", "stdout :: Log: TransformStream: TransformStream { readable: ReadableStream { locked: false }, writable: WritableStream {} }", "stdout :: Log: WritableStream: WritableStream {}", "stdout :: Log: URL: URL { hash: \"\", host: \"www.test.com:123\", hostname: \"www.test.com\", href: \"https://www.test.com:123/asdf?some¶ms=val\", origin: \"https://www.test.com:123\", password: \"\", pathname: \"/asdf\", port: \"123\", protocol: \"https:\", search: \"?some¶ms=val\", searchParams: URLSearchParams {}, username: \"\" }" ] }, "GET /hello-world": { "downstream_response": { "status": 200, "body": "hello world" } }, "GET /hono": { "downstream_response": { "status": 200, "body_prefix": "{\n \"args\": \"\"," } }, "GET /http-cache/hook-errors": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/invalid-properties": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/readonly-properties": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/property-errors": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/candidate-response-properties-cached": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/candidate-response-properties-uncached": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/before-send-errors": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/before-send": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/after-send-no-cache": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/after-send-header-remove": { "environments": ["compute"], "features": ["http-cache"], "downstream_response": { "headers": { "content-length": true, "date": true, "content-type": true, "fastly_service_version": true, "custom": "custom-header", "x-cache": true, "x-cache-hits": true, "x-served-by": true }, "headersExhaustive": true } }, "GET /http-cache/after-send-cache": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/after-send-cache-expire": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/after-send-pass": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/after-send-res-no-body": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/response-mutations": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/stale-responses": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/invalid-transform": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/body-transform": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/body-transform-delay": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/body-transform-error": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/body-transform-error-delay": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/body-transform-invalid-chunk": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/concurrent-transforms": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/sequential": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/sequential-three": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/sequential-request-collapsing-uncacheable": { "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/sequential-request-collapsing-vary": { "skip": true, "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/parallel": { "skip": true, "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/parallel-three": { "skip": true, "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/parallel-request-collapsing-uncacheable": { "skip": true, "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/parallel-request-collapsing-vary": { "skip": true, "environments": ["compute"], "features": ["http-cache"] }, "GET /http-cache/cache-key-on-request": { "environments": ["compute"], "features": ["http-cache"] }, "GET /kv-store-e2e/list": { "flake": true }, "GET /kv-store/exposed-as-global": {}, "GET /kv-store/interface": { "flake": true }, "GET /kv-store/constructor/called-as-regular-function": {}, "GET /kv-store/constructor/parameter-calls-7.1.17-ToString": {}, "GET /kv-store/constructor/empty-parameter": {}, "GET /kv-store/constructor/found-store": { "flake": true }, "GET /kv-store/constructor/missing-store": {}, "GET /kv-store/constructor/invalid-name": {}, "GET /kv-store/put/called-as-constructor": {}, "GET /kv-store/put/called-unbound": {}, "GET /kv-store/put/key-parameter-calls-7.1.17-ToString": { "flake": true }, "GET /kv-store/put/key-parameter-not-supplied": { "flake": true }, "GET /kv-store/put/key-parameter-empty-string": { "flake": true }, "GET /kv-store/put/key-parameter-1024-character-string": { "flake": true }, "GET /kv-store/put/key-parameter-1025-character-string": { "flake": true }, "GET /kv-store/put/key-parameter-containing-newline": { "flake": true }, "GET /kv-store/put/key-parameter-containing-carriage-return": { "flake": true }, "GET /kv-store/put/key-parameter-starting-with-well-known-acme-challenge": { "flake": true }, "GET /kv-store/put/key-parameter-single-dot": { "flake": true }, "GET /kv-store/put/key-parameter-double-dot": { "flake": true }, "GET /kv-store/put/key-parameter-containing-special-characters": { "flake": true }, "GET /kv-store/put/value-parameter-as-undefined": { "flake": true }, "GET /kv-store/put/value-parameter-not-supplied": { "flake": true }, "GET /kv-store/put/value-parameter-readablestream-empty": { "flake": true }, "GET /kv-store/put/value-parameter-readablestream-under-30mb": { "flake": true }, "GET /kv-store/put/value-parameter-readablestream-over-30mb": { "flake": true }, "GET /kv-store/put/value-parameter-readablestream-locked": { "flake": true }, "GET /kv-store/put/value-parameter-URLSearchParams": { "flake": true }, "GET /kv-store/put/value-parameter-strings": { "flake": true }, "GET /kv-store/put/value-parameter-string-over-30mb": { "flake": true }, "GET /kv-store/put/value-parameter-calls-7.1.17-ToString": { "flake": true }, "GET /kv-store/put/value-parameter-buffer": { "flake": true }, "GET /kv-store/put/value-parameter-arraybuffer": { "flake": true }, "GET /kv-store/put/value-parameter-typed-arrays": { "flake": true }, "GET /kv-store/put/value-parameter-dataview": { "flake": true }, "POST /kv-store/put/request-body": { "flake": true, "environments": ["compute"], "downstream_request": { "method": "POST", "pathname": "/kv-store/put/request-body", "headers": ["Content-Type", "application/json"], "body": "hello world!" } }, "GET /kv-store/debug-error": { "flake": true }, "GET /kv-store/delete/called-as-constructor": { "flake": true }, "GET /kv-store/delete/called-unbound": { "flake": true }, "GET /kv-store/delete/key-parameter-calls-7.1.17-ToString": { "flake": true }, "GET /kv-store/delete/key-parameter-not-supplied": { "flake": true }, "GET /kv-store/delete/key-parameter-empty-string": { "flake": true }, "GET /kv-store/delete/key-parameter-1024-character-string": { "flake": true }, "GET /kv-store/delete/key-parameter-1025-character-string": { "flake": true }, "GET /kv-store/delete/key-parameter-containing-newline": { "flake": true }, "GET /kv-store/delete/key-parameter-containing-carriage-return": { "flake": true }, "GET /kv-store/delete/key-parameter-starting-with-well-known-acme-challenge": { "flake": true }, "GET /kv-store/delete/key-parameter-single-dot": { "flake": true }, "GET /kv-store/delete/key-parameter-double-dot": { "flake": true }, "GET /kv-store/delete/key-parameter-containing-special-characters": { "flake": true }, "GET /kv-store/delete/key-does-not-exist-returns-undefined": { "flake": true }, "GET /kv-store/delete/key-exists": { "flake": true }, "GET /kv-store/delete/delete-key-twice": { "flake": true }, "GET /kv-store/delete/multiple-deletes-at-once": { "flake": true }, "GET /kv-store/get/called-as-constructor": { "flake": true }, "GET /kv-store/get/called-unbound": { "flake": true }, "GET /kv-store/get/key-parameter-calls-7.1.17-ToString": { "flake": true }, "GET /kv-store/get/key-parameter-not-supplied": { "flake": true }, "GET /kv-store/get/key-parameter-empty-string": { "flake": true }, "GET /kv-store/get/key-parameter-1024-character-string": { "flake": true }, "GET /kv-store/get/key-parameter-1025-character-string": { "flake": true }, "GET /kv-store/get/key-parameter-containing-newline": { "flake": true }, "GET /kv-store/get/key-parameter-containing-carriage-return": { "flake": true }, "GET /kv-store/get/key-parameter-starting-with-well-known-acme-challenge": { "flake": true }, "GET /kv-store/get/key-parameter-single-dot": { "flake": true }, "GET /kv-store/get/key-parameter-double-dot": { "flake": true }, "GET /kv-store/get/key-parameter-containing-special-characters": { "flake": true }, "GET /kv-store/get/key-does-not-exist-returns-null": { "flake": true }, "GET /kv-store/get/key-exists": { "flake": true }, "GET /kv-store/get/multiple-lookups-at-once": { "flake": true }, "GET /kv-store-entry/interface": { "flake": true }, "GET /kv-store-entry/text/valid": { "flake": true }, "GET /kv-store-entry/json/valid": { "flake": true }, "GET /kv-store-entry/json/invalid": { "flake": true }, "GET /kv-store-entry/arrayBuffer/valid": { "flake": true }, "GET /kv-store-options/gen": { "skip": true, "flake": true }, "GET /kv-store-options/gen-invalid": { "flake": true }, "GET /kv-store-entry/body": { "flake": true }, "GET /kv-store-entry/bodyUsed": { "flake": true }, "GET /kv-store/list/large-response": { "flake": true }, "GET /transform-stream/identity": { "downstream_response": { "body": "hello" } }, "GET /transform-stream/uppercase": { "downstream_response": { "body": "HELLO" } }, "GET /transform-stream/multi-stream-forwarding": { "environments": ["viceroy"], "downstream_response": { "body": "This sentence will be streamed in chunks." } } } ================================================ FILE: integration-tests/js-compute/fixtures/reusable-sandboxes/fastly.toml.in ================================================ # This file describes a Fastly Compute package. To learn more visit: # https://developer.fastly.com/reference/fastly-toml/ authors = ["ulyssa.mello@fastly.com"] description = "" language = "other" manifest_version = 2 name = "js-test-reusable-sandboxes" service_id = "" [scripts] build = "node ../../../../dist/cli/js-compute-runtime-cli.js --env FASTLY_DEBUG_LOGGING,ACL_NAME,CONFIG_STORE_NAME,DICTIONARY_NAME,KV_STORE_NAME,SECRET_STORE_NAME,LOCAL_TEST,TEST=\"foo\" --enable-experimental-high-resolution-time-methods src/index.js" [local_server] [local_server.backends] [local_server.backends.TheOrigin] url = "https://compute-sdk-test-backend.edgecompute.app" override_host = "compute-sdk-test-backend.edgecompute.app" [local_server.backends.TheOrigin2] url = "https://compute-sdk-test-backend.edgecompute.app" override_host = "compute-sdk-test-backend.edgecompute.app" [local_server.backends.httpme] url = "https://http-me.fastly.dev" override_host = "http-me.fastly.dev" [local_server.config_stores] [local_server.config_stores.CONFIG_STORE_NAME] format = "inline-toml" [local_server.config_stores.CONFIG_STORE_NAME.contents] "twitter" = "https://twitter.com/fastly" [local_server.config_stores."DICTIONARY_NAME"] format = "inline-toml" [local_server.config_stores."DICTIONARY_NAME".contents] "twitter" = "https://twitter.com/fastly" [local_server.geolocation] format = "inline-toml" [local_server.geolocation.addresses] [local_server.geolocation.addresses."2.216.196.179"] as_name = "sky uk limited" as_number = 5607 area_code = 0 city = "bircotes" conn_speed = "broadband" conn_type = "wifi" continent = "EU" country_code = "GB" country_code3 = "GBR" country_name = "united kingdom" gmt_offset = 0 latitude = 53.42 longitude = -1.05 metro_code = 826039 postal_code = "dn11 8af" proxy_description = "?" proxy_type = "?" region = "NTT" utc_offset = 0 [local_server.geolocation.addresses."2607:f0d0:1002:51::4"] as_name = "softlayer technologies inc." as_number = 36351 area_code = 214 city = "dallas" conn_speed = "broadband" conn_type = "wired" continent = "NA" country_code = "US" country_code3 = "USA" country_name = "united states" gmt_offset = -600 latitude = 32.94 longitude = -96.84 metro_code = 623 postal_code = "75244" proxy_description = "?" proxy_type = "hosting" region = "TX" utc_offset = -600 [setup] [setup.backends] [setup.backends.httpme] address = "http-me.fastly.dev" port = 443 [setup.backends.TheOrigin] address = "compute-sdk-test-backend.edgecompute.app" port = 443 [setup.backends.TheOrigin2] address = "compute-sdk-test-backend.edgecompute.app" port = 443 ================================================ FILE: integration-tests/js-compute/fixtures/reusable-sandboxes/src/assertions.js ================================================ export function strictEqual(actual, expected, message) { if (actual !== expected) { throw new Error( `Expected \`${JSON.stringify(actual)}\` to equal \`${JSON.stringify(expected)}\`${message ? '\n' + message : ''}`, ); } } export function assert(truthy, maybeMessage) { if (!truthy) { throw new Error(`Assertion failed: ${maybeMessage}`); } } export { assert as ok }; export async function assertResolves(func) { try { await func(); } catch (error) { throw new Error( `Expected \`${func.toString()}\` to resolve - Found it rejected: ${error.name}: ${error.message}`, ); } } export async function assertRejects(func, errorClass, errorMessage) { try { await func(); } catch (error) { if (errorClass) { if (error instanceof errorClass === false) { throw new Error( `Expected \`${func.toString()}\` to reject instance of \`${errorClass.name}\` - Found instance of \`${error.name}\``, ); } } if (errorMessage) { if (error.message !== errorMessage) { throw new Error( `Expected \`${func.toString()}\` to reject error message of \`${errorMessage}\` - Found \`${error.message}\``, ); } } return; } throw new Error( `Expected \`${func.toString()}\` to reject - Found it did not reject`, ); } export function assertThrows(func, errorClass, errorMessage) { try { func(); } catch (error) { if (errorClass) { if (error instanceof errorClass === false) { throw new Error( `Expected \`${func.toString()}\` to throw instance of \`${errorClass.name}\` - Found instance of \`${error.name}\`: ${error.message}\n${error.stack}`, ); } } if (errorMessage) { if (error.message !== errorMessage) { throw new Error( `Expected \`${func.toString()}\` to throw error message of \`${errorMessage}\` - Found \`${error.message}\``, ); } } return; } throw new Error( `Expected \`${func.toString()}\` to throw - Found it did not throw`, ); } export function assertDoesNotThrow(func) { try { func(); } catch (error) { throw new Error( `Expected \`${func.toString()}\` to not throw - Found it did throw: ${error.name}: ${error.message}`, ); } } export function deepStrictEqual(a, b) { if (!deepEqual(a, b)) { throw new Error( `Expected ${a} to equal ${b}, got ${JSON.stringify(a, null, 2)}`, ); } } export function deepEqual(a, b) { var aKeys; var bKeys; var typeA; var typeB; var key; var i; typeA = typeof a; typeB = typeof b; if (a === null || typeA !== 'object') { if (b === null || typeB !== 'object') { return a === b; } return false; } // Case: `a` is of type 'object' if (b === null || typeB !== 'object') { return false; } if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) { return false; } if (a instanceof Date) { return a.getTime() === b.getTime(); } if (a instanceof RegExp) { return a.source === b.source && a.flags === b.flags; } if (a instanceof Error) { if (a.message !== b.message || a.name !== b.name) { return false; } } aKeys = Object.keys(a); bKeys = Object.keys(b); if (aKeys.length !== bKeys.length) { return false; } aKeys.sort(); bKeys.sort(); // Cheap key test: for (i = 0; i < aKeys.length; i++) { if (aKeys[i] !== bKeys[i]) { return false; } } // Possibly expensive deep equality test for each corresponding key: for (i = 0; i < aKeys.length; i++) { key = aKeys[i]; if (!deepEqual(a[key], b[key])) { return false; } } return typeA === typeB; } ================================================ FILE: integration-tests/js-compute/fixtures/reusable-sandboxes/src/index.js ================================================ /// /* eslint-env serviceworker */ import { assert, assertThrows, strictEqual } from './assertions.js'; import { isRunningLocally, routes } from './routes.js'; import { env } from 'fastly:env'; import { enableDebugLogging } from 'fastly:experimental'; import { setReusableSandboxOptions } from 'fastly:experimental'; setReusableSandboxOptions({ maxRequests: 9001 }); import './interleave.js'; addEventListener('fetch', (event) => { // Ensure these reusable sandboxes tests are running locally so that // we don't flake due to requests landing on different cache nodes: assert(isRunningLocally()); const responsePromise = app(event); if (responsePromise) event.respondWith(responsePromise); }); if (env('FASTLY_DEBUG_LOGGING') === '1') { if (fastly.debugMessages) { const { debug: consoleDebug } = console; console.debug = function debug(...args) { fastly.debugLog(...args); consoleDebug(...args); }; } enableDebugLogging(true); } /** * @param {FetchEvent} event * @returns {Response} */ async function app(event) { const FASTLY_SERVICE_VERSION = env('FASTLY_SERVICE_VERSION') || 'local'; const FASTLY_TRACE_ID = env('FASTLY_TRACE_ID'); console.log(`FASTLY_SERVICE_VERSION: ${FASTLY_SERVICE_VERSION}`); const path = new URL(event.request.url).pathname; console.log(`path: ${path}`); let res; try { const routeHandler = routes.get(path); if (routeHandler) { res = await routeHandler(event); if (res !== null) { res = res || new Response('ok'); } } else { return (res = new Response(`${path} endpoint does not exist`, { status: 500, })); } } catch (error) { if (error instanceof Response) { res = error; } else { try { return (res = new Response( `The routeHandler for ${path} threw a [${error.constructor?.name ?? error.name}] error: ${error.message || error}` + '\n' + error.stack + (fastly.debugMessages ? '\n[DEBUG BUILD MESSAGES]:\n\n - ' + fastly.debugMessages.join('\n - ') : ''), { status: 500 }, )); } catch (errRes) { res = errRes; } } } finally { res.headers.set('fastly_service_version', FASTLY_SERVICE_VERSION); res.headers.set('sandbox-id', FASTLY_TRACE_ID); } return res; } ================================================ FILE: integration-tests/js-compute/fixtures/reusable-sandboxes/src/interleave.js ================================================ /* eslint-env serviceworker */ /* global fastly */ // This module contains routes that allow us to verify the behaviour // of interleaving different types of downstream responses, such as // WebSocket redirects mixed with normal HTTP responses, mixed with // streaming responses to backend requests. import { assert } from './assertions.js'; import { CacheOverride } from 'fastly:cache-override'; import { getGeolocationForIpAddress } from 'fastly:geolocation'; import { createFanoutHandoff } from 'fastly:fanout'; import { routes } from './routes.js'; function timeout(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } // Handler for generating the websocket redirect hostcall: routes.set('/createFanoutHandoff', (event) => { return createFanoutHandoff(event.request, 'TheOrigin'); }); // Handler for generating a backend request to http-me.fastly.dev: routes.set('/httpMeRequest', async (event) => { const req = new Request( 'https://http-me.fastly.dev/status=200&header=FooName:FooValue', { method: 'GET', headers: event.request.headers, }, ); const resp = await fetch(req, { backend: 'httpme', cacheOverride: new CacheOverride('pass'), }); return resp; }); routes.set('/getGeolocationForIpAddress', async (event) => { let ip = event.request.headers.get('x-forwarded-for'); assert(ip !== undefined, 'request has x-forwarded-for header'); // Sleep to ensure other items on the event loop get a chance to run: await timeout(1000); let geo = getGeolocationForIpAddress(ip); assert(geo !== null, `resolved ${ip} to geo information`); return new Response('found', { status: 200, headers: new Headers({ 'geo-as-name': geo.as_name, 'geo-as-number': geo.as_number, 'geo-city': geo.city, }), }); }); ================================================ FILE: integration-tests/js-compute/fixtures/reusable-sandboxes/src/routes.js ================================================ import { env } from 'fastly:env'; /** * @type {Map Promise>} */ export const routes = new Map(); routes.set('/', () => { routes.delete('/'); let test_routes = Array.from(routes.keys()); return new Response(JSON.stringify(test_routes), { headers: { 'content-type': 'application/json' }, }); }); export function isRunningLocally() { return ( env('FASTLY_SERVICE_VERSION') === '' || env('FASTLY_SERVICE_VERSION') === '0' ); } ================================================ FILE: integration-tests/js-compute/fixtures/reusable-sandboxes/tests.json ================================================ { "session #1, request #1: GET /getGeolocationForIpAddress": { "environments": ["viceroy"], "downstream_request": { "method": "GET", "pathname": "/getGeolocationForIpAddress", "headers": ["x-forwarded-for", "2.216.196.179"] }, "downstream_response": { "status": 200, "headers": { "sandbox-id": "00000000000000000000000000000000", "geo-as-name": "sky uk limited", "geo-as-number": "5607", "geo-city": "bircotes" }, "body": "found" } }, "session #1, request #2: GET /createFanoutHandoff": { "environments": ["viceroy"], "downstream_request": { "method": "GET", "pathname": "/createFanoutHandoff" }, "downstream_response": { "status": 500, "body": "Error: Could not connect to Pushpin" } }, "session #1, request #3: GET /getGeolocationForIpAddress": { "environments": ["viceroy"], "downstream_request": { "method": "GET", "pathname": "/getGeolocationForIpAddress", "headers": ["x-forwarded-for", "2607:f0d0:1002:51::4"] }, "downstream_response": { "status": 200, "headers": { "sandbox-id": "00000000000000000000000000000000", "geo-as-name": "softlayer technologies inc.", "geo-as-number": "36351", "geo-city": "dallas" }, "body": "found" } }, "session #1, request #4: GET /httpMeRequest": { "environments": ["viceroy"], "downstream_request": { "method": "GET", "pathname": "/httpMeRequest", "headers": { "HM-Status": "200", "HM-Header": "FooName:FooValue", "HM-Append-Header": "BarName:BarValue", "HM-Wait": "1000" } }, "downstream_response": { "status": 200, "headers": { "sandbox-id": "00000000000000000000000000000000", "FooName": "FooValue", "BarName": "BarValue" } } }, "session #1, request #5: GET /createFanoutHandoff": { "environments": ["viceroy"], "downstream_request": { "method": "GET", "pathname": "/createFanoutHandoff" }, "downstream_response": { "status": 500, "body": "Error: Could not connect to Pushpin" } }, "session #2, request #1: GET /httpMeRequest": { "environments": ["viceroy"], "downstream_request": { "method": "GET", "pathname": "/httpMeRequest", "headers": { "HM-Status": "200", "HM-Header": "BazName:BazValue", "HM-Append-Header": "QuuxName:QuuxValue", "HM-Wait": "1000" } }, "downstream_response": { "status": 200, "headers": { "sandbox-id": "00000000000000000000000000000006", "BazName": "BazValue", "QuuxName": "QuuxValue" } } } } ================================================ FILE: integration-tests/js-compute/package.json ================================================ { "scripts": { "install:ci": "npm ci", "lint": "npx prettier --write ./fixtures/**/*.js" }, "devDependencies": { "eslint": "^10", "prettier": "^3" }, "dependencies": { "@actions/core": "^3", "@iarna/toml": "^2", "fast-check": "^4", "undici": "^8", "zx": "^8" }, "type": "module" } ================================================ FILE: integration-tests/js-compute/readme.md ================================================ # Writing Integration Tests for JS-Compute-Runtime - Create a folder within [fixtures](./fixtures) which will contain the test Fastly Compute application - Create a javascript or typescript file within the folder with the same name as the folder, this file should contain the test Fastly Compute application. - Create a fastly.toml.in file which contains any backends that the application requires. This file should adhere to the format defined at - Create a tests.json file which following the format defined below. ## Fields in tests.json tests.json is a file containing a JSON Object which contains all the test requests and assertions for the Fastly Compute application being tested. The keys in the root object are used as the name of the tests. ### environments An array of strings which states in what environments the test should run. Valid strings which can be in the array are: - 'viceroy' - This states that the test should run in the Viceroy environment. - 'compute' - This states that the test should run in the Fastly Compute environment. ### downstream_request An Object which determines how the request to the test application should be configured. The Object can contain the four properties: - method - pathname - body - headers #### method A string which is the name of the method that the request should use. E.G. `"GET"` will make the request be a GET request. #### pathname A string which is the path and querystring that the request should use. E.G. `"/"` will make the request go to `"/"` and `"/?colour=blue"` will make the request go to `"/?colour=blue"`. #### body A string which would be used as the request's body. #### headers An object which contains string keys and values that would each be used as a request header. E.G. `{"a": "1", "b": "2" }` will set two headers on the request, a header named `a` with the value `1` and a header named `b` with the value `2`. ### local_upstream_requests An Array of Objects which are used to assert against requests that the test application may have made during it's execution. The Objects can contain the five properties: - method - pathname - body - headers - timing #### method A string which is the name of the method to assert that the test application request has used during it's execution. E.G. `"GET"` will assert that the upstream request was a GET request. #### pathname A string which is the path and querystring to assert that the test application request has used during it's execution. E.G. `"/?colour=blue"` will assert that the upstream request was made to `"/?colour=blue"`. #### body A string which is the body to assert that the upstream request has used during it's execution. #### headers An object which contains string keys and values that would each be used as an assertion that the test application request has each header set during it's execution. E.G. `{"a": "1", "b": "2" }` will assert that the upstream Request only has the headers named `a` with the value `1` and a header named `b` with the value `2`. #### timing A string set to `"afterDownstreamrequest"` to assert that the test application request happened after the downstream request. If ommited, then no asserton will be made on when the upstream request happened. ### downstream_response An Object which is used to assert against the response that the test application responded with. The Object can contain the three properties: - status - body - headers #### status A number which is the status to assert that the test application response has used. E.G. `204` will assert that the response had a status set to 204. #### body A string or array which is the body to assert that the upstream request has used during it's execution. If a string then the assertion is done on the entire response body. If an array then assertions are done on each individual chunk received from response as a stream. #### headers An array which contains arrays, where each array contains two strings, the first is the header name and the second is the header value. E.G. `{"a": "1", "b": "2" }` will assert that the response only has the headers named `a` with the value `1` and a header named `b` with the value `2`. ### logs An array which contains strings used to assert against any logs emitted by the test application during it's execution. E.G. `["ComputeLog :: Hello!"]` will assert that the application emitted a log-line containing only the string `"ComputeLog :: Hello!"`. ## Example tests.json file ```json { "test for GET /example": { "environments": ["viceroy", "compute"], "downstream_request": { "method": "GET", "pathname": "/example", "headers": ["food", "carrot"] }, "downstream_response": { "status": 200, "headers": [ ["carrot", "yes"], ["potato", "no"] ], "body": "response from /example" }, "local_upstream_requests": [ { "method": "POST", "pathname": "/upstream-after-downstream", "headers": [["test-header", "test-header-value"]], "body": "pow wow", "timing": "afterDownstreamrequest" }, { "method": "GET", "pathname": "/upstream" } ] } } ``` ================================================ FILE: integration-tests/js-compute/replace-host.sh ================================================ #!/usr/bin/env bash set -euo pipefail if [ "$#" -lt 2 ]; then cat < Replace the host and protocol part of each backend's url with another one. This will only replace instances of "JS_COMPUTE_TEST_BACKEND", as other urls might be meaningful for an individual test. EOF exit 1 fi fixtures_dir="$(dirname "${BASH_SOURCE[0]}")/fixtures" fastly_toml="$fixtures_dir/$1/fastly.toml" fastly_toml_in="$fixtures_dir/$1/fastly.toml.in" override_host="$2" sed -e "s|JS_COMPUTE_TEST_BACKEND|$override_host|" "$fastly_toml_in" > "$fastly_toml" ================================================ FILE: integration-tests/js-compute/setup.js ================================================ #!/usr/bin/env node import { $ as zx } from 'zx'; import { argv } from 'node:process'; import { getEnv } from './env.js'; import { $ } from './util.js'; const serviceId = argv[2]; const serviceName = argv[3]; const env = getEnv(serviceName); Object.assign(process.env, env); const { DICTIONARY_NAME, CONFIG_STORE_NAME, KV_STORE_NAME, SECRET_STORE_NAME, ACL_NAME, } = env; function existingListId(stores, existingName) { const existing = stores.find( ({ Name, name }) => name === existingName || Name === existingName, ); return existing?.id || existing?.StoreID; } if (process.env.FASTLY_API_TOKEN === undefined) { zx.verbose = false; try { process.env.FASTLY_API_TOKEN = String( await $`fastly profile token --quiet`, ).trim(); } catch { console.error( 'No environment variable named FASTLY_API_TOKEN has been set and no default fastly profile exists.', ); console.error( 'In order to run the tests, either create a fastly profile using `fastly profile create` or export a fastly token under the name FASTLY_API_TOKEN', ); process.exit(1); } zx.verbose = true; } async function setupConfigStores() { const stores = JSON.parse( await $`fastly config-store list --quiet --json --token $FASTLY_API_TOKEN`, ); let STORE_ID = existingListId(stores, DICTIONARY_NAME); if (!STORE_ID) { console.log(`Creating new config store ${DICTIONARY_NAME}`); STORE_ID = JSON.parse( await $`fastly config-store create --quiet --name="$DICTIONARY_NAME" --json --token $FASTLY_API_TOKEN`, ).id; } else { console.log(`Using existing config store ${DICTIONARY_NAME}`); } await $`echo -n 'https://twitter.com/fastly' | fastly config-store-entry update --upsert --key twitter --store-id=${STORE_ID} --stdin --token $FASTLY_API_TOKEN`; try { await $`fastly service resource-link create --service-id ${serviceId} --version latest --resource-id ${STORE_ID} --token $FASTLY_API_TOKEN --autoclone`; } catch (e) { if (!e.message.includes('Duplicate record')) throw e; } STORE_ID = existingListId(stores, CONFIG_STORE_NAME); if (!STORE_ID) { console.log(`Creating new config store ${CONFIG_STORE_NAME}`); STORE_ID = JSON.parse( await $`fastly config-store create --quiet --name="$CONFIG_STORE_NAME" --json --token $FASTLY_API_TOKEN`, ).id; } else { console.log(`Using existing config store ${CONFIG_STORE_NAME}`); } await $`echo -n 'https://twitter.com/fastly' | fastly config-store-entry update --upsert --key twitter --store-id=${STORE_ID} --stdin --token $FASTLY_API_TOKEN`; try { await $`fastly service resource-link create --service-id ${serviceId} --version latest --resource-id ${STORE_ID} --token $FASTLY_API_TOKEN --autoclone`; } catch (e) { if (!e.message.includes('Duplicate record')) throw e; } } async function setupKVStore() { let stores = JSON.parse( await $`fastly kv-store list --quiet --json --token $FASTLY_API_TOKEN`, ).Data; let STORE_ID = existingListId(stores, KV_STORE_NAME); if (!STORE_ID) { console.log(`Creating new KV store ${KV_STORE_NAME}`); STORE_ID = JSON.parse( await $`fastly kv-store create --quiet --name="$KV_STORE_NAME" --json --token $FASTLY_API_TOKEN`, ).StoreID; } else { console.log(`Using existing KV store ${KV_STORE_NAME}`); } try { await $`fastly service resource-link create --service-id ${serviceId} --version latest --resource-id ${STORE_ID} --token $FASTLY_API_TOKEN --autoclone`; } catch (e) { if (!e.message.includes('Duplicate record')) throw e; } } async function setupSecretStore() { const stores = JSON.parse( await $`fastly secret-store list --quiet --json --token $FASTLY_API_TOKEN`, ); let STORE_ID = stores && existingListId(stores, SECRET_STORE_NAME); if (!STORE_ID) { console.log(`Creating new secret store ${SECRET_STORE_NAME}`); STORE_ID = JSON.parse( await $`fastly secret-store create --quiet --name="$SECRET_STORE_NAME" --json --token $FASTLY_API_TOKEN`, ).id; } else { console.log(`Using existing secret store ${SECRET_STORE_NAME}`); } await $`echo -n 'This is also some secret data' | fastly secret-store-entry create --recreate-allow --name first --store-id=${STORE_ID} --stdin --token $FASTLY_API_TOKEN`; let key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; await $`echo -n 'This is some secret data' | fastly secret-store-entry create --recreate-allow --name ${key} --store-id=${STORE_ID} --stdin --token $FASTLY_API_TOKEN`; try { await $`fastly service resource-link create --service-id ${serviceId} --version latest --resource-id ${STORE_ID} --token $FASTLY_API_TOKEN --autoclone`; } catch (e) { if (!e.message.includes('Duplicate record')) throw e; } } async function setupAcl() { let ACL_ID = existingListId( JSON.parse( await $`fastly compute acl list-acls --quiet --json --token $FASTLY_API_TOKEN`, ).data, ACL_NAME, ); if (!ACL_ID) { console.log(`Creating ACL ${ACL_NAME}`); ACL_ID = JSON.parse( await $`fastly compute acl create --name="$ACL_NAME" --token $FASTLY_API_TOKEN --json`, ).id; await $`fastly compute acl update --acl-id=${ACL_ID} --operation=create --prefix=100.100.0.0/16 --action=BLOCK --token $FASTLY_API_TOKEN`; await $`fastly compute acl update --acl-id=${ACL_ID} --operation=create --prefix=2a03:4b80::/32 --action=ALLOW --token $FASTLY_API_TOKEN`; } else { console.log(`Using existing ACL ${ACL_NAME}`); } try { await $`fastly service resource-link create --service-id ${serviceId} --version latest --resource-id ${ACL_ID} --token $FASTLY_API_TOKEN --autoclone`; } catch (e) { if (!e.message.includes('Duplicate record')) throw e; } } zx.verbose = true; await setupConfigStores(); await setupKVStore(); await setupSecretStore(); await setupAcl(); zx.verbose = false; await $`fastly service-version activate --service-id ${serviceId} --version latest --token $FASTLY_API_TOKEN`; ================================================ FILE: integration-tests/js-compute/teardown.js ================================================ #!/usr/bin/env node import { argv } from 'node:process'; import { getEnv } from './env.js'; import { $ } from './util.js'; const serviceId = argv[2]; const serviceName = argv[3]; const { ACL_NAME, DICTIONARY_NAME, CONFIG_STORE_NAME, KV_STORE_NAME, SECRET_STORE_NAME, } = getEnv(serviceName); function existingListId(stores, existingName) { const existing = stores.find(({ name }) => name === existingName); return existing?.id || existing?.StoreID; } const startTime = Date.now(); if (process.env.FASTLY_API_TOKEN === undefined) { try { process.env.FASTLY_API_TOKEN = String( await $`fastly profile token --quiet`, ).trim(); } catch { console.error( 'No environment variable named FASTLY_API_TOKEN has been set and no default fastly profile exists.', ); console.error( 'In order to run the tests, either create a fastly profile using `fastly profile create` or export a fastly token under the name FASTLY_API_TOKEN', ); process.exit(1); } } const FASTLY_API_TOKEN = process.env.FASTLY_API_TOKEN; async function removeConfigStores() { const stores = JSON.parse( await $`fastly config-store list --quiet --json --token $FASTLY_API_TOKEN`, ); const links = JSON.parse( await $`fastly service resource-link list --service-id=${serviceId} --quiet --json --version latest --token $FASTLY_API_TOKEN`, ); let STORE_ID = existingListId(stores, DICTIONARY_NAME); if (STORE_ID) { const LINK_ID = links.find( ({ resource_id }) => resource_id == STORE_ID, )?.id; if (LINK_ID) { await $`fastly service resource-link delete --version latest --autoclone --id=${LINK_ID} --token $FASTLY_API_TOKEN`; await $`fastly service-version activate --version latest --token $FASTLY_API_TOKEN`; } await $`fastly config-store delete --store-id=${STORE_ID} --token $FASTLY_API_TOKEN`; } STORE_ID = existingListId(stores, CONFIG_STORE_NAME); if (STORE_ID) { const LINK_ID = links.find( ({ resource_id }) => resource_id == STORE_ID, )?.id; if (LINK_ID) { await $`fastly service resource-link delete --version latest --autoclone --id=${LINK_ID} --token $FASTLY_API_TOKEN`; await $`fastly service-version activate --version latest --token $FASTLY_API_TOKEN`; } try { await $`fastly config-store delete --store-id=${STORE_ID} --token $FASTLY_API_TOKEN`; } catch {} } } async function removeKVStore() { const stores = JSON.parse( await $`fastly kv-store list --quiet --json --token $FASTLY_API_TOKEN`, ).Data; let STORE_ID = existingListId(stores, KV_STORE_NAME); if (STORE_ID) { await $`fastly kv-store delete --store-id=${STORE_ID} --quiet --all -y --token $FASTLY_API_TOKEN`; } else { console.error(`Unable to find KV Store ${KV_STORE_NAME} to delete`); } } async function removeSecretStore() { const stores = JSON.parse( await $`fastly secret-store list --quiet --json --token $FASTLY_API_TOKEN`, ); const links = JSON.parse( await $`fastly service resource-link list --service-id=${serviceId} --quiet --json --version latest --token $FASTLY_API_TOKEN`, ); const STORE_ID = existingListId(stores, SECRET_STORE_NAME); if (STORE_ID) { const LINK_ID = links.find( ({ resource_id }) => resource_id == STORE_ID, )?.id; if (LINK_ID) { await $`fastly service resource-link delete --version latest --autoclone --id=${LINK_ID} --token $FASTLY_API_TOKEN`; await $`fastly service-version activate --version latest --token $FASTLY_API_TOKEN`; } try { await $`fastly secret-store delete --store-id=${STORE_ID} --token $FASTLY_API_TOKEN`; } catch {} } } async function removeAcl() { const ACL_ID = existingListId( JSON.parse( await $`fastly compute acl list-acls --quiet --json --token $FASTLY_API_TOKEN`, ).data, ACL_NAME, ); const links = JSON.parse( await $`fastly service resource-link list --service-id=${serviceId} --quiet --json --version latest --token $FASTLY_API_TOKEN`, ); const LINK_ID = links.find(({ resource_id }) => resource_id == ACL_ID)?.id; if (LINK_ID) { await $`fastly service resource-link delete --version latest --autoclone --id=${LINK_ID} --token $FASTLY_API_TOKEN`; await $`fastly service-version activate --version latest --token $FASTLY_API_TOKEN`; } if (ACL_ID) { await $`fastly compute acl delete --acl-id=${ACL_ID} --token $FASTLY_API_TOKEN`; } } try { await removeConfigStores(); } catch (e) { console.error(e.message); } try { await removeKVStore(); } catch (e) { console.error(e.message); } try { await removeSecretStore(); } catch (e) { console.error(e.message); } try { await removeAcl(); } catch (e) { console.error(e.message); } console.log( `Tear down has finished! Took ${(Date.now() - startTime) / 1000} seconds to complete`, ); ================================================ FILE: integration-tests/js-compute/test.js ================================================ #!/usr/bin/env node import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; import { cd, $ as zx, retry, expBackoff } from 'zx'; import { request } from 'undici'; import { compareDownstreamResponse } from './compare-downstream-response.js'; import { argv } from 'node:process'; import { existsSync } from 'node:fs'; import { copyFile, readFile, writeFile } from 'node:fs/promises'; import * as core from '@actions/core'; import TOML from '@iarna/toml'; import { getEnv, GLOBAL_PREFIX } from './env.js'; import { $ } from './util.js'; // test environment variable handling process.env.LOCAL_TEST = 'local val'; async function killPortProcess(port) { zx.verbose = false; const pids = (await zx`lsof -ti:${port}`).stdout; if (pids) { for (const pid of pids.split('\n').reverse()) { if (pid && pid != process.pid) { await zx`kill -15 ${pid}`; } } } } const startTime = Date.now(); const __dirname = dirname(fileURLToPath(import.meta.url)); async function sleep(seconds) { return new Promise((resolve) => { setTimeout(resolve, 1_000 * seconds); }); } let args = argv.slice(2); const local = args.includes('--local'); const verbose = args.includes('--verbose'); const serial = args.includes('--serial'); const fixtureArg = args.find((arg) => arg.startsWith('--fixture=')); const httpCache = args.includes('--http-cache'); const aot = args.includes('--aot'); const debugBuild = args.includes('--debug-build'); const debugLog = args.includes('--debug-log'); const skipSetup = args.includes('--skip-setup'); const skipTeardown = args.includes('--skip-teardown'); const filter = args.filter((arg) => !arg.startsWith('--')); const bail = args.includes('--bail'); const ci = args.includes('--ci'); if (!local && process.env.FASTLY_API_TOKEN === undefined) { try { zx.verbose = false; process.env.FASTLY_API_TOKEN = String( await $`fastly auth show --reveal | grep 'Token:' | cut -d ' ' -f2-`, ).trim(); } catch { console.error( 'No environment variable named FASTLY_API_TOKEN has been set and no default fastly profile exists.', ); console.error( 'In order to run the tests, either create a fastly profile using `fastly profile create` or export a fastly token under the name FASTLY_API_TOKEN', ); process.exit(1); } } const FASTLY_API_TOKEN = process.env.FASTLY_API_TOKEN; zx.verbose = true; const branchName = (await zx`git branch --show-current`).stdout .trim() .replace(/[^a-zA-Z0-9_-]/g, '_'); var fixture = 'app'; if (fixtureArg !== undefined) { fixture = fixtureArg.split('=')[1]; } // Service names are carefully unique to support parallel runs const serviceName = `${GLOBAL_PREFIX}app-${branchName}${aot ? '--aot' : ''}${httpCache ? '--http' : ''}${process.env.SUFFIX_STRING ? '--' + process.env.SUFFIX_STRING : ''}`; let domain, serviceId; const fixturePath = join(__dirname, 'fixtures', fixture); let localServer; const env = getEnv(ci && !local ? serviceName : null); Object.assign(process.env, env); if (debugLog) { process.env.FASTLY_DEBUG_LOGGING = '1'; } await cd(fixturePath); await copyFile( join(fixturePath, 'fastly.toml.in'), join(fixturePath, 'fastly.toml'), ); const envSeen = new Set(); const config = TOML.parse( (await readFile(join(fixturePath, 'fastly.toml'), 'utf-8')).replace( /DICTIONARY_NAME|CONFIG_STORE_NAME|KV_STORE_NAME|SECRET_STORE_NAME|ACL_NAME/g, (match) => { // we only replace the second instance, because the first is the --env flag itself if (!envSeen.has(match)) { envSeen.add(match); return match; } return env[match] || match; }, ), ); config.name = serviceName; if (aot) { const buildArgs = config.scripts.build.split(' '); buildArgs.splice(-1, null, '--enable-aot'); config.scripts.build = buildArgs.join(' '); } if (debugBuild) { const buildArgs = config.scripts.build.split(' '); buildArgs.splice(-1, null, '--debug-build'); config.scripts.build = buildArgs.join(' '); } if (httpCache) { const buildArgs = config.scripts.build.split(' '); buildArgs.splice(-1, null, '--enable-http-cache'); config.scripts.build = buildArgs.join(' '); } await writeFile( join(fixturePath, 'fastly.toml'), TOML.stringify(config), 'utf-8', ); try { if (!local) { core.startGroup('Delete service if already exists'); try { await zx`fastly service delete --quiet --service-name "${serviceName}" --force --token $FASTLY_API_TOKEN`; } catch {} core.endGroup(); await new Promise((resolve) => setTimeout(resolve, 5000)); core.startGroup('Build and deploy service'); await zx`npm i`; await $`fastly compute publish -i ${verbose ? '--verbose' : '--quiet'} --token $FASTLY_API_TOKEN --status-check-off`; core.endGroup(); // It can take time for the new domain to show up on the list. await Promise.all([ (async () => { await retry(27, expBackoff('60s', '10s'), async () => { // get the public domain of the deployed application const domainListing = JSON.parse( await $`fastly service domain list --quiet --version latest --json`, )[0]; domain = `https://${domainListing.Name}`; serviceId = domainListing.ServiceID; core.notice(`Service is running on ${domain}`); }); })(), new Promise((resolve) => setTimeout(resolve, 60_000)), ]); } else { const pushpin = '--local-pushpin-proxy-port=0'; const args = verbose ? '-vv ' + pushpin : pushpin; localServer = zx`fastly compute serve --verbose --viceroy-args="${args}"`; domain = 'http://127.0.0.1:7676'; } core.startGroup(`Setting up service ${domain}`); if (!local && !skipSetup) { const setupPath = join(__dirname, 'setup.js'); if (existsSync(setupPath)) { await zx`node ${setupPath} ${serviceId} ${ci ? serviceName : ''}`; } } await Promise.all([ (async () => { await retry( 27, local ? [ // we expect it to take ~10 seconds to deploy, so focus on that time 6000, 3000, 1500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, // after more than 20 seconds, means we have an unusually slow build, start backoff before timeout 1500, 3000, 6000, 12000, 24000, ].values() : expBackoff('60s', '10s'), async () => { const response = await request(domain); if (response.statusCode !== 200) { throw new Error( `Application "${fixture}" :: Not yet available on domain: ${domain}`, ); } }, ); })(), // we need to wait for the service resource links to all activate, // and we don't currently have a reliable way to poll on that // (perhaps we could poll on the highest version as seen from setup.js resource-link return output // being fully activated?) local ? null : new Promise((resolve) => setTimeout(resolve, 60_000)), ]); core.endGroup(); core.startGroup('Running tests'); const { default: tests } = await import(join(fixturePath, 'tests.json'), { with: { type: 'json' }, }); function chunks(arr, size) { const output = []; for (let i = 0; i < arr.length; i += size) { output.push(arr.slice(i, i + size)); } return output; } let results = []; let chunkSize = serial ? 1 : 100; for (const chunk of chunks(Object.entries(tests), chunkSize)) { results.push( ...(await ( bail ? Promise.all.bind(Promise) : Promise.allSettled.bind(Promise) )( chunk.map(async ([title, test]) => { // test defaults if (!test.downstream_request) { const [method, pathname, extra] = title.split(' '); if (typeof extra === 'string') throw new Error('Cannot infer downstream_request from title'); test.downstream_request = { method, pathname }; } if (!test.downstream_response) { test.downstream_response = { status: 200, }; } if (!test.environments) { test.environments = ['viceroy', 'compute']; } // basic test filtering if ( test.skip || (filter.length > 0 && filter.every((f) => !title.includes(f))) ) { return { title, test, skipped: true, skipReason: test.skip ? 'MARKED AS SKIPPED (pending further work)' : null, // dont mention filtered tests }; } // feature based test filtering if ( (!httpCache && test.features && test.features.includes('http-cache')) || (httpCache && test.features && test.features.includes('skip-http-cache')) ) { return { title, test, skipped: true, skipReason: `feature "http-cache" ${httpCache ? '' : 'not '}"enabled`, }; } async function getBodyChunks(response) { const bodyChunks = []; let downstreamTimeout; await Promise.race([ (async () => { // This body_streaming property allows us to test different cases // of consumer streamining behaviours. switch (test.body_streaming) { case 'first-chunk-only': for await (const chunk of response.body) { bodyChunks.push(chunk); response.body.on('error', () => {}); break; } break; case 'none': response.body.on('error', () => {}); break; case 'full': default: for await (const chunk of response.body) { bodyChunks.push(chunk); } } })(), new Promise((_, reject) => { downstreamTimeout = setTimeout(() => { reject( new Error(`Test downstream response body chunk timeout`), ); }, 30_000); }), ]); clearTimeout(downstreamTimeout); return bodyChunks; } let onInfoHandler = test.downstream_info ? async (status, headers) => { if ( test.downstream_info.status !== undefined && test.downstream_info.status != status ) { throw new Error( `[DownstreamInfo: Status mismatch] Expected: ${configResponse.status} - Got: ${status}}`, ); } if (headers) { compareHeaders( configResponse.headers, headers, configResponse.headersExhaustive, ); } } : undefined; if (local) { if (test.environments.includes('viceroy')) { return (bail || !test.flake ? (_, __, fn) => fn() : retry)( 5, expBackoff('10s', '1s'), async () => { let path = test.downstream_request.pathname; let url = `${domain}${path}`; try { const response = await request(url, { method: test.downstream_request.method || 'GET', headers: test.downstream_request.headers || undefined, body: test.downstream_request.body || undefined, }); const bodyChunks = await getBodyChunks(response); await compareDownstreamResponse( test.downstream_response, response, bodyChunks, ); return { title, test, skipped: false, }; } catch (error) { console.error('\n' + test.downstream_request.pathname); throw new Error(`${title} ${error.message}`, { cause: error, }); } }, ); } else { return { title, test, skipped: true, skipReason: 'no environments', }; } } else { if (test.environments.includes('compute')) { return retry( test.flake ? 15 : bail ? 1 : 4, expBackoff( test.flake ? '60s' : '30s', test.flake ? '30s' : '1s', ), async () => { let path = test.downstream_request.pathname; let url = `${domain}${path}`; try { const response = await request(url, { method: test.downstream_request.method || 'GET', headers: test.downstream_request.headers || undefined, body: test.downstream_request.body || undefined, onInfo: onInfoHandler, }); const bodyChunks = await getBodyChunks(response); await compareDownstreamResponse( test.downstream_response, response, bodyChunks, ); return { title, test, skipped: false, }; } catch (error) { console.error('\n' + test.downstream_request.pathname); throw new Error(`${title} ${error.message}`); } }, ); } else { return { title, test, skipped: true, skipReason: 'no environments', }; } } }), )), ); } core.endGroup(); console.log('Test results'); core.startGroup('Test results'); let passed = 0; const failed = []; const green = '\u001b[32m'; const red = '\u001b[31m'; const reset = '\u001b[0m'; const white = '\u001b[39m'; const info = '\u2139'; const tick = '\u2714'; const cross = '\u2716'; for (const result of results) { if (result.status === 'fulfilled' || bail) { const value = bail ? result : result.value; if (value.skipped) { if (value.skipReason) console.log( white, info, `Skipped ${value.title} due to ${value.skipReason}`, reset, ); } else { passed += 1; console.log(green, tick, value.title, reset); } } else { console.log(red, cross, result.reason, reset); failed.push(result.reason); } } core.endGroup(); if (failed.length) { process.exitCode = 1; core.startGroup('Failed tests'); for (const result of failed) { console.log(red, cross, result, reset); } core.endGroup(); } if (!local && failed.length) { core.notice(`Tests failed.`); } } finally { if (!local && !skipTeardown) { const teardownPath = join(__dirname, 'teardown.js'); if (existsSync(teardownPath)) { core.startGroup('Tear down the extra set-up for the service'); await zx`${teardownPath} ${serviceId} ${ci ? serviceName : ''}`; core.endGroup(); } core.startGroup('Delete service'); // Delete the service now the tests have finished try { await $`fastly service delete --quiet --service-name "${serviceName}" --force --token $FASTLY_API_TOKEN`; } catch (e) { console.log('Failed to delete service:', e.message); } core.endGroup(); } if (process.exitCode == undefined || process.exitCode == 0) { console.log( `All tests passed! Took ${(Date.now() - startTime) / 1000} seconds to complete`, ); } else { console.log(`Tests failed!`); } if (localServer) { await killPortProcess(7676); } process.exit(); } ================================================ FILE: integration-tests/js-compute/util.js ================================================ import { cd, $ as zx, retry, expBackoff } from 'zx'; export async function $(...args) { await new Promise((resolve) => setTimeout(resolve, 3000)); return await retry(10, expBackoff('60s', '10s'), async () => zx(...args)); } ================================================ FILE: package.json ================================================ { "name": "@fastly/js-compute", "version": "3.41.2", "license": "Apache-2.0", "main": "types/index.js", "types": "types/index.d.ts", "type": "module", "exports": { ".": { "fastly": { "types": "./types/index.d.ts", "default": "./types/index.js" }, "default": { "types": "./types/index.d.ts", "default": "./dist/index.js" } } }, "repository": { "type": "git", "url": "https://github.com/fastly/js-compute-runtime" }, "bin": { "js-compute": "dist/cli/js-compute-runtime-cli.js", "js-compute-runtime": "dist/cli/js-compute-runtime-cli.js" }, "files": [ "types", "fastly.wasm", "fastly.debug.wasm", "fastly-weval.wasm", "fastly-ics.wevalcache", "dist", "rsrc", "package.json", "README.md", "CHANGELOG.md" ], "scripts": { "test": "npm run test:types && npm run test:cli", "test:cli": "brittle --bail integration-tests/cli/**.test.js", "test:integration": "node ./integration-tests/js-compute/test.js", "test:wpt": "tests/wpt-harness/build-wpt-runtime.sh && node ./tests/wpt-harness/run-wpt.mjs -vv", "test:wpt:debug": "tests/wpt-harness/build-wpt-runtime.sh --debug-build && node ./tests/wpt-harness/run-wpt.mjs -vv", "test:types": "tsd", "clean": "rm -rf dist/ starling.wasm fastly.wasm fastly.debug.wasm fastly-weval.wasm fastly-ics.wevalcache fastly-js-compute-*.tgz", "build": "npm run clean && npm run build:cli && npm run build:debug && npm run build:release && npm run build:weval", "build:cli": "tsc", "build:release": "./runtime/fastly/build-release.sh", "build:debug": "./runtime/fastly/build-debug.sh", "build:weval": "./runtime/fastly/build-release-weval.sh", "build:debug:info": "./runtime/fastly/build-debug.sh --keep-debug-info", "format-changelog": "node ci/format-changelog.js CHANGELOG.md", "format": "prettier --write 'src/**/*.ts' integration-tests types test-d", "format:check": "prettier --check 'src/**/*.ts' integration-tests" }, "dependencies": { "@bytecodealliance/jco": "^1.7.0", "@bytecodealliance/weval": "^0.3.2", "@bytecodealliance/wizer": "^7.0.5", "@jridgewell/remapping": "^2.3.5", "@jridgewell/trace-mapping": "^0.3.31", "acorn": "^8.13.0", "acorn-walk": "^8.3.4", "cosmiconfig": "^9.0.1", "esbuild": "^0.25.0", "magic-string": "^0.30.12", "picomatch": "^4.0.4", "regexpu-core": "^6.4.0" }, "devDependencies": { "@eslint/js": "^9.39.1", "@jakechampion/cli-testing-library": "^1.0.0", "@types/node": "^24.10.1", "@types/picomatch": "^4.0.2", "brittle": "^3.5.2", "eslint": "^9.39.1", "get-bin-path": "^11.0.0", "prettier": "^3.3.3", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "tsd": "^0.33.0", "typescript": "^5.9.3", "typescript-eslint": "^8.48.1", "unified": "^11.0.5" }, "peerDependencies": { "typescript": ">=5.9" }, "peerDependenciesMeta": { "typescript": { "optional": true } }, "tsd": { "compilerOptions": { "types": [] } } } ================================================ FILE: patches/typedoc-plugin-versions+0.2.2.patch ================================================ diff --git a/node_modules/typedoc-plugin-versions/src/etc/utils.js b/node_modules/typedoc-plugin-versions/src/etc/utils.js index db6b2cb..e92c4e8 100644 --- a/node_modules/typedoc-plugin-versions/src/etc/utils.js +++ b/node_modules/typedoc-plugin-versions/src/etc/utils.js @@ -235,9 +235,7 @@ function makeJsKeys(metadata) { const alias = metadata.stable ? 'stable' : 'dev'; const keys = [ alias, - ...metadata.versions // add the major.minor versions - .map((v) => getMinorVersion(v)) - .filter((v, i, s) => s.indexOf(v) === i), + ...metadata.versions, ]; if (alias !== 'dev' && metadata.dev) { keys.push('dev'); ================================================ FILE: rsrc/trace-mapping.inject.js ================================================ import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping"; let _traceMap; function getTraceMap() { if (!_traceMap) { _traceMap = new TraceMap(globalThis.__FASTLY_SOURCE_MAP); } return _traceMap; } function buildErrorHeading(e) { const name = e?.name || 'Error'; // Prefer e.cause.message if message is missing and cause is informative const msg = (typeof e?.message === 'string' && e.message) || (e?.cause && typeof e.cause?.message === 'string' && e.cause.message) || ''; return msg ? `${name}: ${msg}` : name; } function getSourceContext(source, line, col, { radius = 3 } = {}) { const tm = getTraceMap(); if (!tm) return null; const idx = tm.sources.indexOf(source); if (idx < 0) return null; const content = tm.sourcesContent?.[idx]; if (!content) return null; // gracefully skip const lines = content.split('\n'); const start = Math.max(0, line - 1 - radius); const end = Math.min(lines.length - 1, line - 1 + radius); const result = []; for (let i = start; i <= end; i++) { const prefix = i === (line - 1) ? '>' : ' '; const num = String(i + 1).padStart(5); result.push(`${prefix} ${num} | ${lines[i]}`); if (i === line - 1) { result.push(` ${''.padStart(col)}^`); } } return result; } function parseStarlingMonkeyFrame(line) { line = String(line).trim().replace(/\)?$/, ""); // strip trailing ')' const m = line.match(/:(\d+):(\d+)\s*$/); if (!m) return null; const col = +m[2]; const lineNo = +m[1]; const head = line.slice(0, m.index); if (head.startsWith('@')) { // no function name return { fn: null, file: head.slice(1), line: lineNo, col, }; } const at = head.lastIndexOf("@"); if (at > 0) { // fn@file return { fn: head.slice(0, at), file: head.slice(at + 1), line: lineNo, col, }; } // file only return { fn: null, file: head, line: lineNo, col, }; } function mapStack(raw) { const tm = getTraceMap(); const out = []; const lines = String(raw).split(/\r?\n/); for (const line of lines) { if (line.startsWith('node_modules/@fastly/js-compute/rsrc/trace-mapping.inject.js')) { // If the line comes from this file, skip it continue; } if (line === '') { out.push({l: line}); continue; } const m = parseStarlingMonkeyFrame(line); if (!m) { out.push({e:'(frame not parsed)', l:line}); continue; } const { fn, file, line: l, col: c } = m; const genLine = Number(l); const genCol = Number(c); // Only map frames that come from the generated bundle if (file !== globalThis.__FASTLY_GEN_FILE) { out.push({e:'(frame not mapped)', l:line}); continue; } const pos = originalPositionFor(tm, { line: genLine, column: Math.max(0, genCol - 1) }); if (!pos?.source) { continue; } out.push({m:{pos,fn}, l: line}); } return out; } function mapError(e) { const lines = []; const raw = e?.stack ?? String(e); lines.push(buildErrorHeading(e)); try { const stack = mapStack(raw); let contextOutputted = false; for (const line of stack) { const { e, m, l } = line; if (l === '') { lines.push(''); continue; } if (e != null) { lines.push(`${e} ${l}`); continue; } let formatted; let ctx; if (m == null) { formatted = l; } else { const {pos, fn} = m; let name = pos.name; if (fn == null || fn === '') { name = null; } else if (fn[fn.length-1] === '<') { name = '(anonymous function)'; } else { name = fn; } const filePos = `${pos.source}:${pos.line}:${pos.column != null ? pos.column + 1 : 0}`; formatted = name ? `${name} (${filePos})` : filePos; if (!contextOutputted) { ctx = getSourceContext(pos.source, pos.line, pos.column); contextOutputted = true; } } lines.push(` at ${formatted}`); if (ctx) { lines.push(...ctx); } } } catch { lines.push('(Raw error)'); lines.push(raw); } return lines; } // Monkey patch addEventListener('fetch') const _orig_addEventListener = globalThis.addEventListener; globalThis.addEventListener = function (type, listener) { if (type !== 'fetch') { return _orig_addEventListener.call(this, type, listener); } const _orig_listener = listener; return _orig_addEventListener.call(this, type, (event) => { // Patch respondWith on this event instance const _orig_respondWith = event.respondWith.bind(event); event.respondWith = (value) => { const wrappedValue = Promise .resolve(value) .catch((err) => { console.error('Unhandled error while running request handler'); try { globalThis.__fastlyMapAndLogError(err); } catch { /* swallow */ } console.error('Raw error below:'); throw err; }); try { return _orig_respondWith(wrappedValue); } catch (err) { console.error('Unhandled error sending response'); try { globalThis.__fastlyMapAndLogError(err); } catch { /* swallow */ } console.error('Raw error below:'); throw err; } }; try { return _orig_listener.call(this, event); } catch (err) { console.error('Unhandled error running event listener'); try { globalThis.__fastlyMapAndLogError(err); } catch { /* swallow */ } console.error('Raw error below:'); throw err; } }); }; globalThis.__fastlyMapError = mapError ================================================ FILE: runtime/fastly/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.27) #FIXME(1243) file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/../rust-toolchain.toml" DESTINATION "${CMAKE_CURRENT_SOURCE_DIR}/../StarlingMonkey") # Apply any local patches to StarlingMonkey before it is included as a subproject file(GLOB SM_PATCHES "${CMAKE_CURRENT_SOURCE_DIR}/patches/starlingmonkey-*.patch") foreach(patch IN LISTS SM_PATCHES) execute_process( COMMAND git apply --check "${patch}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../StarlingMonkey" RESULT_VARIABLE patch_check_result OUTPUT_QUIET ERROR_QUIET ) if(patch_check_result EQUAL 0) execute_process( COMMAND git apply "${patch}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../StarlingMonkey" RESULT_VARIABLE patch_result ) if(NOT patch_result EQUAL 0) message(FATAL_ERROR "Failed to apply StarlingMonkey patch: ${patch}") endif() endif() endforeach() include("../StarlingMonkey/cmake/add_as_subproject.cmake") add_builtin( fastly::runtime SRC handler.cpp common/ip_octets_to_js_string.cpp common/normalize_http_method.cpp common/validations.cpp) add_builtin(fastly::cache_simple SRC builtins/cache-simple.cpp DEPENDENCIES OpenSSL) add_builtin(fastly::fastly SRC builtins/fastly.cpp) add_builtin(fastly::acl SRC builtins/acl.cpp) add_builtin(fastly::backend SRC builtins/backend.cpp) add_builtin(fastly::body SRC builtins/body.cpp) add_builtin(fastly::cache_core SRC builtins/cache-core.cpp) add_builtin(fastly::kv_store SRC builtins/kv-store.cpp) add_builtin(fastly::logger SRC builtins/logger.cpp) add_builtin(fastly::device SRC builtins/device.cpp) add_builtin(fastly::dictionary SRC builtins/dictionary.cpp) add_builtin(fastly::edge_rate_limiter SRC builtins/edge-rate-limiter.cpp) add_builtin(fastly::config_store SRC builtins/config-store.cpp) add_builtin(fastly::secret_store SRC builtins/secret-store.cpp) add_builtin(fastly::image_optimizer SRC builtins/image-optimizer.cpp) add_builtin(fastly::shielding SRC builtins/shielding.cpp) add_builtin(fastly::fetch SRC builtins/fetch/fetch.cpp builtins/fetch/request-response.cpp builtins/fetch/request-response.cpp ../StarlingMonkey/builtins/web/fetch/headers.cpp ../StarlingMonkey/builtins/web/fetch/fetch-utils.cpp DEPENDENCIES fmt) add_builtin(fastly::cache_override SRC builtins/cache-override.cpp) add_builtin(fastly::fetch_event SRC builtins/fetch-event.cpp DEPENDENCIES OpenSSL) add_rust_lib(lol_html_c_api "${CMAKE_CURRENT_SOURCE_DIR}/crates/rust-lol-html" "\"capi\"") add_builtin(fastly::html_rewriter SRC builtins/html-rewriter.cpp INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/crates/rust-lol-html/include ) add_compile_definitions(PUBLIC RUNTIME_VERSION=${RUNTIME_VERSION}) if(DEFINED FASTLY_GC_FREQUENCY) add_compile_definitions(PUBLIC FASTLY_GC_FREQUENCY=${FASTLY_GC_FREQUENCY}) endif() project(FastlyJS) ================================================ FILE: runtime/fastly/build-debug.sh ================================================ #!/usr/bin/env bash set -euo pipefail set -x cd "$(dirname "$0")" || exit 1 # Parse command line arguments KEEP_DEBUG_INFO=0 GC_FREQUENCY="" while [[ $# -gt 0 ]]; do case $1 in --keep-debug-info) KEEP_DEBUG_INFO=1 shift ;; --gc-frequency) if [[ -n "${2:-}" ]]; then GC_FREQUENCY="-DFASTLY_GC_FREQUENCY=$2" shift 2 else echo "Error: --gc-frequency requires a value" exit 1 fi ;; *) echo "Unknown option: $1" exit 1 ;; esac done RUNTIME_VERSION=$(npm pkg get version --json --prefix=../../ | jq -r) HOST_API=$(realpath host-api) cmake -B build-debug -DCMAKE_BUILD_TYPE=Debug -DENABLE_BUILTIN_WEB_FETCH=0 -DENABLE_BUILTIN_WEB_FETCH_FETCH_EVENT=0 -DCMAKE_EXPORT_COMPILE_COMMANDS=1 -DRUNTIME_VERSION="\"$RUNTIME_VERSION-debug\"" -DENABLE_JS_DEBUGGER=OFF "$GC_FREQUENCY" cmake --build build-debug --parallel 10 if [ "$KEEP_DEBUG_INFO" -eq 0 ]; then wasm-tools strip build-debug/starling-raw.wasm/starling-raw.wasm -d ".debug_(info|loc|ranges|abbrev|line|str)" -o ../../fastly.debug.wasm else cp build-debug/starling-raw.wasm/starling-raw.wasm ../../fastly.debug.wasm fi ================================================ FILE: runtime/fastly/build-release-weval.sh ================================================ #!/usr/bin/env bash cd "$(dirname "$0")" || exit 1 RUNTIME_VERSION=$(npm pkg get version --json --prefix=../../ | jq -r) HOST_API=$(realpath host-api) cmake -B build-release-weval -DCMAKE_BUILD_TYPE=Release -DENABLE_BUILTIN_WEB_FETCH=0 -DENABLE_BUILTIN_WEB_FETCH_FETCH_EVENT=0 -DRUNTIME_VERSION="\"$RUNTIME_VERSION\"" -DWEVAL=ON -DENABLE_JS_DEBUGGER=OFF cmake --build build-release-weval --parallel 8 mv build-release-weval/starling-raw.wasm/starling-raw.wasm ../../fastly-weval.wasm mv build-release-weval/starling-raw.wasm/starling-ics.wevalcache ../../fastly-ics.wevalcache ================================================ FILE: runtime/fastly/build-release.sh ================================================ #!/usr/bin/env bash cd "$(dirname "$0")" || exit 1 RUNTIME_VERSION=$(npm pkg get version --json --prefix=../../ | jq -r) HOST_API=$(realpath host-api) cmake -B build-release -DCMAKE_BUILD_TYPE=Release -DENABLE_BUILTIN_WEB_FETCH=0 -DENABLE_BUILTIN_WEB_FETCH_FETCH_EVENT=0 -DRUNTIME_VERSION="\"$RUNTIME_VERSION\"" -DENABLE_JS_DEBUGGER=OFF cmake --build build-release mv build-release/starling-raw.wasm/starling-raw.wasm ../../fastly.wasm ================================================ FILE: runtime/fastly/builtins/acl.cpp ================================================ #include "acl.h" #include "../common/validations.h" #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "encode.h" #include "fastly.h" #include "js/JSON.h" #include using builtins::BuiltinNoConstructor; using fastly::FastlyGetErrorMessage; namespace fastly::acl { namespace { host_api::HostString parse_and_validate_name(JSContext *cx, JS::HandleValue name_val) { if (!name_val.isString()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_ACL_NAME_NOT_STRING); return nullptr; } JS::RootedString name(cx, name_val.toString()); if (!name) { return nullptr; } auto length = JS::GetStringLength(name); if (length > 254) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_ACL_NAME_TOO_LONG); return nullptr; } if (length == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_ACL_NAME_EMPTY); return nullptr; } return core::encode(cx, name); } } // namespace bool Acl::open(JSContext *cx, unsigned argc, JS::Value *vp) { CallArgs args = CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "Acl open", 1)) return false; auto name = parse_and_validate_name(cx, args.get(0)); if (!name) { return false; } auto open_res = host_api::Acl::open(name); if (auto *err = open_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto found = open_res.unwrap(); if (!found.has_value()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_ACL_NOT_FOUND, name.begin()); return false; } RootedObject acl_instance(cx, JS_NewObjectWithGivenProto(cx, &Acl::class_, Acl::proto_obj)); if (!acl_instance) { return false; } JS::SetReservedSlot(acl_instance, static_cast(Slots::HostAcl), JS::Int32Value(found.value().handle)); args.rval().setObject(*acl_instance); return true; } bool Acl::lookup(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::RootedString address_str(cx, JS::ToString(cx, args[0])); if (!address_str) return false; auto address = core::encode(cx, address_str); if (!address) { return false; } int format = AF_INET; size_t octets_len = 4; if (std::find(address.begin(), address.end(), ':') != address.end()) { format = AF_INET6; octets_len = 16; } uint8_t octets[sizeof(struct in6_addr)]; if (inet_pton(format, address.begin(), octets) != 1) { JS_ReportErrorLatin1(cx, "Invalid address passed to acl.lookup"); return false; } host_api::Acl acl{static_cast( JS::GetReservedSlot(self, static_cast(Slots::HostAcl)).toInt32())}; auto lookup_res = acl.lookup(std::span{octets, octets_len}); if (auto *err = lookup_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto [body, error] = lookup_res.unwrap(); switch (error) { case host_api::Acl::LookupError::Ok: break; case host_api::Acl::LookupError::NoContent: args.rval().setNull(); return true; case host_api::Acl::LookupError::TooManyRequests: JS_ReportErrorLatin1(cx, "Acl.lookup: Too many requests, please try again later"); return false; case host_api::Acl::LookupError::Uninitialized: JS_ReportErrorLatin1(cx, "Acl.lookup: Uninitialized acl passed to lookup"); return false; } auto buf_res = body.value().read_all(); if (auto *err = buf_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::RootedString str( cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(reinterpret_cast(buf_res.unwrap().ptr.get()), buf_res.unwrap().len))); if (!str) { return false; } JS::RootedValue json(cx); if (!JS_ParseJSON(cx, str, &json)) { return false; } args.rval().set(json); return true; } const JSFunctionSpec Acl::static_methods[] = { JS_FN("open", Acl::open, 1, JSPROP_ENUMERATE), }; const JSPropertySpec Acl::static_properties[] = {JS_PS_END}; const JSFunctionSpec Acl::methods[] = {JS_FN("lookup", Acl::lookup, 1, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec Acl::properties[] = {JS_PS_END}; bool install(api::Engine *engine) { if (!Acl::init_class_impl(engine->cx(), engine->global())) { return false; } RootedObject acl_obj(engine->cx(), JS_GetConstructor(engine->cx(), BuiltinNoConstructor::proto_obj)); RootedValue acl_val(engine->cx(), ObjectValue(*acl_obj)); RootedObject acl_ns(engine->cx(), JS_NewObject(engine->cx(), nullptr)); if (!JS_SetProperty(engine->cx(), acl_ns, "Acl", acl_val)) { return false; } RootedValue acl_ns_val(engine->cx(), JS::ObjectValue(*acl_ns)); if (!engine->define_builtin_module("fastly:acl", acl_ns_val)) { return false; } return true; } } // namespace fastly::acl ================================================ FILE: runtime/fastly/builtins/acl.h ================================================ #ifndef FASTLY_ACL_H #define FASTLY_ACL_H #include "builtin.h" #include "extension-api.h" namespace fastly::acl { class Acl : public builtins::BuiltinNoConstructor { private: public: static constexpr const char *class_name = "Acl"; static const int ctor_length = 1; enum Slots { HostAcl, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool open(JSContext *cx, unsigned argc, JS::Value *vp); static bool lookup(JSContext *cx, unsigned argc, JS::Value *vp); }; } // namespace fastly::acl #endif ================================================ FILE: runtime/fastly/builtins/backend.cpp ================================================ #include #include #include #include #include #include #include #include #include #include #include #include // TODO: remove these once the warnings are fixed #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" #include "js/experimental/TypedData.h" #pragma clang diagnostic pop #include "../common/validations.h" #include "../host-api/host_api_fastly.h" #include "./fetch/request-response.h" #include "./secret-store.h" #include "backend.h" #include "builtin.h" #include "decode.h" #include "encode.h" #include "fastly.h" using builtins::BuiltinImpl; using fastly::FastlyGetErrorMessage; using fastly::common::parse_and_validate_timeout; using fastly::fastly::Fastly; using fastly::fetch::RequestOrResponse; using fastly::secret_store::SecretStoreEntry; namespace fastly::backend { namespace { enum class Authentication : uint8_t { RSA, }; enum class KeyExchange : uint8_t { EECDH, RSA, }; enum class Encryption : uint8_t { AES128, AES128GCM, AES256, AES256GCM, CHACHA20POLY1305, TRIPLE_DES, }; enum class EncryptionLevel : uint8_t { MEDIUM, HIGH, }; enum class MessageDigest : uint8_t { SHA1, SHA256, SHA384, AEAD, }; enum class Protocol : uint8_t { SSLv3, TLSv1, TLSv1_2, }; class Cipher { public: std::string_view open_ssl_alias; KeyExchange kx; Authentication au; Encryption enc; MessageDigest mac; Protocol protocol; EncryptionLevel level; uint16_t strength_bits; constexpr Cipher(std::string_view open_ssl_alias, KeyExchange kx, Authentication au, Encryption enc, MessageDigest mac, Protocol protocol, EncryptionLevel level, int strength_bits) : open_ssl_alias(open_ssl_alias), kx(kx), au(au), enc(enc), mac(mac), protocol(protocol), level(level), strength_bits(strength_bits) {} // Overload the == operator const bool operator==(const Cipher &obj) const { return open_ssl_alias == obj.open_ssl_alias && kx == obj.kx && au == obj.au && enc == obj.enc && mac == obj.mac && protocol == obj.protocol && level == obj.level && strength_bits == obj.strength_bits; } }; /** * Class in charge with parsing openSSL expressions to define a list of ciphers. */ class OpenSSLCipherConfigurationParser { private: using AliasMap = std::unordered_map>; AliasMap aliases; // This array should stay aligned with the canonical list located at: // https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration // The mapping is from OpenSSL cipher names as strings to a the cipher represented as a Cipher // object static constexpr std::array, 11> CIPHER{ std::pair{ "DES-CBC3-SHA", Cipher(std::string_view("DES-CBC3-SHA"), KeyExchange::RSA, Authentication::RSA, Encryption::TRIPLE_DES, MessageDigest::SHA1, Protocol::SSLv3, EncryptionLevel::MEDIUM, 112)}, {"AES128-SHA", Cipher(std::string_view("AES128-SHA"), KeyExchange::RSA, Authentication::RSA, Encryption::AES128, MessageDigest::SHA1, Protocol::SSLv3, EncryptionLevel::HIGH, 128)}, {"AES256-SHA", Cipher(std::string_view("AES256-SHA"), KeyExchange::RSA, Authentication::RSA, Encryption::AES256, MessageDigest::SHA1, Protocol::SSLv3, EncryptionLevel::HIGH, 256)}, {"AES128-GCM-SHA256", Cipher(std::string_view("AES128-GCM-SHA256"), KeyExchange::RSA, Authentication::RSA, Encryption::AES128GCM, MessageDigest::AEAD, Protocol::TLSv1_2, EncryptionLevel::HIGH, 128)}, {"ECDHE-RSA-AES128-SHA", Cipher(std::string_view("ECDHE-RSA-AES128-SHA"), KeyExchange::EECDH, Authentication::RSA, Encryption::AES128, MessageDigest::SHA1, Protocol::TLSv1, EncryptionLevel::HIGH, 128)}, {"ECDHE-RSA-AES256-SHA", Cipher(std::string_view("ECDHE-RSA-AES256-SHA"), KeyExchange::EECDH, Authentication::RSA, Encryption::AES256, MessageDigest::SHA1, Protocol::TLSv1, EncryptionLevel::HIGH, 256)}, {"ECDHE-RSA-AES128-SHA256", Cipher(std::string_view("ECDHE-RSA-AES128-SHA256"), KeyExchange::EECDH, Authentication::RSA, Encryption::AES128, MessageDigest::SHA256, Protocol::TLSv1_2, EncryptionLevel::HIGH, 128)}, {"ECDHE-RSA-AES256-SHA384", Cipher(std::string_view("ECDHE-RSA-AES256-SHA384"), KeyExchange::EECDH, Authentication::RSA, Encryption::AES256, MessageDigest::SHA384, Protocol::TLSv1_2, EncryptionLevel::HIGH, 256)}, {"ECDHE-RSA-AES128-GCM-SHA256", Cipher(std::string_view("ECDHE-RSA-AES128-GCM-SHA256"), KeyExchange::EECDH, Authentication::RSA, Encryption::AES128GCM, MessageDigest::AEAD, Protocol::TLSv1_2, EncryptionLevel::HIGH, 128)}, {"ECDHE-RSA-AES256-GCM-SHA384", Cipher(std::string_view("ECDHE-RSA-AES256-GCM-SHA384"), KeyExchange::EECDH, Authentication::RSA, Encryption::AES256GCM, MessageDigest::AEAD, Protocol::TLSv1_2, EncryptionLevel::HIGH, 256)}, {"ECDHE-RSA-CHACHA20-POLY1305", Cipher(std::string_view("ECDHE-RSA-CHACHA20-POLY1305"), KeyExchange::EECDH, Authentication::RSA, Encryption::CHACHA20POLY1305, MessageDigest::AEAD, Protocol::TLSv1_2, EncryptionLevel::HIGH, 256)}, }; static constexpr auto SSL_PROTO_TLSv1_2 = "TLSv1.2"; static constexpr auto SSL_PROTO_TLSv1_0 = "TLSv1.0"; static constexpr auto SSL_PROTO_SSLv3 = "SSLv3"; static constexpr auto SSL_PROTO_TLSv1 = "TLSv1"; // static constexpr auto SEPARATOR = ":, "; /** * If ! is used then the ciphers are permanently deleted from the list. The ciphers deleted can * never reappear in the list even if they are explicitly stated. */ static constexpr char EXCLUDE = '!'; /** * If - is used then the ciphers are deleted from the list, but some or all of the ciphers can be * added again by later options. */ static constexpr char DELETE = '-'; /** * If + is used then the ciphers are moved to the end of the list. This option doesn't add any new * ciphers it just moves matching existing ones. */ static constexpr char TO_END = '+'; /** * Lists of cipher suites can be combined in a single cipher string using the + character. * This is used as a logical and operation. * For example SHA1+DES represents all cipher suites containing the SHA1 and the DES algorithms. */ static constexpr char AND = '+'; /** * 'high' encryption cipher suites. This currently means those with key lengths larger than 128 * bits, and some cipher suites with 128-bit keys. */ static constexpr auto HIGH = "HIGH"; /** * 'medium' encryption cipher suites, currently some of those using 128 bit encryption:: */ static constexpr auto MEDIUM = "MEDIUM"; /** * Cipher suites using RSA key exchange. */ static constexpr auto kRSA = "kRSA"; /** * Cipher suites using RSA authentication. */ static constexpr auto aRSA = "aRSA"; /** * Cipher suites using RSA for key exchange * Despite what the docs say, RSA is equivalent to kRSA. */ static constexpr auto RSA = "RSA"; /** * Cipher suites using ephemeral ECDH key agreement, including anonymous cipher suites. */ static constexpr auto kEECDH = "kEECDH"; /** * Cipher suites using ephemeral ECDH key agreement, excluding anonymous cipher suites. * Same as "kEECDH:-AECDH" */ static constexpr auto EECDH = "EECDH"; /** * Cipher suitesusing ECDH key exchange, including anonymous, ephemeral and fixed ECDH. */ static constexpr auto ECDH = "ECDH"; /** * Cipher suites using ephemeral ECDH key agreement, including anonymous cipher suites. */ static constexpr auto kECDHE = "kECDHE"; /** * Cipher suites using authenticated ephemeral ECDH key agreement */ static constexpr auto ECDHE = "ECDHE"; /** * Cipher suites using 128 bit AES. */ static constexpr auto AES128 = "AES128"; /** * Cipher suites using 256 bit AES. */ static constexpr auto AES256 = "AES256"; /** * Cipher suites using either 128 or 256 bit AES. */ static constexpr auto AES = "AES"; /** * AES in Galois Counter Mode (GCM): these cipher suites are only supported in TLS v1.2. */ static constexpr auto AESGCM = "AESGCM"; /** * Cipher suites using CHACHA20. */ static constexpr auto CHACHA20 = "CHACHA20"; /** * Cipher suites using triple DES. */ static constexpr auto TRIPLE_DES = "3DES"; /** * Cipher suites using SHA1. */ static constexpr auto SHA1 = "SHA1"; /** * Cipher suites using SHA1. */ static constexpr auto SHA = "SHA"; /** * Cipher suites using SHA256. */ static constexpr auto SHA256 = "SHA256"; /** * Cipher suites using SHA384. */ static constexpr auto SHA384 = "SHA384"; // The content of the default list is determined at compile time and normally corresponds to // ALL:!COMPLEMENTOFDEFAULT:!eNULL. static constexpr auto DEFAULT = "DEFAULT"; // The ciphers included in ALL, but not enabled by default. static constexpr auto COMPLEMENTOFDEFAULT = "COMPLEMENTOFDEFAULT"; static constexpr auto ALL = "ALL"; void move_to_end(const AliasMap &aliases, std::vector &ciphers, std::string_view cipher) const { this->move_to_end(ciphers, aliases.at(cipher)); } void move_to_end(std::vector &ciphers, const std::vector &ciphers_to_move_to_end) const { std::stable_partition(ciphers.begin(), ciphers.end(), [&ciphers_to_move_to_end](auto &cipher) { return std::find(ciphers_to_move_to_end.begin(), ciphers_to_move_to_end.end(), cipher) == ciphers_to_move_to_end.end(); }); } void add(const AliasMap &aliases, std::vector &ciphers, std::string_view alias) const { auto to_add = aliases.at(alias); ciphers.insert(ciphers.end(), to_add.begin(), to_add.end()); } void remove(const AliasMap &aliases, std::vector &ciphers, std::string_view alias) const { auto &to_remove = aliases.at(alias); ciphers.erase(std::remove_if(ciphers.begin(), ciphers.end(), [&](auto &x) { return std::find(to_remove.begin(), to_remove.end(), x) != to_remove.end(); }), ciphers.end()); } void strength_sort(std::vector &ciphers) const { /* * This routine sorts the ciphers with descending strength. The sorting * must keep the pre-sorted sequence. */ std::stable_sort(ciphers.begin(), ciphers.end(), [](auto &l, auto &r) { return l.strength_bits > r.strength_bits; }); } /* * See * https://github.com/openssl/openssl/blob/709651c9022e7be7e69cf8a2f6edf2c8722a6a1e/ssl/ssl_ciph.c#L1455 */ void default_sort(std::vector &ciphers) const { auto by_strength = [](auto &l, auto &r) { return l.strength_bits > r.strength_bits; }; // order all ciphers by strength first std::sort(ciphers.begin(), ciphers.end(), by_strength); auto it = std::stable_partition(ciphers.begin(), ciphers.end(), this->by_key_exchange(KeyExchange::EECDH)); /* AES is our preferred symmetric cipher */ auto aes = {Encryption::AES128, Encryption::AES128GCM, Encryption::AES256, Encryption::AES256GCM}; /* Now arrange all ciphers by preference: */ it = std::stable_partition(it, ciphers.end(), this->by_encryption(aes)); /* Move ciphers without forward secrecy to the end */; std::stable_partition( it, ciphers.end(), [compare = this->by_key_exchange(KeyExchange::RSA)](auto &c) { return !compare(c); }); } std::function by_protocol(Protocol val) const { return [val](auto &c) { return c.protocol == val; }; } std::function by_key_exchange(KeyExchange val) const { return [val](auto &c) { return c.kx == val; }; } std::function by_authentication(Authentication val) const { return [val](auto &c) { return c.au == val; }; } std::function by_encryption(std::set vals) const { return [vals](auto &c) { return vals.find(c.enc) != vals.end(); }; } std::function by_encryption(Encryption val) const { return [val](auto &c) { return c.enc == val; }; } std::function by_encryption_level(EncryptionLevel val) const { return [val](auto &c) { return c.level == val; }; } std::function by_message_digest(MessageDigest val) const { return [val](auto &c) { return c.mac == val; }; } std::pair split_on(std::string_view str, char c) const { auto ix = str.find(c); if (ix == str.npos) { return {str, ""}; } auto left = str.substr(0, ix); ix++; if (ix >= str.size()) { return {left, ""}; } return {left, str.substr(ix)}; } std::vector split_cipher_suite_string(std::string_view string) const { std::vector result; while (!string.empty()) { auto [line, rest] = this->split_on(string, ':'); string = rest; while (!line.empty()) { auto [part, rest] = this->split_on(line, ','); line = rest; result.push_back(part); } } return result; } std::vector all; public: OpenSSLCipherConfigurationParser() { this->all.reserve(CIPHER.size()); for (const auto &any : CIPHER) { auto &cipher = any.second; this->all.push_back(cipher); auto cipher_alias = cipher.open_ssl_alias; auto alias = aliases.find(cipher_alias); if (alias != aliases.end()) { alias->second.push_back(cipher); } else { std::vector list; list.push_back(cipher); aliases.insert({cipher_alias, list}); } aliases.insert({cipher.open_ssl_alias, std::vector{cipher}}); } // Note: the descriptions of the aliases within the comments are from // https://www.openssl.org/docs/manmaster/man1/openssl-ciphers.html // All cipher suites except the eNULL ciphers (which must be explicitly enabled if needed). // As of OpenSSL 1.0.0, the ALL cipher suites are sensibly ordered by default. this->default_sort(this->all); aliases.insert({ALL, this->all}); // "High" encryption cipher suites. This currently means those with key lengths larger than 128 // bits, and some cipher suites with 128-bit keys. std::vector high; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(high), this->by_encryption_level(EncryptionLevel::HIGH)); aliases.insert({HIGH, high}); // "Medium" encryption cipher suites, currently some of those using 128 bit encryption. std::vector medium; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(medium), this->by_encryption_level(EncryptionLevel::MEDIUM)); aliases.insert({MEDIUM, medium}); // Cipher suites using RSA key exchange or authentication. RSA is an alias for kRSA. std::vector krsa; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(krsa), this->by_key_exchange(KeyExchange::RSA)); aliases.insert({kRSA, krsa}); std::vector arsa; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(arsa), this->by_authentication(Authentication::RSA)); aliases.insert({aRSA, arsa}); aliases.insert({RSA, krsa}); // Cipher suites using ephemeral ECDH key agreement, including anonymous cipher suites. std::vector ecdh; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(ecdh), this->by_key_exchange(KeyExchange::EECDH)); aliases.insert({kEECDH, ecdh}); aliases.insert({kECDHE, ecdh}); aliases.insert({ECDH, ecdh}); // Cipher suites using authenticated ephemeral ECDH key agreement. aliases.insert({EECDH, ecdh}); aliases.insert({ECDHE, ecdh}); // Lists cipher suites which are only supported in at least TLS v1.2, TLS v1.0 or SSL v3.0 // respectively. Note: there are no cipher suites specific to TLS v1.1. Since this is only the // minimum version, if, for example, TLSv1.0 is negotiated then both TLSv1.0 and SSLv3.0 cipher // suites are available. Note: these cipher strings do not change the negotiated version of SSL // or TLS, they only affect the list of available cipher suites. std::vector tlsv2; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(tlsv2), this->by_protocol(Protocol::TLSv1_2)); aliases.insert({SSL_PROTO_TLSv1_2, tlsv2}); std::vector tlsv1; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(tlsv1), this->by_protocol(Protocol::TLSv1)); aliases.insert({SSL_PROTO_TLSv1_0, tlsv1}); aliases.insert({SSL_PROTO_TLSv1, tlsv1}); std::vector sslv3; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(sslv3), this->by_protocol(Protocol::SSLv3)); aliases.insert({SSL_PROTO_SSLv3, sslv3}); // cipher suites using 128 bit AES. std::vector aes128; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(aes128), this->by_encryption({Encryption::AES128, Encryption::AES128GCM})); aliases.insert({AES128, aes128}); // cipher suites using 256 bit AES. std::vector aes256; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(aes256), this->by_encryption({Encryption::AES256, Encryption::AES256GCM})); aliases.insert({AES256, aes256}); // cipher suites using either 128 or 256 bit AES. auto aes(aes128); aes.insert(aes.end(), aes256.begin(), aes256.end()); aliases.insert({AES, aes}); // AES in Galois Counter Mode (GCM). std::vector aesgcm; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(aesgcm), this->by_encryption({Encryption::AES128GCM, Encryption::AES256GCM})); aliases.insert({AESGCM, aesgcm}); // Cipher suites using ChaCha20. std::vector chacha20; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(chacha20), this->by_encryption(Encryption::CHACHA20POLY1305)); aliases.insert({CHACHA20, chacha20}); // Cipher suites using triple DES. std::vector triple_des; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(triple_des), this->by_encryption(Encryption::TRIPLE_DES)); aliases.insert({TRIPLE_DES, triple_des}); // Cipher suites using SHA1. std::vector sha1; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(sha1), this->by_message_digest(MessageDigest::SHA1)); aliases.insert({SHA1, sha1}); aliases.insert({SHA, sha1}); // Cipher suites using SHA256. std::vector sha256; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(sha256), this->by_message_digest(MessageDigest::SHA256)); aliases.insert({SHA256, sha256}); // Cipher suites using SHA384. std::vector sha384; std::copy_if(this->all.begin(), this->all.end(), std::back_inserter(sha384), this->by_message_digest(MessageDigest::SHA384)); aliases.insert({SHA384, sha384}); // COMPLEMENTOFDEFAULT: // The ciphers included in ALL, but not enabled by default. Currently this includes all RC4 and // anonymous ciphers. Note that this rule does not cover eNULL, which is not included by ALL // (use COMPLEMENTOFALL if necessary). Note that RC4 based cipher suites are not supported by // Fastly and the only supported anonymous ciphers are `ecdh` and `triple_des`. auto complement_of_default(ecdh); complement_of_default.insert(complement_of_default.end(), triple_des.begin(), triple_des.end()); aliases.insert({COMPLEMENTOFDEFAULT, complement_of_default}); // The content of the default list is determined at compile time and normally corresponds to // ALL:!COMPLEMENTOFDEFAULT:!eNULL. aliases.insert({DEFAULT, this->parse("ALL:!COMPLEMENTOFDEFAULT:!eNULL")}); } std::vector parse(std::string_view expression) const { /** * All ciphers by their openssl alias name. */ auto elements = this->split_cipher_suite_string(expression); std::vector ciphers; std::vector removed_ciphers; for (auto &element : elements) { if (element.rfind(DELETE, 0) == 0) { auto alias = element.substr(1); if (aliases.find(alias) != aliases.end()) { this->remove(aliases, ciphers, alias); } } else if (element.rfind(EXCLUDE, 0) == 0) { auto alias = element.substr(1); auto found = aliases.find(alias); if (found != aliases.end()) { auto to_add = found.operator->()->second; removed_ciphers.insert(removed_ciphers.end(), to_add.begin(), to_add.end()); } } else if (element.rfind(TO_END, 0) == 0) { auto alias = element.substr(1); if (aliases.find(alias) != aliases.end()) { this->move_to_end(aliases, ciphers, alias); } } else if ("@STRENGTH" == element) { this->strength_sort(ciphers); break; } else if (aliases.find(element) != aliases.end()) { this->add(aliases, ciphers, element); } else if (element.find(AND) != std::string::npos) { std::vector intersections; for (auto r : element | std::views::split(AND)) intersections.emplace_back(r.begin(), r.end()); if (intersections.size() > 0) { auto found = aliases.find(intersections[0]); if (found != aliases.end()) { auto result{found.operator->()->second}; for (int i = 1; i < intersections.size(); i++) { auto alias = aliases.find(intersections[i]); if (alias != aliases.end()) { // make `result` only contain the ciphers also present in `alias` result.erase(std::remove_if(result.begin(), result.end(), [&](auto x) { return std::find(alias->second.begin(), alias->second.end(), x) == alias->second.end(); }), result.end()); } } // Add all of `result` onto `ciphers` ciphers.insert(ciphers.end(), result.begin(), result.end()); } } } } // Remove all ciphers from `ciphers` which are contained in `removed_ciphers` ciphers.erase(std::remove_if(ciphers.begin(), ciphers.end(), [&removed_ciphers](auto &c) { return std::find(removed_ciphers.begin(), removed_ciphers.end(), c) != removed_ciphers.end(); }), ciphers.end()); return ciphers; } }; bool is_valid_ip(std::string_view ip) { int format = AF_INET; if (ip.find(':') != std::string::npos) { format = AF_INET6; } char octets[sizeof(struct in6_addr)]; if (inet_pton(format, ip.data(), octets) != 1) { return false; } return true; } // A "host" is a "hostname" and an optional "port" in the format hostname:port // A "hostname" is between 1 and 255 octets -- https://www.rfc-editor.org/rfc/rfc1123#page-13 // A "hostname" must start with a letter or digit -- https://www.rfc-editor.org/rfc/rfc1123#page-13 // A "hostname" is made up of "labels" delimited by a dot `.` // A "label" is between 1 and 63 octets bool is_valid_host(std::string_view host) { if (host.length() < 1) { return false; } auto first_character = host.front(); // check first character is in the regex [a-zA-Z0-9] if (!std::isalnum(first_character)) { return false; } // split the hostname from the port int pos = host.find_first_of(':'); std::string_view hostname = host.substr(0, pos); // hostnames can not be longer than 253 characters // This is because a hostname is represented as a series of labels, and is terminated by a label // of length zero. A label consists of a length octet followed by that number of octets // representing the name itself. https://www.rfc-editor.org/rfc/rfc1035#section-3.3 // https://www.rfc-editor.org/rfc/rfc2181#section-11 if (hostname.length() > 253) { return false; } auto last_character = hostname.back(); // check last character is in the regex [a-zA-Z0-9] if (!std::isalnum(last_character)) { return false; } for (auto r : hostname | std::views::split('.')) { auto label = std::string_view(r.begin(), r.end()); // Each label in a hostname can not be longer than 63 characters // https://www.rfc-editor.org/rfc/rfc2181#section-11 if (label.length() > 63) { return false; } // Each label can only contain the characters in the regex [a-zA-Z0-9\-] auto it = std::find_if_not(label.begin(), label.end(), [](auto character) { return std::isalnum(character) || character == '-'; }); if (it != label.end()) { return false; } } // if there is a port - confirm it is all digits and is between 0 and 65536 // https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml if (pos != std::string::npos) { std::string_view port = host.substr(pos + 1); if (!std::all_of(port.begin(), port.end(), [](auto c) { return std::isdigit(c); })) { return false; } int value; const std::from_chars_result result = std::from_chars(port.data(), port.data() + port.size(), value); if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range) { return false; } if (value == 0 || value >= 65536) { return false; } } return true; } OpenSSLCipherConfigurationParser cipher_parser; bool is_cipher_suite_supported_by_fastly(std::string_view cipher_spec) { auto ciphers = cipher_parser.parse(cipher_spec); return ciphers.size() > 0; } host_api::HostString parse_and_validate_name(JSContext *cx, JS::HandleValue name_val) { if (name_val.isNullOrUndefined()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_NAME_NOT_SET); return nullptr; } JS::RootedString name(cx, JS::ToString(cx, name_val)); if (!name) { return nullptr; } auto length = JS::GetStringLength(name); if (length > 254) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_NAME_TOO_LONG); return nullptr; } if (length == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_NAME_EMPTY); return nullptr; } return core::encode(cx, name); } const host_api::Backend *set_backend(JSContext *cx, JSObject *backend, JS::HandleValue name_val) { MOZ_ASSERT(Backend::is_instance(backend)); auto name = parse_and_validate_name(cx, name_val); if (!name) { return nullptr; } auto host_backend = new host_api::Backend(std::move(name)); JS::SetReservedSlot(backend, Backend::Slots::HostBackend, JS::PrivateValue(host_backend)); return host_backend; } const host_api::Backend *get_backend(JSContext *cx, JSObject *backend) { if (!Backend::is_instance(backend)) { return nullptr; } auto backend_slot = JS::GetReservedSlot(backend, Backend::Slots::HostBackend); if (!backend_slot.isDouble()) { return nullptr; } return static_cast(backend_slot.toPrivate()); } bool set_host_override(JSContext *cx, host_api::BackendConfig &backend_config, JS::HandleValue host_override_val) { auto host_override = JS::RootedString(cx, JS::ToString(cx, host_override_val)); if (!host_override) { return false; } if (JS_GetStringLength(host_override) == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_HOST_OVERRIDE_EMPTY); return false; } backend_config.host_override = core::encode(cx, host_override); return true; } bool set_sni_hostname(JSContext *cx, host_api::BackendConfig &backend, JS::HandleValue sni_hostname_val) { auto sni_hostname = RootedString(cx, JS::ToString(cx, sni_hostname_val)); if (!sni_hostname) { return false; } if (JS_GetStringLength(sni_hostname) == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_SNI_HOSTNAME_EMPTY); return false; } backend.sni_hostname = core::encode(cx, sni_hostname); return true; } bool validate_target(JSContext *cx, std::string_view target_string) { auto length = target_string.length(); if (length == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TARGET_EMPTY); return false; } if (target_string == "::") { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TARGET_INVALID); return false; } if (!is_valid_host(target_string) && !is_valid_ip(target_string)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TARGET_INVALID); return false; } return true; } host_api::BackendConfig default_backend_config{}; const uint64_t MAX_BACKEND_TIMEOUT = 0x100000000; bool apply_backend_config(JSContext *cx, host_api::BackendConfig &backend, HandleObject configuration) { bool found; JS::RootedValue host_override_val(cx); if (!JS_HasProperty(cx, configuration, "hostOverride", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "hostOverride", &host_override_val)) { return false; } if (!set_host_override(cx, backend, host_override_val)) { return false; } } JS::RootedValue connect_timeout_val(cx); if (!JS_HasProperty(cx, configuration, "connectTimeout", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "connectTimeout", &connect_timeout_val)) { return false; } auto parsed = parse_and_validate_timeout(cx, connect_timeout_val, "Backend constructor", "connectTimeout", MAX_BACKEND_TIMEOUT); if (!parsed) { return false; } backend.connect_timeout = parsed; } // Timeouts for backends must be less than 2^32 milliseconds, or // about a month and a half. JS::RootedValue first_byte_timeout_val(cx); if (!JS_HasProperty(cx, configuration, "firstByteTimeout", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "firstByteTimeout", &first_byte_timeout_val)) { return false; } auto parsed = parse_and_validate_timeout(cx, first_byte_timeout_val, "Backend constructor", "firstByteTimeout", MAX_BACKEND_TIMEOUT); if (!parsed) { return false; } backend.first_byte_timeout = parsed; } // Timeouts for backends must be less than 2^32 milliseconds, or // about a month and a half. JS::RootedValue between_bytes_timeout_val(cx); if (!JS_HasProperty(cx, configuration, "betweenBytesTimeout", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "betweenBytesTimeout", &between_bytes_timeout_val)) { return false; } auto parsed = parse_and_validate_timeout(cx, between_bytes_timeout_val, "Backend constructor", "betweenBytesTimeout", MAX_BACKEND_TIMEOUT); if (!parsed) { return false; } backend.between_bytes_timeout = parsed; } // Has to be either: 1; 1.1; 1.2; 1.3; JS::RootedValue tls_min_version_val(cx); if (!JS_HasProperty(cx, configuration, "tlsMinVersion", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "tlsMinVersion", &tls_min_version_val)) { return false; } double version; if (!JS::ToNumber(cx, tls_min_version_val, &version)) { return false; } if (std::isnan(version)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TLS_MIN_INVALID); return false; } if (version == 1.3) { backend.ssl_min_version = host_api::TlsVersion::version_1_3(); } else if (version == 1.2) { backend.ssl_min_version = host_api::TlsVersion::version_1_2(); } else if (version == 1.1) { backend.ssl_min_version = host_api::TlsVersion::version_1_1(); } else if (version == 1) { backend.ssl_min_version = host_api::TlsVersion::version_1(); } else { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TLS_MIN_INVALID); return false; } } // Has to be either: 1; 1.1; 1.2; 1.3; JS::RootedValue tls_max_version_val(cx); if (!JS_HasProperty(cx, configuration, "tlsMaxVersion", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "tlsMaxVersion", &tls_max_version_val)) { return false; } double version; if (!JS::ToNumber(cx, tls_max_version_val, &version)) { return false; } if (std::isnan(version)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TLS_MAX_INVALID); return false; } if (version == 1.3) { backend.ssl_max_version = host_api::TlsVersion::version_1_3(); } else if (version == 1.2) { backend.ssl_max_version = host_api::TlsVersion::version_1_2(); } else if (version == 1.1) { backend.ssl_max_version = host_api::TlsVersion::version_1_1(); } else if (version == 1) { backend.ssl_max_version = host_api::TlsVersion::version_1(); } else { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TLS_MAX_INVALID); return false; } } if (backend.ssl_min_version.has_value() && backend.ssl_max_version.has_value()) { if (backend.ssl_min_version->value > backend.ssl_max_version->value) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TLS_MIN_GREATER_THAN_TLS_MAX); return false; } } JS::RootedValue certificate_hostname_val(cx); if (!JS_HasProperty(cx, configuration, "certificateHostname", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "certificateHostname", &certificate_hostname_val)) { return false; } auto certificate_hostname = JS::RootedString(cx, JS::ToString(cx, certificate_hostname_val)); if (!certificate_hostname) { return false; } if (JS_GetStringLength(certificate_hostname) == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_CERTIFICATE_HOSTNAME_EMPTY); return false; } backend.cert_hostname = core::encode(cx, certificate_hostname); } JS::RootedValue use_ssl_val(cx); if (!JS_HasProperty(cx, configuration, "useSSL", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "useSSL", &use_ssl_val)) { return false; } backend.use_ssl = JS::ToBoolean(use_ssl_val); } JS::RootedValue dont_pool_val(cx); if (!JS_HasProperty(cx, configuration, "dontPool", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "dontPool", &dont_pool_val)) { return false; } backend.dont_pool = JS::ToBoolean(dont_pool_val); } JS::RootedValue ca_certificate_val(cx); if (!JS_HasProperty(cx, configuration, "caCertificate", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "caCertificate", &ca_certificate_val)) { return false; } auto ca_certificate = JS::RootedString(cx, JS::ToString(cx, ca_certificate_val)); if (!ca_certificate) { return false; } if (JS_GetStringLength(ca_certificate) == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_CA_CERTIFICATE_EMPTY); return false; } backend.ca_cert = core::encode(cx, ca_certificate); } // Cipher list consisting of one or more cipher strings separated by colons. // Commas or spaces are also acceptable separators but colons are normally used. JS::RootedValue ciphers_val(cx); if (!JS_HasProperty(cx, configuration, "ciphers", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "ciphers", &ciphers_val)) { return false; } auto ciphers_chars = core::encode(cx, ciphers_val); if (!ciphers_chars) { return false; } if (ciphers_chars.size() == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_CIPHERS_EMPTY); return false; } std::string cipher_spec(ciphers_chars.begin(), ciphers_chars.len); if (!is_cipher_suite_supported_by_fastly(cipher_spec)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_CIPHERS_NOT_AVALIABLE); return false; } backend.ciphers.emplace(std::move(ciphers_chars)); } JS::RootedValue sni_hostname_val(cx); if (!JS_HasProperty(cx, configuration, "sniHostname", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "sniHostname", &sni_hostname_val)) { return false; } if (!set_sni_hostname(cx, backend, sni_hostname_val)) { return false; } } JS::RootedValue client_cert_val(cx); if (!JS_HasProperty(cx, configuration, "clientCertificate", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "clientCertificate", &client_cert_val)) { return false; } if (!client_cert_val.isObject()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_CLIENT_CERTIFICATE_NOT_OBJECT); return false; } JS::RootedObject client_cert_obj(cx, &client_cert_val.toObject()); JS::RootedValue client_cert_cert_val(cx); if (!JS_HasProperty(cx, client_cert_obj, "certificate", &found)) { return false; } if (!found) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_CLIENT_CERTIFICATE_NO_CERTIFICATE); return false; } if (!JS_GetProperty(cx, client_cert_obj, "certificate", &client_cert_cert_val)) { return false; } RootedString client_cert(cx, JS::ToString(cx, client_cert_cert_val)); if (!client_cert) { return false; } if (JS_GetStringLength(client_cert) == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_CLIENT_CERTIFICATE_CERTIFICATE_EMPTY); return false; } JS::RootedValue client_cert_key_val(cx); if (!JS_HasProperty(cx, client_cert_obj, "key", &found)) { return false; } if (!found) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_CLIENT_CERTIFICATE_KEY_INVALID); return false; } if (!JS_GetProperty(cx, client_cert_obj, "key", &client_cert_key_val)) { return false; } if (!SecretStoreEntry::is_instance(client_cert_key_val)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_CLIENT_CERTIFICATE_KEY_INVALID); return false; } JS::RootedObject client_cert_key_obj(cx, &client_cert_key_val.toObject()); backend.client_cert = host_api::ClientCert{.cert = core::encode(cx, client_cert), .key = SecretStoreEntry::secret_handle(client_cert_key_obj).handle}; } JS::RootedValue grpc_val(cx); if (!JS_HasProperty(cx, configuration, "grpc", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "grpc", &grpc_val)) { return false; } backend.grpc = JS::ToBoolean(grpc_val); } JS::RootedValue http_keepalive_time_ms_val(cx); if (!JS_HasProperty(cx, configuration, "httpKeepalive", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "httpKeepalive", &http_keepalive_time_ms_val)) { return false; } auto parsed = parse_and_validate_timeout(cx, http_keepalive_time_ms_val, "httpKeepalive", "Backend constructor", MAX_BACKEND_TIMEOUT); if (!parsed) { return false; } backend.http_keepalive_time_ms = parsed; } JS::RootedValue tcp_keepalive_val(cx); if (!JS_HasProperty(cx, configuration, "tcpKeepalive", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configuration, "tcpKeepalive", &tcp_keepalive_val)) { return false; } if (tcp_keepalive_val.isBoolean()) { if (tcp_keepalive_val.toBoolean()) { backend.tcp_keepalive = host_api::TcpKeepalive{}; } } else if (!tcp_keepalive_val.isObject()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TCP_KEEPALIVE_NOT_OBJECT_OR_BOOL); return false; } if (tcp_keepalive_val.isObject()) { host_api::TcpKeepalive tcp_keepalive{}; JS::RootedObject tcp_keepalive_obj(cx, &tcp_keepalive_val.toObject()); JS::RootedValue tcp_keepalive_time_secs_val(cx); if (!JS_HasProperty(cx, tcp_keepalive_obj, "timeSecs", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, tcp_keepalive_obj, "timeSecs", &tcp_keepalive_time_secs_val)) { return false; } auto parsed = parse_and_validate_timeout(cx, tcp_keepalive_time_secs_val, "timeSecs", "Backend constructor", MAX_BACKEND_TIMEOUT); if (!parsed) { return false; } tcp_keepalive.time_secs = parsed; } JS::RootedValue tcp_keepalive_interval_secs_val(cx); if (!JS_HasProperty(cx, tcp_keepalive_obj, "intervalSecs", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, tcp_keepalive_obj, "intervalSecs", &tcp_keepalive_interval_secs_val)) { return false; } auto parsed = parse_and_validate_timeout(cx, tcp_keepalive_interval_secs_val, "intervalSecs", "Backend constructor", MAX_BACKEND_TIMEOUT); if (!parsed) { return false; } tcp_keepalive.interval_secs = parsed; } JS::RootedValue tcp_keepalive_probes_val(cx); if (!JS_HasProperty(cx, tcp_keepalive_obj, "probes", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, tcp_keepalive_obj, "probes", &tcp_keepalive_probes_val)) { return false; } double native_value; if (!JS::ToNumber(cx, tcp_keepalive_probes_val, &native_value)) { return false; } if (std::isnan(native_value) || native_value <= 0 || native_value >= 0x100000000) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TCP_KEEPALIVE_INVALID_PROBES); return false; } tcp_keepalive.probes = std::round(native_value); } backend.tcp_keepalive = tcp_keepalive; } } return true; } } // namespace JSString *Backend::name(JSContext *cx, JSObject *self) { auto backend = static_cast( JS::GetReservedSlot(self, Backend::Slots::HostBackend).toPrivate()); return JS_NewStringCopyN(cx, backend->name().begin(), backend->name().size()); } bool Backend::name_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { args.rval().setUndefined(); return true; } auto &name = backend->name(); auto name_str = JS_NewStringCopyN(cx, name.begin(), name.size()); if (!name_str) { return false; } args.rval().setString(name_str); return true; } bool Backend::exists(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "Backend.exists", 1)) { return false; } auto name = parse_and_validate_name(cx, args.get(0)); if (!name) { return false; } auto res = host_api::Backend::exists(name); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto exists = res.unwrap(); args.rval().setBoolean(exists); return true; } bool Backend::get_from_valid_name(JSContext *cx, host_api::HostString name, JS::MutableHandleValue out) { auto backend_instance = JS_NewObjectWithGivenProto(cx, &Backend::class_, Backend::proto_obj); if (!backend_instance) { return false; } JS::RootedValue backend_val(cx, JS::ObjectValue(*backend_instance)); JS::RootedObject backend(cx, backend_instance); if (!backend) { return false; } auto host_backend = new host_api::Backend(std::move(name)); JS::SetReservedSlot(backend, Backend::Slots::HostBackend, JS::PrivateValue(host_backend)); out.setObject(*backend); return true; } bool Backend::from_name(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "Backend.fromName", 1)) { return false; } auto name = parse_and_validate_name(cx, args.get(0)); if (!name) { return false; } auto res = host_api::Backend::exists(name); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto exists = res.unwrap(); if (!exists) { JS_ReportErrorNumberUTF8(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_FROMNAME_BACKEND_DOES_NOT_EXIST, name.begin()); return false; } get_from_valid_name(cx, std::move(name), args.rval()); return true; } bool Backend::health_for_name(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "Backend.health", 1)) { return false; } auto name = parse_and_validate_name(cx, args.get(0)); if (!name) { return false; } auto exists = host_api::Backend::exists(name); if (auto *err = exists.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!exists.unwrap()) { JS_ReportErrorNumberUTF8(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_IS_HEALTHY_BACKEND_DOES_NOT_EXIST, name.begin()); return false; } auto backend = new host_api::Backend(std::move(name)); auto res = backend->health(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto health = res.unwrap(); if (health.is_healthy()) { args.rval().setString(JS_NewStringCopyZ(cx, "healthy")); } else if (health.is_unhealthy()) { args.rval().setString(JS_NewStringCopyZ(cx, "unhealthy")); } else { args.rval().setString(JS_NewStringCopyZ(cx, "unknown")); } return true; } bool Backend::health(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->health(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto health = res.unwrap(); if (health.is_healthy()) { args.rval().setString(JS_NewStringCopyZ(cx, "healthy")); } else if (health.is_unhealthy()) { args.rval().setString(JS_NewStringCopyZ(cx, "unhealthy")); } else { args.rval().setString(JS_NewStringCopyZ(cx, "unknown")); } return true; } bool Backend::is_dynamic_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->is_dynamic(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setBoolean(res.unwrap()); return true; } bool Backend::target_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->get_host(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto str = core::decode(cx, res.unwrap()); if (!str) { return false; } args.rval().setString(str); return true; } bool Backend::host_override_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->get_override_host(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto str = core::decode(cx, res.unwrap()); if (!str) { return false; } args.rval().setString(str); return true; } bool Backend::port_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->get_port(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setNumber(res.unwrap()); return true; } bool Backend::connect_timeout_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->get_connect_timeout_ms(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); } else { args.rval().setNumber(res.unwrap().value()); } return true; } bool Backend::first_byte_timeout_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->get_first_byte_timeout_ms(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); } else { args.rval().setNumber(res.unwrap().value()); } return true; } bool Backend::between_bytes_timeout_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->get_between_bytes_timeout_ms(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); } else { args.rval().setNumber(res.unwrap().value()); } return true; } bool Backend::http_keepalive_time_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->get_http_keepalive_time(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setNumber(res.unwrap()); return true; } bool Backend::tcp_keepalive_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->get_tcp_keepalive_enable(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap()) { args.rval().setNull(); return true; } else { JS::RootedObject tcp_keepalive_obj(cx, JS_NewPlainObject(cx)); { auto res = backend->get_tcp_keepalive_interval(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::RootedValue val(cx, JS_NumberValue(res.unwrap())); if (!JS_SetProperty(cx, tcp_keepalive_obj, "intervalSecs", val)) { return false; } } { auto res = backend->get_tcp_keepalive_time(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::RootedValue val(cx, JS_NumberValue(res.unwrap())); if (!JS_SetProperty(cx, tcp_keepalive_obj, "timeSecs", val)) { return false; } } { auto res = backend->get_tcp_keepalive_probes(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::RootedValue val(cx, JS_NumberValue(res.unwrap())); if (!JS_SetProperty(cx, tcp_keepalive_obj, "probes", val)) { return false; } } args.rval().setObject(*tcp_keepalive_obj); } return true; } bool Backend::is_ssl_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->is_ssl(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setBoolean(res.unwrap()); return true; } bool Backend::tls_min_version_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->ssl_min_version(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); } else { args.rval().setNumber(res.unwrap().value().get_version_number()); } return true; } bool Backend::tls_max_version_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto backend = get_backend(cx, self); if (!backend) { return true; } auto res = backend->ssl_max_version(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); } else { args.rval().setNumber(res.unwrap().value().get_version_number()); } return true; } const JSFunctionSpec Backend::static_methods[] = { JS_FN("exists", exists, 1, JSPROP_ENUMERATE), JS_FN("fromName", from_name, 1, JSPROP_ENUMERATE), JS_FN("health", health_for_name, 1, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec Backend::static_properties[] = {JS_PS_END}; const JSFunctionSpec Backend::methods[] = { JS_FN("health", health, 0, JSPROP_ENUMERATE), JS_FN("toString", name_get, 0, JSPROP_ENUMERATE), JS_FN("toName", name_get, 0, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec Backend::properties[] = { JS_PSG("name", name_get, JSPROP_ENUMERATE), JS_PSG("isDynamic", is_dynamic_get, JSPROP_ENUMERATE), JS_PSG("target", target_get, JSPROP_ENUMERATE), JS_PSG("hostOverride", host_override_get, JSPROP_ENUMERATE), JS_PSG("port", port_get, JSPROP_ENUMERATE), JS_PSG("connectTimeout", connect_timeout_get, JSPROP_ENUMERATE), JS_PSG("firstByteTimeout", first_byte_timeout_get, JSPROP_ENUMERATE), JS_PSG("betweenBytesTimeout", between_bytes_timeout_get, JSPROP_ENUMERATE), JS_PSG("httpKeepaliveTime", http_keepalive_time_get, JSPROP_ENUMERATE), JS_PSG("tcpKeepalive", tcp_keepalive_get, JSPROP_ENUMERATE), JS_PSG("isSSL", is_ssl_get, JSPROP_ENUMERATE), JS_PSG("tlsMinVersion", tls_min_version_get, JSPROP_ENUMERATE), JS_PSG("tlsMaxVersion", tls_max_version_get, JSPROP_ENUMERATE), JS_PS_END}; JSObject *Backend::create(JSContext *cx, JS::HandleObject request) { JS::RootedValue request_url(cx, RequestOrResponse::url(request)); auto url_string = core::encode_spec_string(cx, request_url); if (!url_string.data) { return nullptr; } auto url = jsurl::new_jsurl(&url_string); if (!url) { JS_ReportErrorUTF8(cx, "URL constructor: %s is not a valid URL.", (char *)url_string.data); return nullptr; } const jsurl::SpecSlice slice = jsurl::host(url); auto name_js_str = JS_NewStringCopyN(cx, (char *)slice.data, slice.len); if (!name_js_str) { return nullptr; } std::string name_str((char *)slice.data, slice.len); JS::RootedValue name(cx, JS::StringValue(name_js_str)); JS::SetReservedSlot(request, static_cast(Request::Slots::Backend), name); // Check if we already constructed an implicit dynamic backend for this host. bool found; JS::RootedValue already_built_backend(cx); if (!JS_HasProperty(cx, Backend::backends, name_str.c_str(), &found)) { return nullptr; } if (found) { if (!JS_GetProperty(cx, Backend::backends, name_str.c_str(), &already_built_backend)) { return nullptr; } JS::RootedObject backend(cx, &already_built_backend.toObject()); return backend; } auto backend_instance = JS_NewObjectWithGivenProto(cx, &Backend::class_, Backend::proto_obj); if (!backend_instance) { return nullptr; } JS::RootedValue backend_val(cx, JS::ObjectValue(*backend_instance)); JS::RootedObject backend(cx, backend_instance); if (!backend) { return nullptr; } host_api::BackendConfig backend_config = default_backend_config.clone(); auto host_backend = set_backend(cx, backend, name); if (!host_backend) { return nullptr; } if (!set_host_override(cx, backend_config, name)) { return nullptr; } auto target_string_slice = core::encode_spec_string(cx, name); if (!target_string_slice.data) { return nullptr; } std::string_view target_string(reinterpret_cast(target_string_slice.data), target_string_slice.len); if (!validate_target(cx, target_string)) { return nullptr; } const jsurl::SpecString origin_specstring = jsurl::origin(url); std::string_view origin((char *)origin_specstring.data, origin_specstring.len); auto use_ssl = origin.rfind("https://", 0) == 0; if (use_ssl) { backend_config.use_ssl = true; if (!set_sni_hostname(cx, backend_config, name)) { return nullptr; } } auto res = host_api::HttpReq::register_dynamic_backend(host_backend->name(), target_string, backend_config); if (auto *err = res.to_err()) { if (host_api::error_is_unsupported(*err)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_DYNAMIC_BACKENDS_UNSUPPORTED_IMPLICIT, target_string.data(), url_string.data); return nullptr; } HANDLE_ERROR(cx, *err); return nullptr; } if (!JS_SetProperty(cx, Backend::backends, name_str.c_str(), backend_val)) { return nullptr; } return backend; } bool Backend::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The Backend builtin"); CTOR_HEADER("Backend", 1); auto configuration_parameter = args.get(0); if (!configuration_parameter.isObject()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_PARAMETER_NOT_OBJECT); return false; } auto configuration = RootedObject(cx, &configuration_parameter.toObject()); JS::RootedObject backend(cx, JS_NewObjectForConstructor(cx, &class_, args)); if (!backend) { return false; } JS::RootedValue name_val(cx); if (!JS_GetProperty(cx, configuration, "name", &name_val)) { return false; } auto host_backend = set_backend(cx, backend, name_val); if (!host_backend) { return false; } JS::RootedValue target_val(cx); if (!JS_GetProperty(cx, configuration, "target", &target_val)) { return false; } if (target_val.isNullOrUndefined()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_TARGET_NOT_SET); return false; } auto target_string_slice = core::encode_spec_string(cx, target_val); if (!target_string_slice.data) { return false; } std::string_view target_string(reinterpret_cast(target_string_slice.data), target_string_slice.len); if (!validate_target(cx, target_string)) { return false; } host_api::BackendConfig backend_config = default_backend_config.clone(); if (!apply_backend_config(cx, backend_config, configuration)) { return false; } auto res = host_api::HttpReq::register_dynamic_backend(host_backend->name(), target_string, backend_config); if (auto *err = res.to_err()) { if (host_api::error_is_unsupported(*err)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_DYNAMIC_BACKENDS_UNSUPPORTED_EXPLICIT, target_string_slice.data); return false; } HANDLE_ERROR(cx, *err); return false; } args.rval().setObject(*backend); return true; } void Backend::finalize(JS::GCContext *gcx, JSObject *obj) { auto backend = static_cast( JS::GetReservedSlot(obj, Backend::Slots::HostBackend).toPrivate()); free(backend); } bool set_default_backend_config(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "setDefaultDynamicBackendConfiguration", 1)) { return false; } auto backend_config_val = args.get(0); if (!backend_config_val.isObject()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BACKEND_PARAMETER_NOT_OBJECT); return false; } RootedObject backend_config_obj(cx, &backend_config_val.toObject()); if (!apply_backend_config(cx, default_backend_config, backend_config_obj)) { return false; } return true; } // TODO: in next major, when global and fastly experimental are deprecated, // make it so that calling twice always throws an already enforced error. // and possibly also don't allow changing the default again. bool enforce_explicit_backends(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); auto default_backend_val = args.get(0); if (!default_backend_val.isNullOrUndefined()) { if (!default_backend_val.isString()) { api::throw_error(cx, api::Errors::TypeError, "enforceExplicitBackends", "defaultBackend", "be undefined or a string"); return false; } JS::RootedString backend(cx, JS::ToString(cx, default_backend_val)); if (!backend) { return false; } Fastly::defaultBackend = backend; } Fastly::allowDynamicBackends = false; args.rval().setUndefined(); return true; } bool install(api::Engine *engine) { JS::RootedObject backends(engine->cx(), JS_NewPlainObject(engine->cx())); if (!backends) { return false; } Backend::backends.init(engine->cx(), backends); if (!Backend::init_class_impl(engine->cx(), engine->global())) { return false; } RootedObject backend_obj(engine->cx(), JS_GetConstructor(engine->cx(), BuiltinImpl::proto_obj)); RootedValue backend_val(engine->cx(), ObjectValue(*backend_obj)); RootedObject backend_ns(engine->cx(), JS_NewObject(engine->cx(), nullptr)); if (!JS_SetProperty(engine->cx(), backend_ns, "Backend", backend_val)) { return false; } auto set_default_backend_config_fn = JS_NewFunction(engine->cx(), &set_default_backend_config, 1, 0, "setDefaultDynamicBackendConfig"); RootedObject set_default_backend_config_obj(engine->cx(), JS_GetFunctionObject(set_default_backend_config_fn)); RootedValue set_default_backend_config_val(engine->cx(), JS::ObjectValue(*set_default_backend_config_obj)); if (!JS_SetProperty(engine->cx(), backend_ns, "setDefaultDynamicBackendConfig", set_default_backend_config_val)) { return false; } auto enforce_explicit_backends_fn = JS_NewFunction(engine->cx(), &enforce_explicit_backends, 1, 0, "enforceExplicitBackends"); RootedObject enforce_explicit_backends_obj(engine->cx(), JS_GetFunctionObject(enforce_explicit_backends_fn)); RootedValue enforce_explicit_backends_val(engine->cx(), JS::ObjectValue(*enforce_explicit_backends_obj)); if (!JS_SetProperty(engine->cx(), backend_ns, "enforceExplicitBackends", enforce_explicit_backends_val)) { return false; } RootedValue backend_ns_val(engine->cx(), JS::ObjectValue(*backend_ns)); if (!engine->define_builtin_module("fastly:backend", backend_ns_val)) { return false; } return true; } } // namespace fastly::backend ================================================ FILE: runtime/fastly/builtins/backend.h ================================================ #ifndef FASTLY_BACKEND_H #define FASTLY_BACKEND_H #include "builtin.h" #include "extension-api.h" namespace fastly::backend { class Backend : public builtins::FinalizableBuiltinImpl { private: public: static constexpr const char *class_name = "Backend"; static const int ctor_length = 1; enum Slots { HostBackend, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; inline static JS::PersistentRootedObject backends; static JSString *name(JSContext *cx, JSObject *self); static JSObject *create(JSContext *cx, JS::HandleObject request); // static methods static bool exists(JSContext *cx, unsigned argc, JS::Value *vp); static bool from_name(JSContext *cx, unsigned argc, JS::Value *vp); static bool health_for_name(JSContext *cx, unsigned argc, JS::Value *vp); // prototype methods static bool health(JSContext *cx, unsigned argc, JS::Value *vp); // getters static bool name_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool is_dynamic_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool target_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool host_override_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool port_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool connect_timeout_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool first_byte_timeout_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool between_bytes_timeout_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool http_keepalive_time_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool tcp_keepalive_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool is_ssl_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool tls_min_version_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool tls_max_version_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); static void finalize(JS::GCContext *gcx, JSObject *obj); static bool get_from_valid_name(JSContext *cx, host_api::HostString name, JS::MutableHandleValue out); }; bool set_default_backend_config(JSContext *cx, unsigned argc, JS::Value *vp); } // namespace fastly::backend #endif ================================================ FILE: runtime/fastly/builtins/body.cpp ================================================ #include #include #include #include #include #include "../../../StarlingMonkey/builtins/web/fetch/fetch-errors.h" #include "../../../StarlingMonkey/builtins/web/streams/native-stream-source.h" #include "../../../StarlingMonkey/builtins/web/url.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../host-api/host_api_fastly.h" #include "./fetch/request-response.h" #include "body.h" #include "fastly.h" #include "js/Stream.h" using builtins::web::streams::NativeStreamSource; using fastly::FastlyGetErrorMessage; using fastly::fastly::convertBodyInit; using fastly::fetch::RequestOrResponse; namespace fastly::body { host_api::HttpBody host_body(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(FastlyBody::Slots::Body)); return host_api::HttpBody(static_cast(val.toInt32())); } // concat(dest: FastlyBody): void; bool FastlyBody::concat(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1); auto destination_val = args.get(0); if (!FastlyBody::is_instance(destination_val)) { JS_ReportErrorUTF8( cx, "FastlyBody.concat: The `destination` argument is not an instance of FastlyBody."); return false; } JS::RootedObject destination(cx, &destination_val.toObject()); auto body = host_body(self); auto result = body.append(host_body(destination)); if (auto *err = result.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } // read(chunkSize: number): ArrayBuffer; bool FastlyBody::read(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1); double chunkSize_val; if (!JS::ToNumber(cx, args.get(0), &chunkSize_val)) { return false; } if (chunkSize_val < 0) { JS_ReportErrorUTF8(cx, "FastlyBody.read: The `chunkSize` argument has to be a positive integer."); return false; } if (chunkSize_val < 0 || std::isnan(chunkSize_val) || std::isinf(chunkSize_val)) { JS_ReportErrorASCII(cx, "chunkSize parameter is an invalid value, only positive numbers can be " "used for chunkSize."); return false; } uint32_t chunkSize = std::round(chunkSize_val); auto body = host_body(self); auto result = body.read(chunkSize); if (auto *err = result.to_err()) { if (chunkSize < 0) { JS_ReportErrorUTF8(cx, "FastlyBody.read: The `chunkSize` argument has to be a positive integer."); return false; } HANDLE_ERROR(cx, *err); return false; } auto &chunk = result.unwrap(); JS::UniqueChars buffer = std::move(chunk.ptr); JS::RootedObject array_buffer(cx); array_buffer.set(JS::NewArrayBufferWithContents( cx, chunk.len, buffer.get(), JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory)); if (!array_buffer) { JS_ReportOutOfMemory(cx); return false; } // `array_buffer` now owns `buf` static_cast(buffer.release()); args.rval().setObject(*array_buffer); return true; } // append(data: BodyInit): void; bool FastlyBody::append(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1); auto body = host_body(self); if (!body.valid()) { return false; } auto data_val = args.get(0); host_api::HttpBody source_body; JS::UniqueChars data; JS::RootedObject data_obj(cx, data_val.isObject() ? &data_val.toObject() : nullptr); // If the data parameter is a Host-backed ReadableStream we optimise our implementation // by using the ReadableStream's handle directly. if (data_obj && JS::IsReadableStream(data_obj)) { if (RequestOrResponse::body_unusable(cx, data_obj)) { api::throw_error(cx, FetchErrors::BodyStreamUnusable); } // If the stream is backed by a C@E body handle, we can use that handle directly. if (NativeStreamSource::stream_is_body(cx, data_obj)) { JS::RootedObject stream_source(cx, NativeStreamSource::get_stream_source(cx, data_obj)); JS::RootedObject source_owner(cx, NativeStreamSource::owner(stream_source)); source_body = RequestOrResponse::body_handle(source_owner); if (!source_body.valid()) { return false; } auto res = body.append(source_body); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } else { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BODY_APPEND_CONTENT_STREAM); return false; } } else { auto result = convertBodyInit(cx, data_val); if (result.isErr()) { return false; } size_t length; std::tie(data, length) = result.unwrap(); auto write_res = body.write_all_back(reinterpret_cast(data.get()), length); if (auto *err = write_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } } // prepend(data: BodyInit): void; bool FastlyBody::prepend(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1); auto body = host_body(self); if (!body.valid()) { return false; } auto data_val = args.get(0); host_api::HttpBody source_body; JS::RootedObject data_obj(cx, data_val.isObject() ? &data_val.toObject() : nullptr); // If the data parameter is a Host-backed ReadableStream we optimise our implementation // by using the ReadableStream's handle directly. if (data_obj && JS::IsReadableStream(data_obj)) { if (RequestOrResponse::body_unusable(cx, data_obj)) { return api::throw_error(cx, FetchErrors::BodyStreamUnusable); } // If the stream is backed by a C@E body handle, we can use that handle directly. if (NativeStreamSource::stream_is_body(cx, data_obj)) { JS::RootedObject stream_source(cx, NativeStreamSource::get_stream_source(cx, data_obj)); JS::RootedObject source_owner(cx, NativeStreamSource::owner(stream_source)); source_body = RequestOrResponse::body_handle(source_owner); if (!source_body.valid()) { return false; } auto make_res = host_api::HttpBody::make(); if (auto *err = make_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto new_body = make_res.unwrap(); if (!new_body.valid()) { return false; } auto res = new_body.append(source_body); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } res = new_body.append(body); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::SetReservedSlot(self, static_cast(Slots::Body), JS::Int32Value(new_body.handle)); args.rval().setUndefined(); return true; } else { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_BODY_PREPEND_CONTENT_STREAM); return false; } } else { auto result = convertBodyInit(cx, data_val); if (result.isErr()) { return false; } size_t length; JS::UniqueChars data; std::tie(data, length) = result.unwrap(); auto write_res = body.write_all_front(reinterpret_cast(data.get()), length); if (auto *err = write_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } } // close(): void; bool FastlyBody::close(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto body = host_body(self); auto result = body.close(); if (auto *err = result.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } bool FastlyBody::abandon(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto body = host_body(self); auto result = body.abandon(); if (auto *err = result.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } const JSFunctionSpec FastlyBody::static_methods[] = { JS_FS_END, }; const JSPropertySpec FastlyBody::static_properties[] = { JS_PS_END, }; const JSFunctionSpec FastlyBody::methods[] = { JS_FN("concat", concat, 1, JSPROP_ENUMERATE), JS_FN("read", read, 1, JSPROP_ENUMERATE), JS_FN("append", append, 1, JSPROP_ENUMERATE), JS_FN("prepend", prepend, 1, JSPROP_ENUMERATE), JS_FN("close", close, 0, JSPROP_ENUMERATE), JS_FN("abandon", abandon, 0, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec FastlyBody::properties[] = { JS_STRING_SYM_PS(toStringTag, "FastlyBody", JSPROP_READONLY), JS_PS_END, }; bool FastlyBody::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The FastlyBody builtin"); CTOR_HEADER("FastlyBody", 0); auto make_res = host_api::HttpBody::make(); if (auto *err = make_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body = make_res.unwrap(); if (!body.valid()) { return false; } JS::RootedObject instance(cx, JS_NewObjectForConstructor(cx, &class_, args)); if (!instance) { return false; } JS::SetReservedSlot(instance, static_cast(Slots::Body), JS::Int32Value(body.handle)); args.rval().setObject(*instance); return true; } JSObject *FastlyBody::create(JSContext *cx, uint32_t handle) { host_api::HttpBody body{handle}; JS::RootedObject instance( cx, JS_NewObjectWithGivenProto(cx, &FastlyBody::class_, FastlyBody::proto_obj)); if (!instance) { return nullptr; } JS::SetReservedSlot(instance, static_cast(Slots::Body), JS::Int32Value(handle)); return instance; } bool install(api::Engine *engine) { if (!FastlyBody::init_class_impl(engine->cx(), engine->global())) { return false; } RootedObject body_obj(engine->cx(), JS_GetConstructor(engine->cx(), FastlyBody::proto_obj)); RootedValue body_val(engine->cx(), ObjectValue(*body_obj)); RootedObject body_ns(engine->cx(), JS_NewObject(engine->cx(), nullptr)); if (!JS_SetProperty(engine->cx(), body_ns, "FastlyBody", body_val)) { return false; } RootedValue body_ns_val(engine->cx(), JS::ObjectValue(*body_ns)); if (!engine->define_builtin_module("fastly:body", body_ns_val)) { return false; } return true; } } // namespace fastly::body ================================================ FILE: runtime/fastly/builtins/body.h ================================================ #ifndef JS_COMPUTE_RUNTIME_BODY_H #define JS_COMPUTE_RUNTIME_BODY_H #include "builtin.h" #include "extension-api.h" namespace fastly::body { class FastlyBody final : public builtins::BuiltinImpl { public: static bool concat(JSContext *cx, unsigned argc, JS::Value *vp); static bool read(JSContext *cx, unsigned argc, JS::Value *vp); static bool append(JSContext *cx, unsigned argc, JS::Value *vp); static bool prepend(JSContext *cx, unsigned argc, JS::Value *vp); static bool close(JSContext *cx, unsigned argc, JS::Value *vp); static bool abandon(JSContext *cx, unsigned argc, JS::Value *vp); static constexpr const char *class_name = "FastlyBody"; enum class Slots { Body, Count, }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static const unsigned ctor_length = 0; static JSObject *create(JSContext *cx, uint32_t handle); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); }; } // namespace fastly::body #endif ================================================ FILE: runtime/fastly/builtins/cache-core.cpp ================================================ #include "cache-core.h" #include "../../../StarlingMonkey/builtins/web/fetch/headers.h" #include "../../../StarlingMonkey/builtins/web/streams/native-stream-source.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../host-api/host_api_fastly.h" #include "body.h" #include "builtin.h" #include "fastly.h" #include "host_api.h" #include "js/Stream.h" #include using builtins::web::fetch::Headers; using builtins::web::streams::NativeStreamSource; using fastly::body::FastlyBody; using fastly::fastly::convertBodyInit; using fastly::fetch::Request; using fastly::fetch::RequestOrResponse; using builtins::web::fetch::Headers; namespace fastly::cache_core { namespace { api::Engine *ENGINE; // The JavaScript LookupOptions parameter we are parsing should have the below interface: // interface LookupOptions { // headers?: HeadersInit; // } JS::Result parseLookupOptions(JSContext *cx, JS::HandleValue options_val) { host_api::CacheLookupOptions options; // options parameter is optional // options is meant to be an object with an optional headers field, // the headers field can be: // Headers | string[][] | Record; if (!options_val.isUndefined()) { if (!options_val.isObject()) { JS_ReportErrorASCII(cx, "options argument must be an object"); return JS::Result(JS::Error()); } JS::RootedObject options_obj(cx, &options_val.toObject()); JS::RootedValue headers_val(cx); if (!JS_GetProperty(cx, options_obj, "headers", &headers_val)) { return JS::Result(JS::Error()); } // headers property is optional if (!headers_val.isUndefined()) { if (!headers_val.isObject()) { JS_ReportErrorASCII( cx, "Failed to construct Headers object. If defined, the first argument must be either " "a [ ['name', 'value'], ... ] sequence, or a { 'name' : 'value', ... } record."); return JS::Result(JS::Error()); } auto request_handle_res = host_api::HttpReq::make(); if (auto *err = request_handle_res.to_err()) { HANDLE_ERROR(cx, *err); return JS::Result(JS::Error()); } auto request_handle = request_handle_res.unwrap(); JS::RootedObject headers(cx, Headers::create(cx, headers_val, Headers::HeadersGuard::Request)); if (!headers) { return JS::Result(JS::Error()); } if (Headers::mode(headers) == Headers::Mode::Uninitialized) { return options; } MOZ_ASSERT(Headers::mode(headers) == Headers::Mode::ContentOnly); Headers::HeadersList *headers_list = Headers::get_list(cx, headers); MOZ_ASSERT(headers_list); auto res = host_api::write_headers(request_handle.headers_writable(), *headers_list); if (auto *err = res.to_err()) { return JS::Result(JS::Error()); } options.request_headers = host_api::HttpReq(request_handle); } } return options; } // The JavaScript TransactionUpdateOptions parameter we are parsing should have the below interface: // interface TransactionUpdateOptions { // maxAge: number, // vary?: Array, // initialAge?: number, // staleWhileRevalidate?: number, // surrogateKeys?: Array, // length?: number, // userMetadata?: ArrayBufferView | ArrayBuffer | URLSearchParams | string, // } JS::Result parseTransactionUpdateOptions(JSContext *cx, JS::HandleValue options_val) { host_api::CacheWriteOptions options; if (!options_val.isObject()) { JS_ReportErrorASCII(cx, "options argument must be an object"); return JS::Result(JS::Error()); } JS::RootedObject options_obj(cx, &options_val.toObject()); JS::RootedValue maxAge_val(cx); if (!JS_GetProperty(cx, options_obj, "maxAge", &maxAge_val) || maxAge_val.isUndefined()) { JS_ReportErrorASCII(cx, "maxAge is required"); return JS::Result(JS::Error()); } // Convert maxAge field into a number and check the value adheres to our // validation rules. double maxAge; if (!JS::ToNumber(cx, maxAge_val, &maxAge)) { return JS::Result(JS::Error()); } if (maxAge < 0 || std::isnan(maxAge) || std::isinf(maxAge)) { JS_ReportErrorASCII( cx, "maxAge field is an invalid value, only positive numbers can be used for maxAge values."); return JS::Result(JS::Error()); } // turn millisecond representation into nanosecond representation constexpr double max_time_ms = static_cast(std::numeric_limits::max()) / 1'000'000; if (maxAge > max_time_ms) { JS_ReportErrorASCII(cx, "maxAge can not be greater than 2^63."); return JS::Result(JS::Error()); } options.max_age_ns = JS::ToUint64(maxAge) * 1'000'000; JS::RootedValue initialAge_val(cx); if (!JS_GetProperty(cx, options_obj, "initialAge", &initialAge_val)) { return JS::Result(JS::Error()); } if (!initialAge_val.isUndefined()) { // Convert initialAge field into a number and check the value adheres to our // validation rules. double initialAge; if (!JS::ToNumber(cx, initialAge_val, &initialAge)) { return JS::Result(JS::Error()); } if (initialAge < 0 || std::isnan(initialAge) || std::isinf(initialAge)) { JS_ReportErrorASCII(cx, "initialAge field is an invalid value, only positive numbers can be " "used for initialAge values."); return JS::Result(JS::Error()); } // turn millisecond representation into nanosecond representation if (initialAge > max_time_ms) { JS_ReportErrorASCII(cx, "initialAge can not be greater than 2^63."); return JS::Result(JS::Error()); } options.initial_age_ns = JS::ToUint64(initialAge) * 1'000'000; } JS::RootedValue staleWhileRevalidate_val(cx); if (!JS_GetProperty(cx, options_obj, "staleWhileRevalidate", &staleWhileRevalidate_val)) { return JS::Result(JS::Error()); } if (!staleWhileRevalidate_val.isUndefined()) { // Convert staleWhileRevalidate field into a number and check the value adheres to our // validation rules. double staleWhileRevalidate; if (!JS::ToNumber(cx, staleWhileRevalidate_val, &staleWhileRevalidate)) { return JS::Result(JS::Error()); } if (staleWhileRevalidate < 0 || std::isnan(staleWhileRevalidate) || std::isinf(staleWhileRevalidate)) { JS_ReportErrorASCII(cx, "staleWhileRevalidate field is an invalid value, only positive " "numbers can be used for staleWhileRevalidate values."); return JS::Result(JS::Error()); } // turn millisecond representation into nanosecond representation if (staleWhileRevalidate > max_time_ms) { JS_ReportErrorASCII(cx, "staleWhileRevalidate can not be greater than 2^63."); return JS::Result(JS::Error()); } options.stale_while_revalidate_ns = JS::ToUint64(staleWhileRevalidate) * 1'000'000; } JS::RootedValue length_val(cx); if (!JS_GetProperty(cx, options_obj, "length", &length_val)) { return JS::Result(JS::Error()); } if (!length_val.isUndefined()) { // Convert length field into a number and check the value adheres to our // validation rules. double length; if (!JS::ToNumber(cx, length_val, &length)) { return JS::Result(JS::Error()); } if (length < 0 || std::isnan(length) || std::isinf(length)) { JS_ReportErrorASCII( cx, "length field is an invalid value, only positive numbers can be used for length values."); return JS::Result(JS::Error()); } options.length = JS::ToUint64(length); } JS::RootedValue vary_val(cx); if (!JS_GetProperty(cx, options_obj, "vary", &vary_val)) { return JS::Result(JS::Error()); } if (!vary_val.isUndefined()) { JS::ForOfIterator it(cx); if (!it.init(vary_val)) { return JS::Result(JS::Error()); } JS::RootedValue entry_val(cx); std::string varies; bool first = true; while (true) { bool done; if (!it.next(&entry_val, &done)) { return JS::Result(JS::Error()); } if (done) { break; } auto vary = core::encode(cx, entry_val); if (!vary) { return JS::Result(JS::Error()); } if (first) { first = false; } else { varies += " "; } varies += vary; } options.vary_rule = varies; } JS::RootedValue surrogateKeys_val(cx); if (!JS_GetProperty(cx, options_obj, "surrogateKeys", &surrogateKeys_val)) { return JS::Result(JS::Error()); } if (!surrogateKeys_val.isUndefined()) { JS::ForOfIterator it(cx); if (!it.init(surrogateKeys_val)) { return JS::Result(JS::Error()); } JS::RootedValue entry_val(cx); std::string surrogateKeys; bool first = true; while (true) { bool done; if (!it.next(&entry_val, &done)) { return JS::Result(JS::Error()); } if (done) { break; } auto skey = core::encode(cx, entry_val); if (!skey) { return JS::Result(JS::Error()); } if (first) { first = false; } else { surrogateKeys += " "; } surrogateKeys += skey; } options.surrogate_keys = surrogateKeys; } JS::RootedValue userMetadata_val(cx); if (!JS_GetProperty(cx, options_obj, "userMetadata", &userMetadata_val)) { return JS::Result(JS::Error()); } if (!userMetadata_val.isUndefined()) { auto result = convertBodyInit(cx, userMetadata_val); if (result.isErr()) { return JS::Result(JS::Error()); } size_t length; JS::UniqueChars data; std::tie(data, length) = result.unwrap(); options.metadata = host_api::HostBytes( std::unique_ptr(reinterpret_cast(std::move(data).release())), length); } return options; } // The JavaScript TransactionInsertOptions parameter we are parsing should have the below interface: // interface TransactionInsertOptions { // maxAge: number, // vary?: Array, // initialAge?: number, // staleWhileRevalidate?: number, // surrogateKeys?: Array, // length?: number, // userMetadata?: ArrayBufferView | ArrayBuffer | URLSearchParams | string, // sensitive?: boolean, // } JS::Result parseTransactionInsertOptions(JSContext *cx, JS::HandleValue options_val) { auto options_res = parseTransactionUpdateOptions(cx, options_val); if (options_res.isErr()) { return JS::Result(JS::Error()); } auto options = options_res.unwrap(); JS::RootedObject options_obj(cx, &options_val.toObject()); JS::RootedValue sensitive_val(cx); if (!JS_GetProperty(cx, options_obj, "sensitive", &sensitive_val)) { return JS::Result(JS::Error()); } options.sensitive = JS::ToBoolean(sensitive_val); return options; } // The JavaScript TransactionInsertOptions parameter we are parsing should have the below interface: // interface InsertOptions extends TransactionInsertOptions { // headers?: HeadersInit, // } JS::Result parseInsertOptions(JSContext *cx, JS::HandleValue options_val) { auto options_res = parseTransactionInsertOptions(cx, options_val); if (options_res.isErr()) { return JS::Result(JS::Error()); } auto options = options_res.unwrap(); JS::RootedObject options_obj(cx, &options_val.toObject()); JS::RootedValue headers_val(cx); if (!JS_GetProperty(cx, options_obj, "headers", &headers_val)) { return JS::Result(JS::Error()); } // headers property is optional if (!headers_val.isUndefined()) { if (!headers_val.isObject()) { JS_ReportErrorASCII( cx, "Failed to construct Headers object. If defined, the first argument must be either " "a [ ['name', 'value'], ... ] sequence, or a { 'name' : 'value', ... } record."); return JS::Result(JS::Error()); } auto request_handle_res = host_api::HttpReq::make(); if (auto *err = request_handle_res.to_err()) { HANDLE_ERROR(cx, *err); return JS::Result(JS::Error()); } auto request_handle = request_handle_res.unwrap(); JS::RootedObject headers(cx, Headers::create(cx, headers_val, Headers::HeadersGuard::Request)); if (!headers) { return JS::Result(JS::Error()); } if (Headers::mode(headers) == Headers::Mode::Uninitialized) { return options; } MOZ_ASSERT(Headers::mode(headers) == Headers::Mode::ContentOnly); Headers::HeadersList *headers_list = Headers::get_list(cx, headers); MOZ_ASSERT(headers_list); auto res = host_api::write_headers(request_handle.headers_writable(), *headers_list); if (auto *err = res.to_err()) { return JS::Result(JS::Error()); } options.request_headers = host_api::HttpReq(request_handle); } return options; } } // namespace // Below is the implementation of the JavaScript CacheState Class which has this definition: // class CacheState { // found(): boolean; // usable(): boolean; // stale(): boolean; // mustInsertOrUpdate(): boolean; // } // found(): boolean; bool CacheState::found(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto state = static_cast( JS::GetReservedSlot(self, static_cast(Slots::State)).toInt32()); args.rval().setBoolean(state & CacheState::found_flag); return true; } // usable(): boolean; bool CacheState::usable(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto state = static_cast( JS::GetReservedSlot(self, static_cast(Slots::State)).toInt32()); args.rval().setBoolean(state & CacheState::usable_flag); return true; } // stale(): boolean; bool CacheState::stale(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto state = static_cast( JS::GetReservedSlot(self, static_cast(Slots::State)).toInt32()); args.rval().setBoolean(state & CacheState::stale_flag); return true; } // mustInsertOrUpdate(): boolean; bool CacheState::mustInsertOrUpdate(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto state = static_cast( JS::GetReservedSlot(self, static_cast(Slots::State)).toInt32()); args.rval().setBoolean(state & CacheState::must_insert_or_update_flag); return true; } const JSFunctionSpec CacheState::static_methods[] = {JS_FS_END}; const JSPropertySpec CacheState::static_properties[] = {JS_PS_END}; const JSFunctionSpec CacheState::methods[] = { JS_FN("found", found, 0, JSPROP_ENUMERATE), JS_FN("usable", usable, 0, JSPROP_ENUMERATE), JS_FN("stale", stale, 0, JSPROP_ENUMERATE), JS_FN("mustInsertOrUpdate", mustInsertOrUpdate, 0, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec CacheState::properties[] = { JS_STRING_SYM_PS(toStringTag, "CacheState", JSPROP_READONLY), JS_PS_END}; JSObject *CacheState::create(JSContext *cx, uint32_t state) { JS::RootedObject instance(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!instance) { return nullptr; } JS::SetReservedSlot(instance, static_cast(Slots::State), JS::Int32Value(state)); return instance; } // Below is the implementation of the JavaScript CacheEntry Class which has this definition: // class CacheEntry { // close(): void; // state(): CacheState; // userMetadata(): ArrayBuffer; // body(options?: CacheBodyOptions): ReadableStream; // length(): number | null; // maxAge(): number; // staleWhileRevalidate(): number; // age(): number; // hits(): number; // } bool CacheEntry::is_instance(JSObject *obj) { return BuiltinImpl::is_instance(obj) || TransactionCacheEntry::is_instance(obj); } bool CacheEntry::is_instance(JS::Value val) { return val.isObject() && is_instance(&val.toObject()); } host_api::CacheHandle CacheEntry::get_cache_handle(JSObject *self) { MOZ_ASSERT(CacheEntry::is_instance(self)); host_api::CacheHandle handle{static_cast( JS::GetReservedSlot(self, static_cast(Slots::Handle)).toInt32())}; return handle; } // close(): void; bool CacheEntry::close(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!check_receiver(cx, args.thisv(), "close")) { return false; } JS::RootedObject self(cx, &args.thisv().toObject()); if (!args.requireAtLeast(cx, "close", 0)) { return false; } auto handle = CacheEntry::get_cache_handle(self); auto res = handle.close(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } // state(): CacheState; bool CacheEntry::state(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!check_receiver(cx, args.thisv(), "state")) { return false; } JS::RootedObject self(cx, &args.thisv().toObject()); if (!args.requireAtLeast(cx, "state", 0)) { return false; } auto handle = CacheEntry::get_cache_handle(self); auto res = handle.get_state(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::RootedObject state(cx, CacheState::create(cx, res.unwrap().state)); args.rval().setObjectOrNull(state); return true; } // userMetadata(): ArrayBuffer; bool CacheEntry::userMetadata(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!check_receiver(cx, args.thisv(), "userMetadata")) { return false; } JS::RootedObject self(cx, &args.thisv().toObject()); if (!args.requireAtLeast(cx, "userMetadata", 0)) { return false; } auto handle = CacheEntry::get_cache_handle(self); auto res = handle.get_user_metadata(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto metadata = std::move(res.unwrap()); JS::RootedObject array_buffer(cx); array_buffer.set(JS::NewArrayBufferWithContents( cx, metadata.len, metadata.ptr.get(), JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory)); if (!array_buffer) { JS_ReportOutOfMemory(cx); return false; } // `array_buffer` now owns `metadata` static_cast(metadata.ptr.release()); args.rval().setObject(*array_buffer); return true; } // body(options?: CacheBodyOptions): ReadableStream; bool CacheEntry::body(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!check_receiver(cx, args.thisv(), "body")) { return false; } JS::RootedObject self(cx, &args.thisv().toObject()); if (!args.requireAtLeast(cx, "body", 0)) { return false; } auto handle = CacheEntry::get_cache_handle(self); host_api::CacheGetBodyOptions options; auto options_val = args.get(0); // options parameter is optional // options is meant to be an object with an optional `start` and `end` fields, both which can be // Numbers. if (!options_val.isUndefined()) { if (!options_val.isObject()) { JS_ReportErrorASCII(cx, "options argument must be an object"); return false; } JS::RootedObject options_obj(cx, &options_val.toObject()); JS::RootedValue start_val(cx); if (!JS_GetProperty(cx, options_obj, "start", &start_val)) { return false; } // start property is optional if (!start_val.isUndefined()) { // Convert start field into a number and check the value adheres to our // validation rules. double start; if (!JS::ToNumber(cx, start_val, &start)) { return false; } if (start < 0 || std::isnan(start) || std::isinf(start)) { JS_ReportErrorASCII( cx, "start field is an invalid value, only positive numbers can be used for start values."); return false; } options.start = JS::ToUint64(start); } JS::RootedValue end_val(cx); if (!JS_GetProperty(cx, options_obj, "end", &end_val)) { return false; } // end property is optional if (!end_val.isUndefined()) { // Convert start field into a number and check the value adheres to our // validation rules. double end; if (!JS::ToNumber(cx, end_val, &end)) { return false; } if (end < 0 || std::isnan(end) || std::isinf(end)) { JS_ReportErrorASCII( cx, "end field is an invalid value, only positive numbers can be used for end values."); return false; } options.end = JS::ToUint64(end); } // Reject cases where the start is greater than the end. // Ideally this would be a host-side check... but we didn't do it there to begin with, // so we couple it to an SDK/runtime upgrade. if (!start_val.isUndefined() && !end_val.isUndefined() && options.end > options.start) { JS_ReportErrorASCII(cx, "end field is before the start field"); return false; } } auto res = handle.get_body(options); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body = res.unwrap(); JS::SetReservedSlot(self, static_cast(Slots::Body), JS::Int32Value(body.handle)); JS::SetReservedSlot(self, static_cast(Slots::BodyStream), JS::NullValue()); JS::SetReservedSlot(self, static_cast(Slots::HasBody), JS::BooleanValue(true)); JS::SetReservedSlot(self, static_cast(Slots::BodyUsed), JS::FalseValue()); JS::RootedObject source( cx, NativeStreamSource::create(cx, self, JS::UndefinedHandleValue, RequestOrResponse::body_source_pull_algorithm, RequestOrResponse::body_source_cancel_algorithm)); if (!source) { return false; } // Create a readable stream with a highwater mark of 0.0 to prevent an eager // pull. With the default HWM of 1.0, the streams implementation causes a // pull, which means we enqueue a read from the host handle, which we quite // often have no interest in at all. JS::RootedObject body_stream(cx, NativeStreamSource::stream(source)); if (!body_stream) { return false; } args.rval().setObject(*body_stream); return true; } // length(): number | null; bool CacheEntry::length(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!check_receiver(cx, args.thisv(), "length")) { return false; } JS::RootedObject self(cx, &args.thisv().toObject()); if (!args.requireAtLeast(cx, "length", 0)) { return false; } auto handle = CacheEntry::get_cache_handle(self); auto res = handle.get_length(); if (auto *err = res.to_err()) { if (host_api::error_is_optional_none(*err)) { args.rval().setNull(); return true; } HANDLE_ERROR(cx, *err); return false; } auto length = res.unwrap(); JS::RootedValue result(cx, JS::NumberValue(length)); args.rval().set(result); return true; } // maxAge(): number; bool CacheEntry::maxAge(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!check_receiver(cx, args.thisv(), "maxAge")) { return false; } JS::RootedObject self(cx, &args.thisv().toObject()); if (!args.requireAtLeast(cx, "maxAge", 0)) { return false; } auto handle = CacheEntry::get_cache_handle(self); auto res = handle.get_max_age_ns(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto age = res.unwrap(); JS::RootedValue result(cx, JS::NumberValue(age / 1'000'000)); args.rval().set(result); return true; } // staleWhileRevalidate(): number; bool CacheEntry::staleWhileRevalidate(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!check_receiver(cx, args.thisv(), "staleWhileRevalidate")) { return false; } JS::RootedObject self(cx, &args.thisv().toObject()); if (!args.requireAtLeast(cx, "staleWhileRevalidate", 0)) { return false; } auto handle = CacheEntry::get_cache_handle(self); auto res = handle.get_stale_while_revalidate_ns(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto staleWhileRevalidateNs = res.unwrap(); JS::RootedValue result(cx, JS::NumberValue(staleWhileRevalidateNs / 1'000'000)); args.rval().set(result); return true; } // age(): number; bool CacheEntry::age(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!check_receiver(cx, args.thisv(), "age")) { return false; } JS::RootedObject self(cx, &args.thisv().toObject()); if (!args.requireAtLeast(cx, "age", 0)) { return false; } auto handle = CacheEntry::get_cache_handle(self); auto res = handle.get_age_ns(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto age = res.unwrap(); JS::RootedValue result(cx, JS::NumberValue(age / 1'000'000)); args.rval().set(result); return true; } // hits(): number; bool CacheEntry::hits(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!check_receiver(cx, args.thisv(), "hits")) { return false; } JS::RootedObject self(cx, &args.thisv().toObject()); if (!args.requireAtLeast(cx, "hits", 0)) { return false; } auto handle = CacheEntry::get_cache_handle(self); auto res = handle.get_hits(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto hits = res.unwrap(); JS::RootedValue result(cx, JS::NumberValue(hits)); args.rval().set(result); return true; } const JSFunctionSpec CacheEntry::static_methods[] = {JS_FS_END}; const JSPropertySpec CacheEntry::static_properties[] = {JS_PS_END}; const JSFunctionSpec CacheEntry::methods[] = { JS_FN("close", close, 0, JSPROP_ENUMERATE), JS_FN("state", state, 0, JSPROP_ENUMERATE), JS_FN("userMetadata", userMetadata, 0, JSPROP_ENUMERATE), JS_FN("body", body, 0, JSPROP_ENUMERATE), JS_FN("length", length, 0, JSPROP_ENUMERATE), JS_FN("maxAge", maxAge, 0, JSPROP_ENUMERATE), JS_FN("staleWhileRevalidate", staleWhileRevalidate, 0, JSPROP_ENUMERATE), JS_FN("age", age, 0, JSPROP_ENUMERATE), JS_FN("hits", hits, 0, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec CacheEntry::properties[] = { JS_STRING_SYM_PS(toStringTag, "CacheEntry", JSPROP_READONLY), JS_PS_END}; JSObject *CacheEntry::create(JSContext *cx, uint32_t handle) { JS::RootedObject instance(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!instance) { return nullptr; } JS::SetReservedSlot(instance, static_cast(Slots::Handle), JS::Int32Value(handle)); return instance; } // Below is the implementation of the JavaScript TransactionCacheEntry Class which has this // definition: class TransactionCacheEntry extends CacheEntry { // insert(options: TransactionInsertOptions): import("fastly:body").FastlyBody; // insertAndStreamBack(options: TransactionInsertOptions): [import("fastly:body").FastlyBody, // CacheEntry]; update(options: TransactionUpdateOptions): void; cancel(): void; // } // insert(options: TransactionInsertOptions): FastlyBody; bool TransactionCacheEntry::insert(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1); auto handle = CacheEntry::get_cache_handle(self); auto options_res = parseTransactionInsertOptions(cx, args.get(0)); if (options_res.isErr()) { return false; } auto options = options_res.unwrap(); auto res = handle.transaction_insert(options); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body = res.unwrap(); auto instance = FastlyBody::create(cx, body.handle); if (!instance) { return false; } args.rval().setObjectOrNull(instance); return true; } // insertAndStreamBack(options: TransactionInsertOptions): [FastlyBody, CacheEntry]; bool TransactionCacheEntry::insertAndStreamBack(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1); auto options_res = parseTransactionInsertOptions(cx, args.get(0)); if (options_res.isErr()) { return false; } auto options = options_res.unwrap(); auto handle = CacheEntry::get_cache_handle(self); auto res = handle.transaction_insert_and_stream_back(options); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } host_api::HttpBody body; host_api::CacheHandle cache_handle; std::tie(body, cache_handle) = res.unwrap(); JS::RootedValue writer(cx, JS::ObjectOrNullValue(FastlyBody::create(cx, body.handle))); JS::RootedValue reader(cx, JS::ObjectOrNullValue(CacheEntry::create(cx, cache_handle.handle))); JS::RootedValueVector result(cx); if (!result.append(writer)) { js::ReportOutOfMemory(cx); return false; } if (!result.append(reader)) { js::ReportOutOfMemory(cx); return false; } JS::Rooted writer_and_reader(cx, JS::NewArrayObject(cx, result)); if (!writer_and_reader) { return false; } args.rval().setObjectOrNull(writer_and_reader); return true; } // update(options: TransactionUpdateOptions): void; bool TransactionCacheEntry::update(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1); auto options_res = parseTransactionUpdateOptions(cx, args.get(0)); if (options_res.isErr()) { return false; } auto options = options_res.unwrap(); auto handle = CacheEntry::get_cache_handle(self); auto state_res = handle.get_state(); if (auto *err = state_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto state = state_res.unwrap(); if (!state.is_found() || !state.must_insert_or_update()) { JS_ReportErrorASCII(cx, "TransactionCacheEntry.update: entry does not exist or is not updatable"); return false; } auto res = handle.transaction_update(options); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } // cancel(): void; bool TransactionCacheEntry::cancel(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto handle = CacheEntry::get_cache_handle(self); auto res = handle.transaction_cancel(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } const JSFunctionSpec TransactionCacheEntry::static_methods[] = {JS_FS_END}; const JSPropertySpec TransactionCacheEntry::static_properties[] = {JS_PS_END}; const JSFunctionSpec TransactionCacheEntry::methods[] = { JS_FN("insert", insert, 1, JSPROP_ENUMERATE), JS_FN("insertAndStreamBack", insertAndStreamBack, 1, JSPROP_ENUMERATE), JS_FN("update", update, 1, JSPROP_ENUMERATE), JS_FN("cancel", cancel, 0, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec TransactionCacheEntry::properties[] = { JS_STRING_SYM_PS(toStringTag, "TransactionCacheEntry", JSPROP_READONLY), JS_PS_END}; JSObject *TransactionCacheEntry::create(JSContext *cx, uint32_t handle) { JS::RootedObject instance(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!instance) { return nullptr; } JS::SetReservedSlot(instance, static_cast(Slots::Handle), JS::Int32Value(handle)); return instance; } // Below is the implementation of the JavaScript CoreCache Class which has this definition: // class CoreCache { // static lookup(key: string, options?: LookupOptions): CacheEntry | null; // static insert(key: string, options: InsertOptions): import("fastly:body").FastlyBody; // static transactionLookup(key: string, options?: LookupOptions): TransactionCacheEntry; // } // static lookup(key: string, options?: LookupOptions): CacheEntry | null; bool CoreCache::lookup(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The CoreCache builtin"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "CoreCache.lookup", 1)) { return false; } // Convert key parameter into a string and check the value adheres to our validation rules. auto key = core::encode(cx, args.get(0)); if (!key) { return false; } if (key.len == 0) { JS_ReportErrorASCII(cx, "CoreCache.lookup: key can not be an empty string"); return false; } if (key.len > 8135) { JS_ReportErrorASCII(cx, "CoreCache.lookup: key is too long, the maximum allowed length is 8135."); return false; } auto options_result = parseLookupOptions(cx, args.get(1)); if (options_result.isErr()) { return false; } auto options = options_result.unwrap(); auto res = host_api::CacheHandle::lookup(key, options); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto cache_handle = res.unwrap(); auto cache_state_res = cache_handle.get_state(); if (auto *err = cache_state_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto cache_state = cache_state_res.unwrap(); if (cache_state.is_found()) { JS::RootedObject entry(cx, CacheEntry::create(cx, cache_handle.handle)); args.rval().setObject(*entry); } else { args.rval().setNull(); } return true; } // static insert(key: string, options: InsertOptions): FastlyBody; bool CoreCache::insert(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The CoreCache builtin"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "CoreCache.insert", 2)) { return false; } // Convert key parameter into a string and check the value adheres to our validation rules. auto key = core::encode(cx, args.get(0)); if (!key) { return false; } if (key.len == 0) { JS_ReportErrorASCII(cx, "CoreCache.insert: key can not be an empty string"); return false; } if (key.len > 8135) { JS_ReportErrorASCII(cx, "CoreCache.insert: key is too long, the maximum allowed length is 8135."); return false; } auto options_res = parseInsertOptions(cx, args.get(1)); if (options_res.isErr()) { return false; } auto options = options_res.unwrap(); auto res = host_api::CacheHandle::insert(key, options); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body = res.unwrap(); JS::RootedObject instance(cx, FastlyBody::create(cx, body.handle)); if (!instance) { return false; } args.rval().setObjectOrNull(instance); return true; } // static transactionLookup(key: string, options?: LookupOptions): TransactionCacheEntry; bool CoreCache::transactionLookup(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The CoreCache builtin"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "CoreCache.transactionLookup", 1)) { return false; } // Convert key parameter into a string and check the value adheres to our validation rules. auto key = core::encode(cx, args.get(0)); if (!key) { return false; } if (key.len == 0) { JS_ReportErrorASCII(cx, "CoreCache.transactionLookup: key can not be an empty string"); return false; } if (key.len > 8135) { JS_ReportErrorASCII( cx, "CoreCache.transactionLookup: key is too long, the maximum allowed length is 8135."); return false; } auto options_result = parseLookupOptions(cx, args.get(1)); if (options_result.isErr()) { return false; } auto options = options_result.unwrap(); auto res = host_api::CacheHandle::transaction_lookup(key, options); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto cache_handle = res.unwrap(); JS::RootedObject entry(cx, TransactionCacheEntry::create(cx, cache_handle.handle)); args.rval().setObject(*entry); return true; } const JSFunctionSpec CoreCache::static_methods[] = { JS_FN("lookup", lookup, 1, JSPROP_ENUMERATE), JS_FN("insert", insert, 2, JSPROP_ENUMERATE), JS_FN("transactionLookup", transactionLookup, 1, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec CoreCache::static_properties[] = {JS_PS_END}; const JSFunctionSpec CoreCache::methods[] = {JS_FS_END}; const JSPropertySpec CoreCache::properties[] = { JS_STRING_SYM_PS(toStringTag, "CoreCache", JSPROP_READONLY), JS_PS_END}; bool install(api::Engine *engine) { ENGINE = engine; if (!CoreCache::init_class_impl(engine->cx(), engine->global())) { return false; } if (!CacheEntry::init_class_impl(engine->cx(), engine->global())) { return false; } JS::RootedObject proto(engine->cx(), CacheEntry::proto_obj); if (!proto) { return false; } if (!TransactionCacheEntry::init_class_impl(engine->cx(), engine->global(), proto)) { return false; } if (!CacheState::init_class_impl(engine->cx(), engine->global())) { return false; } // fastly:cache RootedObject cache(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue cache_val(engine->cx(), JS::ObjectValue(*cache)); RootedObject core_cache_obj(engine->cx(), JS_GetConstructor(engine->cx(), CoreCache::proto_obj)); RootedValue core_cache_val(engine->cx(), ObjectValue(*core_cache_obj)); if (!JS_SetProperty(engine->cx(), cache, "CoreCache", core_cache_val)) { return false; } RootedObject cache_entry_obj(engine->cx(), JS_GetConstructor(engine->cx(), CacheEntry::proto_obj)); RootedValue cache_entry_val(engine->cx(), ObjectValue(*cache_entry_obj)); if (!JS_SetProperty(engine->cx(), cache, "CacheEntry", cache_entry_val)) { return false; } RootedObject cache_state_obj(engine->cx(), JS_GetConstructor(engine->cx(), CacheState::proto_obj)); RootedValue cache_state_val(engine->cx(), ObjectValue(*cache_state_obj)); if (!JS_SetProperty(engine->cx(), cache, "CacheState", cache_state_val)) { return false; } RootedObject transaction_cache_entry_obj( engine->cx(), JS_GetConstructor(engine->cx(), TransactionCacheEntry::proto_obj)); RootedValue transaction_cache_entry_val(engine->cx(), ObjectValue(*transaction_cache_entry_obj)); if (!JS_SetProperty(engine->cx(), cache, "TransactionCacheEntry", transaction_cache_entry_val)) { return false; } RootedValue simple_cache_val(engine->cx()); if (!JS_GetProperty(engine->cx(), engine->global(), "SimpleCache", &simple_cache_val)) { return false; } if (!JS_SetProperty(engine->cx(), cache, "SimpleCache", simple_cache_val)) { return false; } RootedValue simple_cache_entry_val(engine->cx()); if (!JS_GetProperty(engine->cx(), engine->global(), "SimpleCacheEntry", &simple_cache_entry_val)) { return false; } if (!JS_SetProperty(engine->cx(), cache, "SimpleCacheEntry", simple_cache_entry_val)) { return false; } if (!engine->define_builtin_module("fastly:cache", cache_val)) { return false; } return true; } } // namespace fastly::cache_core ================================================ FILE: runtime/fastly/builtins/cache-core.h ================================================ #ifndef FASTLY_CACHE_CORE_H #define FASTLY_CACHE_CORE_H #include "./fetch/request-response.h" #include "builtin.h" #include "extension-api.h" namespace fastly::cache_core { // export class CacheState { // found(): boolean; // usable(): boolean; // stale(): boolean; // mustInsertOrUpdate(): boolean; // } class CacheState : public builtins::BuiltinNoConstructor { static constexpr const uint8_t found_flag = 1 << 0; static constexpr const uint8_t usable_flag = 1 << 1; static constexpr const uint8_t stale_flag = 1 << 2; static constexpr const uint8_t must_insert_or_update_flag = 1 << 3; // found(): boolean; static bool found(JSContext *cx, unsigned argc, JS::Value *vp); // usable(): boolean; static bool usable(JSContext *cx, unsigned argc, JS::Value *vp); // stale(): boolean; static bool stale(JSContext *cx, unsigned argc, JS::Value *vp); // mustInsertOrUpdate(): boolean; static bool mustInsertOrUpdate(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "CacheState"; static const int ctor_length = 0; enum Slots { State, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static JSObject *create(JSContext *cx, uint32_t handle); }; class CacheEntry : public builtins::BuiltinNoConstructor { // cache-close: func(handle: cache-handle) -> result<_, error> // close(): void; static bool close(JSContext *cx, unsigned argc, JS::Value *vp); // cache-get-state: func(handle: cache-handle) -> result // state(): CacheState; static bool state(JSContext *cx, unsigned argc, JS::Value *vp); /// cache-get-user-metadata: func(handle: cache-handle) -> result, error> // userMetadata(): ArrayBuffer; static bool userMetadata(JSContext *cx, unsigned argc, JS::Value *vp); // cache-get-body: func(handle: cache-handle, options: cache-get-body-options) -> // result body(options?: CacheBodyOptions): ReadableStream; static bool body(JSContext *cx, unsigned argc, JS::Value *vp); // cache-get-length: func(handle: cache-handle) -> result // length(): number; static bool length(JSContext *cx, unsigned argc, JS::Value *vp); // cache-get-max-age-ns: func(handle: cache-handle) -> result // maxAge(): number; static bool maxAge(JSContext *cx, unsigned argc, JS::Value *vp); // cache-get-stale-while-revalidate-ns: func(handle: cache-handle) -> result // staleWhileRevalidate(): number; static bool staleWhileRevalidate(JSContext *cx, unsigned argc, JS::Value *vp); // cache-get-age-ns: func(handle: cache-handle) -> result // age(): number; static bool age(JSContext *cx, unsigned argc, JS::Value *vp); // cache-get-hits: func(handle: cache-handle) -> result // hits(): number; static bool hits(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "CacheEntry"; static const int ctor_length = 0; enum Slots { Body = static_cast(fetch::RequestOrResponse::Slots::Body), BodyStream = static_cast(fetch::RequestOrResponse::Slots::BodyStream), HasBody = static_cast(fetch::RequestOrResponse::Slots::HasBody), BodyUsed = static_cast(fetch::RequestOrResponse::Slots::BodyUsed), Handle = static_cast(fetch::RequestOrResponse::Slots::Count), Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool is_instance(JSObject *obj); static bool is_instance(JS::Value val); static host_api::CacheHandle get_cache_handle(JSObject *self); static JSObject *create(JSContext *cx, uint32_t handle); }; class TransactionCacheEntry : public builtins::BuiltinNoConstructor { static bool insert(JSContext *cx, unsigned argc, JS::Value *vp); static bool insertAndStreamBack(JSContext *cx, unsigned argc, JS::Value *vp); static bool update(JSContext *cx, unsigned argc, JS::Value *vp); static bool cancel(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "TransactionCacheEntry"; static const int ctor_length = 0; enum Slots { Body = static_cast(CacheEntry::Slots::Body), BodyStream = static_cast(CacheEntry::Slots::BodyStream), HasBody = static_cast(CacheEntry::Slots::HasBody), BodyUsed = static_cast(CacheEntry::Slots::BodyUsed), Handle = static_cast(CacheEntry::Slots::Handle), Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static JSObject *create(JSContext *cx, uint32_t handle); }; class CoreCache : public builtins::BuiltinNoConstructor { // cache-lookup: func(cache-key: string, options: cache-lookup-options) -> result static lookup(key: string, options?: LookupOptions): CacheEntry | null; static bool lookup(JSContext *cx, unsigned argc, JS::Value *vp); // cache-insert: func(cache-key: string, options: cache-write-options) -> result static insert(key: string, options: InsertOptions): FastlyBody; static bool insert(JSContext *cx, unsigned argc, JS::Value *vp); // transaction-lookup: func(cache-key: string, options: cache-lookup-options) -> // result static transactionLookup(key: string, optoptions?: LookupOptions): // CacheEntry | null; static bool transactionLookup(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "CoreCache"; static const int ctor_length = 0; enum Slots { Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; }; } // namespace fastly::cache_core #endif ================================================ FILE: runtime/fastly/builtins/cache-override.cpp ================================================ // TODO: remove these once the warnings are fixed #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" #include "js/experimental/TypedData.h" // used in "js/Conversions.h" #pragma clang diagnostic pop #include "js/Conversions.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "cache-override.h" #include "fastly.h" #include "host_api.h" using builtins::BuiltinImpl; using fastly::FastlyGetErrorMessage; namespace fastly::cache_override { namespace { bool parse_mode(JSContext *cx, JS::HandleValue mode, CacheOverride::CacheOverrideMode *mode_out) { auto mode_chars = core::encode(cx, mode); if (!mode_chars) { return false; } if (!strcmp(mode_chars.begin(), "none")) { *mode_out = CacheOverride::CacheOverrideMode::None; } else if (!strcmp(mode_chars.begin(), "pass")) { *mode_out = CacheOverride::CacheOverrideMode::Pass; } else if (!strcmp(mode_chars.begin(), "override")) { *mode_out = CacheOverride::CacheOverrideMode::Override; } else { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_CACHE_OVERRIDE_MODE_INVALID, mode_chars.begin()); return false; } return true; } } // namespace CacheOverride::CacheOverrideMode CacheOverride::mode(JSObject *self) { return (CacheOverride::CacheOverrideMode)JS::GetReservedSlot(self, Slots::Mode).toInt32(); } void CacheOverride::set_mode(JSObject *self, CacheOverride::CacheOverrideMode mode) { MOZ_ASSERT(is_instance(self)); JS::SetReservedSlot(self, CacheOverride::Slots::Mode, JS::Int32Value((int32_t)mode)); } JS::Value CacheOverride::ttl(JSObject *self) { MOZ_ASSERT(is_instance(self)); if (CacheOverride::mode(self) != CacheOverride::CacheOverrideMode::Override) { return JS::UndefinedValue(); } return JS::GetReservedSlot(self, Slots::TTL); } void CacheOverride::set_ttl(JSObject *self, uint32_t ttl) { MOZ_ASSERT(is_instance(self)); MOZ_ASSERT(mode(self) == CacheOverride::CacheOverrideMode::Override); JS::SetReservedSlot(self, CacheOverride::Slots::TTL, JS::Int32Value((int32_t)ttl)); } JS::Value CacheOverride::swr(JSObject *self) { MOZ_ASSERT(is_instance(self)); if (CacheOverride::mode(self) != CacheOverride::CacheOverrideMode::Override) return JS::UndefinedValue(); return JS::GetReservedSlot(self, Slots::SWR); } void CacheOverride::set_swr(JSObject *self, uint32_t swr) { MOZ_ASSERT(is_instance(self)); MOZ_ASSERT(CacheOverride::mode(self) == CacheOverride::CacheOverrideMode::Override); JS::SetReservedSlot(self, CacheOverride::Slots::SWR, JS::Int32Value((int32_t)swr)); } JS::Value CacheOverride::surrogate_key(JSObject *self) { MOZ_ASSERT(is_instance(self)); if (CacheOverride::mode(self) != CacheOverride::CacheOverrideMode::Override) return JS::UndefinedValue(); return JS::GetReservedSlot(self, Slots::SurrogateKey); } void CacheOverride::set_surrogate_key(JSObject *self, JSString *key) { MOZ_ASSERT(is_instance(self)); MOZ_ASSERT(CacheOverride::mode(self) == CacheOverride::CacheOverrideMode::Override); JS::SetReservedSlot(self, CacheOverride::Slots::SurrogateKey, JS::StringValue(key)); } JS::Value CacheOverride::pci(JSObject *self) { MOZ_ASSERT(is_instance(self)); if (CacheOverride::mode(self) != CacheOverride::CacheOverrideMode::Override) return JS::UndefinedValue(); return JS::GetReservedSlot(self, Slots::PCI); } void CacheOverride::set_pci(JSObject *self, bool pci) { MOZ_ASSERT(is_instance(self)); MOZ_ASSERT(CacheOverride::mode(self) == CacheOverride::CacheOverrideMode::Override); JS::SetReservedSlot(self, CacheOverride::Slots::PCI, JS::BooleanValue(pci)); } JSObject *CacheOverride::beforeSend(JSObject *self) { MOZ_ASSERT(is_instance(self)); auto before_send = JS::GetReservedSlot(self, Slots::BeforeSend); if (before_send.isUndefined()) { return nullptr; } return before_send.toObjectOrNull(); } void CacheOverride::set_beforeSend(JSObject *self, JSObject *fn) { MOZ_ASSERT(is_instance(self)); JS::SetReservedSlot(self, Slots::BeforeSend, JS::ObjectValue(*fn)); } JSObject *CacheOverride::afterSend(JSObject *self) { MOZ_ASSERT(is_instance(self)); auto after_send = JS::GetReservedSlot(self, Slots::AfterSend); if (after_send.isUndefined()) { return nullptr; } return after_send.toObjectOrNull(); } void CacheOverride::set_afterSend(JSObject *self, JSObject *fn) { MOZ_ASSERT(is_instance(self)); JS::SetReservedSlot(self, Slots::AfterSend, JS::ObjectValue(*fn)); } host_api::CacheOverrideTag CacheOverride::abi_tag(JSObject *self) { host_api::CacheOverrideTag tag; MOZ_ASSERT(is_instance(self)); switch (CacheOverride::mode(self)) { case CacheOverride::CacheOverrideMode::None: return tag; case CacheOverride::CacheOverrideMode::Pass: tag.set_pass(); return tag; default:; } if (!ttl(self).isUndefined()) { tag.set_ttl(); } if (!swr(self).isUndefined()) { tag.set_stale_while_revalidate(); } if (!pci(self).isUndefined() && pci(self).toBoolean()) { tag.set_pci(); } return tag; } bool CacheOverride::mode_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "mode get", "CacheOverride"); } const char *mode_chars; switch (mode(self)) { case CacheOverrideMode::None: mode_chars = "none"; break; case CacheOverrideMode::Pass: mode_chars = "pass"; break; case CacheOverrideMode::Override: mode_chars = "override"; break; } JS::RootedString mode_str(cx, JS_NewStringCopyZ(cx, mode_chars)); if (!mode_str) return false; rval.setString(mode_str); return true; } bool CacheOverride::ensure_override(JSContext *cx, JS::HandleObject self, const char *field) { if (mode(self) == CacheOverrideMode::Override) return true; JS_ReportErrorUTF8(cx, "Can't set %s on CacheOverride object whose mode " "isn't \"override\"", field); return false; } bool CacheOverride::mode_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue ret) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "mode get", "CacheOverride"); } CacheOverrideMode mode; if (!parse_mode(cx, val, &mode)) { return false; } set_mode(self, mode); return true; } bool CacheOverride::ttl_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "ttl get", "CacheOverride"); } rval.set(ttl(self)); return true; } bool CacheOverride::ttl_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "ttl set", "CacheOverride"); } if (!ensure_override(cx, self, "a TTL")) return false; if (val.isUndefined()) { JS::SetReservedSlot(self, Slots::TTL, val); } else { int32_t ttl; if (!JS::ToInt32(cx, val, &ttl)) return false; set_ttl(self, ttl); } rval.set(ttl(self)); return true; } bool CacheOverride::swr_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "swr get", "CacheOverride"); } rval.set(swr(self)); return true; } bool CacheOverride::swr_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "swr set", "CacheOverride"); } if (!ensure_override(cx, self, "SWR")) return false; if (val.isUndefined()) { JS::SetReservedSlot(self, Slots::SWR, val); } else { int32_t swr; if (!JS::ToInt32(cx, val, &swr)) return false; set_swr(self, swr); } rval.set(swr(self)); return true; } bool CacheOverride::surrogate_key_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "surrogate_key get", "CacheOverride"); } rval.set(surrogate_key(self)); return true; } bool CacheOverride::surrogate_key_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "surrogate_key set", "CacheOverride"); } if (!ensure_override(cx, self, "a surrogate key")) return false; if (val.isUndefined()) { JS::SetReservedSlot(self, Slots::SurrogateKey, val); } else { JS::RootedString surrogate_key(cx, JS::ToString(cx, val)); if (!surrogate_key) return false; set_surrogate_key(self, surrogate_key); } rval.set(surrogate_key(self)); return true; } bool CacheOverride::pci_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "pci get", "CacheOverride"); } rval.set(pci(self)); return true; } bool CacheOverride::pci_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "pci set", "CacheOverride"); } if (!ensure_override(cx, self, "PCI")) return false; if (val.isUndefined()) { JS::SetReservedSlot(self, Slots::PCI, val); } else { bool pci = JS::ToBoolean(val); set_pci(self, pci); } rval.set(pci(self)); return true; } bool CacheOverride::before_send_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "beforeSend get", "CacheOverride"); } JSObject *beforeSend(self); if (!beforeSend) { rval.setUndefined(); return true; } rval.setObject(*beforeSend); return true; } bool CacheOverride::before_send_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "beforeSend set", "CacheOverride"); } if (!ensure_override(cx, self, "beforeSend")) return false; if (val.isUndefined()) { JS::SetReservedSlot(self, Slots::BeforeSend, JS::UndefinedValue()); rval.setUndefined(); return true; } else if (!val.isObject() || !JS::IsCallable(&val.toObject())) { JS_ReportErrorUTF8(cx, "CacheOverride: beforeSend must be a function"); return false; } else { set_beforeSend(self, &val.toObject()); } rval.setObject(*beforeSend(self)); return true; } bool CacheOverride::after_send_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "afterSend get", "CacheOverride"); } JSObject *afterSend(self); if (!afterSend) { rval.setUndefined(); return true; } rval.setObject(*afterSend); return true; } bool CacheOverride::after_send_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval) { if (self == proto_obj) { return api::throw_error(cx, api::Errors::WrongReceiver, "afterSend set", "CacheOverride"); } if (!ensure_override(cx, self, "afterSend")) return false; if (val.isUndefined()) { JS::SetReservedSlot(self, Slots::AfterSend, JS::UndefinedValue()); rval.setUndefined(); return true; } else if (!val.isObject() || !JS::IsCallable(&val.toObject())) { JS_ReportErrorUTF8(cx, "CacheOverride: afterSend must be a function"); return false; } else { set_afterSend(self, &val.toObject()); } rval.setObject(*afterSend(self)); return true; } template bool CacheOverride::accessor_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) return accessor_fn(cx, self, args.rval()); } template bool CacheOverride::accessor_set(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) return accessor_fn(cx, self, args[0], args.rval()); } const JSFunctionSpec CacheOverride::static_methods[] = {JS_FS_END}; const JSPropertySpec CacheOverride::static_properties[] = {JS_PS_END}; const JSFunctionSpec CacheOverride::methods[] = {JS_FS_END}; const JSPropertySpec CacheOverride::properties[] = { JS_PSGS("mode", accessor_get, accessor_set, JSPROP_ENUMERATE), JS_PSGS("ttl", accessor_get, accessor_set, JSPROP_ENUMERATE), JS_PSGS("swr", accessor_get, accessor_set, JSPROP_ENUMERATE), JS_PSGS("surrogateKey", accessor_get, accessor_set, JSPROP_ENUMERATE), JS_PSGS("pci", accessor_get, accessor_set, JSPROP_ENUMERATE), JS_PSGS("beforeSend", accessor_get, accessor_set, JSPROP_ENUMERATE), JS_PSGS("afterSend", accessor_get, accessor_set, JSPROP_ENUMERATE), JS_STRING_SYM_PS(toStringTag, "CacheOverride", JSPROP_READONLY), JS_PS_END}; JSObject *CacheOverride::create(JSContext *cx, JS::HandleValue override) { JS::RootedObject self(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); JS::RootedValue val(cx); if (override.isString()) { CacheOverrideMode mode; if (!parse_mode(cx, override, &mode)) { return nullptr; } set_mode(self, mode); return self; } else if (!override.isObject()) { JS_ReportErrorUTF8(cx, "CacheOverride must be created from a string mode or override object"); return nullptr; } JS::RootedObject override_obj(cx, &override.toObject()); set_mode(self, CacheOverrideMode::Override); if (!JS_GetProperty(cx, override_obj, "ttl", &val) || !ttl_set(cx, self, val, &val)) { return nullptr; } if (!JS_GetProperty(cx, override_obj, "swr", &val) || !swr_set(cx, self, val, &val)) { return nullptr; } if (!JS_GetProperty(cx, override_obj, "surrogateKey", &val) || !surrogate_key_set(cx, self, val, &val)) { return nullptr; } if (!JS_GetProperty(cx, override_obj, "pci", &val) || !pci_set(cx, self, val, &val)) { return nullptr; } if (!JS_GetProperty(cx, override_obj, "beforeSend", &val) || !before_send_set(cx, self, val, &val)) { return nullptr; } if (!JS_GetProperty(cx, override_obj, "afterSend", &val) || !after_send_set(cx, self, val, &val)) { return nullptr; } return self; } bool CacheOverride::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { CTOR_HEADER("CacheOverride", 1); JS::RootedValue init(cx); CacheOverrideMode mode; if (args[0].isObject()) { init.setObject(args[0].toObject()); mode = CacheOverrideMode::Override; } else { if (!parse_mode(cx, args[0], &mode)) { return false; } if (args.length() > 1) { init.set(args[1]); } } if (mode == CacheOverride::CacheOverrideMode::Override) { if (!init.isObject()) { JS_ReportErrorUTF8(cx, "Creating a CacheOverride object with mode \"override\" requires " "an init object for the override parameters as the second argument"); return false; } JSObject *cache_override = create(cx, init); if (!cache_override) { return false; } args.rval().setObject(*cache_override); return true; } JS::RootedObject cache_override(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!cache_override) { return false; } set_mode(cache_override, mode); args.rval().setObject(*cache_override); return true; } /** * Clone a CacheOverride instance by copying all its reserved slots. * * This works because CacheOverride slots only contain primitive values. */ JSObject *CacheOverride::clone(JSContext *cx, JS::HandleObject self) { MOZ_ASSERT(is_instance(self)); JS::RootedObject result(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!result) { return nullptr; } for (size_t i = 0; i < Slots::Count; i++) { JS::Value val = JS::GetReservedSlot(self, i); JS::SetReservedSlot(result, i, val); } return result; } bool install(api::Engine *engine) { if (!CacheOverride::init_class_impl(engine->cx(), engine->global())) { return false; } RootedObject cache_override(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue cache_override_class(engine->cx()); if (!JS_GetProperty(engine->cx(), engine->global(), "CacheOverride", &cache_override_class)) { return false; } if (!JS_SetProperty(engine->cx(), cache_override, "CacheOverride", cache_override_class)) { return false; } RootedValue cache_override_val(engine->cx(), JS::ObjectValue(*cache_override)); if (!engine->define_builtin_module("fastly:cache-override", cache_override_val)) { return false; } return true; } } // namespace fastly::cache_override ================================================ FILE: runtime/fastly/builtins/cache-override.h ================================================ #ifndef FASTLY_CACHE_OVERRIDE_H #define FASTLY_CACHE_OVERRIDE_H #include "../host-api/host_api_fastly.h" #include "builtin.h" namespace fastly::cache_override { class CacheOverride : public builtins::BuiltinImpl { private: public: static constexpr const char *class_name = "CacheOverride"; static const int ctor_length = 1; // The values stored in these slots are ultimately passed to the host // via the fastly_req_cache_override_v2_set hostcall. // // If `Mode` is not `Override`, all other values are ignored. // // If `Mode` is `Override`, the values are interpreted in the following way: // // If `TTL`, `SWR`, or `SurrogateKey` are `undefined`, they're ignored. // For each of them, if the value isn't `undefined`, a flag gets set in the // hostcall's `tag` parameter, and the value itself is encoded as a uint32 // parameter. // // `PCI` is interpreted as a boolean, and a flag gets set in the hostcall's // `tag` parameter if `PCI` is true. // // `BeforeSend` and `AfterSend` are function callbacks that can be set // to execute before and after sending the request. enum Slots { Mode, TTL, SWR, SurrogateKey, PCI, BeforeSend, AfterSend, Count }; enum class CacheOverrideMode { None, Pass, Override }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static host_api::CacheOverrideTag abi_tag(JSObject *self); static JS::Value ttl(JSObject *self); static void set_ttl(JSObject *self, uint32_t ttl); static JS::Value swr(JSObject *self); static void set_swr(JSObject *self, uint32_t swr); static JS::Value surrogate_key(JSObject *self); static void set_surrogate_key(JSObject *self, JSString *key); static JSObject *clone(JSContext *cx, JS::HandleObject self); static JS::Value pci(JSObject *self); static void set_pci(JSObject *self, bool pci); static JSObject *beforeSend(JSObject *self); static void set_beforeSend(JSObject *self, JSObject *fn); static JSObject *afterSend(JSObject *self); static void set_afterSend(JSObject *self, JSObject *fn); static CacheOverrideMode mode(JSObject *self); static void set_mode(JSObject *self, CacheOverride::CacheOverrideMode mode); static bool mode_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval); static bool mode_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval); static bool ttl_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval); static bool ttl_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval); static bool swr_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval); static bool swr_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval); static bool surrogate_key_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval); static bool surrogate_key_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval); static bool pci_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval); static bool pci_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval); static bool before_send_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval); static bool before_send_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval); static bool after_send_get(JSContext *cx, JS::HandleObject self, JS::MutableHandleValue rval); static bool after_send_set(JSContext *cx, JS::HandleObject self, JS::HandleValue val, JS::MutableHandleValue rval); template static bool accessor_get(JSContext *cx, unsigned argc, JS::Value *vp); template static bool accessor_set(JSContext *cx, unsigned argc, JS::Value *vp); static bool ensure_override(JSContext *cx, JS::HandleObject self, const char *field); static JSObject *create(JSContext *cx, JS::HandleValue override); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); }; } // namespace fastly::cache_override #endif ================================================ FILE: runtime/fastly/builtins/cache-simple.cpp ================================================ #include "cache-simple.h" #include "../../StarlingMonkey/builtins/web/streams/native-stream-source.h" #include "../../StarlingMonkey/builtins/web/url.h" #include "../../StarlingMonkey/runtime/encode.h" #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "fastly.h" #include "js/ArrayBuffer.h" #include "js/Result.h" #include "js/Stream.h" #include "openssl/evp.h" #include using builtins::BuiltinNoConstructor; using builtins::web::streams::NativeStreamSource; using fastly::FastlyGetErrorMessage; using fastly::fastly::convertBodyInit; using fastly::fetch::RequestOrResponse; namespace { api::Engine *GLOBAL_ENGINE; } namespace fastly::cache_simple { template bool SimpleCacheEntry::bodyAll(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); return RequestOrResponse::bodyAll(cx, args, self); } bool SimpleCacheEntry::body_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); if (!JS::GetReservedSlot(self, static_cast(Slots::HasBody)).isBoolean()) { JS::SetReservedSlot(self, static_cast(Slots::HasBody), JS::BooleanValue(false)); } return RequestOrResponse::body_get(cx, args, self, true); } bool SimpleCacheEntry::bodyUsed_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); if (!JS::GetReservedSlot(self, static_cast(Slots::BodyUsed)).isBoolean()) { JS::SetReservedSlot(self, static_cast(Slots::BodyUsed), JS::BooleanValue(false)); } args.rval().setBoolean(RequestOrResponse::body_used(self)); return true; } const JSFunctionSpec SimpleCacheEntry::static_methods[] = { JS_FS_END, }; const JSPropertySpec SimpleCacheEntry::static_properties[] = { JS_PS_END, }; const JSFunctionSpec SimpleCacheEntry::methods[] = { JS_FN("arrayBuffer", bodyAll, 0, JSPROP_ENUMERATE), JS_FN("json", bodyAll, 0, JSPROP_ENUMERATE), JS_FN("text", bodyAll, 0, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec SimpleCacheEntry::properties[] = { JS_PSG("body", body_get, JSPROP_ENUMERATE), JS_PSG("bodyUsed", bodyUsed_get, JSPROP_ENUMERATE), JS_STRING_SYM_PS(toStringTag, "SimpleCacheEntry", JSPROP_READONLY), JS_PS_END, }; JSObject *SimpleCacheEntry::create(JSContext *cx, host_api::HttpBody body_handle) { JS::RootedObject SimpleCacheEntry(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!SimpleCacheEntry) return nullptr; JS::SetReservedSlot(SimpleCacheEntry, static_cast(Slots::Body), JS::Int32Value(body_handle.handle)); JS::SetReservedSlot(SimpleCacheEntry, static_cast(Slots::BodyStream), JS::NullValue()); JS::SetReservedSlot(SimpleCacheEntry, static_cast(Slots::HasBody), JS::BooleanValue(true)); JS::SetReservedSlot(SimpleCacheEntry, static_cast(Slots::BodyUsed), JS::FalseValue()); return SimpleCacheEntry; } namespace { // Purging/Deleting a cache item within the Compute SDKs via a hostcall is only // possible via surrogate-keys. We add a surrogate key to all the cache entries, // which is the sha-256 digest of the cache entries cache-key, converted to // uppercase hexadecimal. // Note: We should keep this consistent across the Compute SDKs, this would allow // a Compute Service to move from one SDK to another, and have consistent purging // behavior between the Compute Service Versions which were using a different SDK. JS::Result createGlobalSurrogateKeyFromCacheKey(JSContext *cx, std::string_view cache_key) { const EVP_MD *algorithm = EVP_sha256(); unsigned int size = EVP_MD_size(algorithm); std::vector md(size); if (!EVP_Digest(cache_key.data(), cache_key.size(), md.data(), &size, algorithm, nullptr)) { return JS::Result(JS::Error()); } JS::UniqueChars data{OPENSSL_buf2hexstr(md.data(), size)}; std::string surrogate_key{data.get(), std::remove(data.get(), data.get() + size, ':')}; return JS::Result(surrogate_key); } // Purging/Deleting a cache item within the Compute SDKs via a hostcall is only // possible via surrogate-keys. We add a surrogate key to all the cache entries, // which is the sha-256 digest of the cache entries cache-key and the FASTLY_POP // environment variable, converted to uppercase hexadecimal. // Note: We should keep this consistent across the Compute SDKs, this would allow // a Compute Service to move from one SDK to another, and have consistent purging // behavior between the Compute Service Versions which were using a different SDK. JS::Result createPopSurrogateKeyFromCacheKey(JSContext *cx, std::string_view cache_key) { const EVP_MD *algorithm = EVP_sha256(); unsigned int size = EVP_MD_size(algorithm); std::vector md(size); std::string key{cache_key}; auto pop = getenv("FASTLY_POP"); if (pop) { key += pop; } // TODO: use the incremental Digest api instead of allocating a string if (!EVP_Digest(key.c_str(), key.length(), md.data(), &size, algorithm, nullptr)) { return JS::Result(JS::Error()); } JS::UniqueChars data{OPENSSL_buf2hexstr(md.data(), size)}; std::string surrogate_key{data.get(), std::remove(data.get(), data.get() + size, ':')}; return JS::Result(surrogate_key); } // Create all the surrogate keys for the cache key JS::Result createSurrogateKeysFromCacheKey(JSContext *cx, std::string_view cache_key) { const EVP_MD *algorithm = EVP_sha256(); unsigned int size = EVP_MD_size(algorithm); std::vector md(size); if (!EVP_Digest(cache_key.data(), cache_key.size(), md.data(), &size, algorithm, nullptr)) { return JS::Result(JS::Error()); } JS::UniqueChars data{OPENSSL_buf2hexstr(md.data(), size)}; std::string surrogate_keys{data.get(), std::remove(data.get(), data.get() + size, ':')}; if (auto *pop = getenv("FASTLY_POP")) { // TODO: use the incremental Digest api instead of allocating a string std::string key{cache_key}; key += pop; if (!EVP_Digest(key.c_str(), key.length(), md.data(), &size, algorithm, nullptr)) { return JS::Result(JS::Error()); } JS::UniqueChars data{OPENSSL_buf2hexstr(md.data(), size)}; surrogate_keys.push_back(' '); surrogate_keys.append(data.get(), std::remove(data.get(), data.get() + size, ':')); } return JS::Result(surrogate_keys); } #define BEGIN_TRANSACTION(t, cx, promise, handle) \ CacheTransaction t{cx, promise, handle, __func__, __LINE__}; class CacheTransaction final { JSContext *cx; JS::RootedObject promise; host_api::CacheHandle handle; const char *func; int line; public: CacheTransaction(JSContext *cx, JS::HandleObject promise, host_api::CacheHandle handle, const char *func, const int line) : cx{cx}, promise{this->cx, promise}, handle{handle}, func{func}, line{line} {}; ~CacheTransaction() { // An invalid handle indicates that this transaction has been committed. if (!this->handle.is_valid()) { return; } auto res = this->handle.transaction_cancel(); if (auto *err = res.to_err()) { host_api::handle_api_error(this->cx, *err, this->line, this->func); } // We always reject the promise if the transaction hasn't committed. RejectPromiseWithPendingError(this->cx, this->promise); } /// Commit this transaction. void commit() { // Invalidate the handle to indicate that the transaction has been committed. MOZ_ASSERT(this->handle.is_valid()); this->handle = host_api::CacheHandle{}; MOZ_ASSERT(!this->handle.is_valid()); } }; bool get_or_set_then_handler(JSContext *cx, JS::HandleObject lookup_state, JS::HandleValue extra, JS::CallArgs args) { JS::RootedValue handle_val(cx); JS::RootedValue promise_val(cx); if (!JS_GetProperty(cx, lookup_state, "promise", &promise_val)) { return false; } MOZ_ASSERT(promise_val.isObject()); JS::RootedObject promise(cx, &promise_val.toObject()); if (!promise) { return ReturnPromiseRejectedWithPendingError(cx, args); } if (!JS_GetProperty(cx, lookup_state, "handle", &handle_val)) { return RejectPromiseWithPendingError(cx, promise); } MOZ_ASSERT(handle_val.isInt32()); host_api::CacheHandle handle(handle_val.toInt32()); BEGIN_TRANSACTION(transaction, cx, promise, handle); JS::RootedValue keyVal(cx); if (!JS_GetProperty(cx, lookup_state, "key", &keyVal)) { return false; } auto arg0 = args.get(0); if (!arg0.isObject()) { JS_ReportErrorASCII(cx, "SimpleCache.getOrSet: does not adhere to interface {value: BodyInit, " "ttl: number, length?:number}"); return false; } JS::RootedObject insertionObject(cx, &arg0.toObject()); JS::RootedValue ttl_val(cx); if (!JS_GetProperty(cx, insertionObject, "ttl", &ttl_val)) { return false; } // Convert ttl (time-to-live) field into a number and check the value adheres to our // validation rules. double ttl; if (!JS::ToNumber(cx, ttl_val, &ttl)) { return false; } if (ttl < 0 || std::isnan(ttl) || std::isinf(ttl)) { JS_ReportErrorASCII( cx, "SimpleCache.getOrSet: TTL field is an invalid value, only positive numbers can " "be used for TTL values."); return false; } host_api::CacheWriteOptions options; // turn second representation into nanosecond representation options.max_age_ns = JS::ToUint64(ttl) * 1'000'000'000; JS::RootedValue body_val(cx); if (!JS_GetProperty(cx, insertionObject, "value", &body_val)) { return false; } host_api::HttpBody source_body; JS::UniqueChars buf; JS::RootedObject body_obj(cx, body_val.isObject() ? &body_val.toObject() : nullptr); // If the body is a Host-backed ReadableStream we optimise our implementation // by using the ReadableStream's handle directly. if (body_obj && JS::IsReadableStream(body_obj)) { if (RequestOrResponse::body_unusable(cx, body_obj)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_READABLE_STREAM_LOCKED_OR_DISTRUBED); return false; } // If the stream is backed by a Fastly Compute body handle, we can use that handle directly. if (NativeStreamSource::stream_is_body(cx, body_obj)) { JS::RootedObject stream_source(cx, NativeStreamSource::get_stream_source(cx, body_obj)); JS::RootedObject source_owner(cx, NativeStreamSource::owner(stream_source)); source_body = RequestOrResponse::body_handle(source_owner); } else { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_SIMPLE_CACHE_SET_CONTENT_STREAM); return false; } // The cache APIs require the length to be known upfront, we don't know the length of a // stream upfront, which means the caller will need to supply the information explicitly for us. bool found; if (!JS_HasProperty(cx, insertionObject, "length", &found)) { return false; } if (found) { JS::RootedValue length_val(cx); if (!JS_GetProperty(cx, insertionObject, "length", &length_val)) { return false; } double number; if (!JS::ToNumber(cx, length_val, &number)) { return false; } if (number < 0 || std::isnan(number) || std::isinf(number)) { JS_ReportErrorASCII( cx, "SimpleCache.getOrSet: length property is an invalid value, only positive numbers can " "be used for length values."); return false; } options.length = JS::ToInteger(number); } } else { auto result = convertBodyInit(cx, body_val); if (result.isErr()) { return false; } std::tie(buf, options.length) = result.unwrap(); } // We create a surrogate-key from the cache-key, as this allows the cached contents to be purgable // from within the JavaScript application // This is because the cache API currently only supports purging via surrogate-key auto key_chars = core::encode(cx, keyVal); if (!key_chars) { return false; } auto key_result = createSurrogateKeysFromCacheKey(cx, key_chars); if (key_result.isErr()) { return false; } options.surrogate_keys = key_result.inspect(); auto inserted_res = handle.transaction_insert_and_stream_back(options); if (auto *err = inserted_res.to_err()) { return false; } auto [body, inserted_handle] = inserted_res.unwrap(); if (!body.valid()) { return false; } // source_body will only be valid when the body is a Host-backed ReadableStream if (source_body.valid()) { auto res = body.append(source_body); if (auto *error = res.to_err()) { return false; } } else { auto write_res = body.write_all_back(reinterpret_cast(buf.get()), options.length); if (auto *error = write_res.to_err()) { return false; } auto close_res = body.close(); if (auto *error = close_res.to_err()) { return false; } } auto res = inserted_handle.get_body(host_api::CacheGetBodyOptions{}); if (auto *err = res.to_err()) { return false; } JS::RootedObject entry(cx, SimpleCacheEntry::create(cx, res.unwrap())); if (!entry) { return false; } transaction.commit(); JS::RootedValue result(cx); result.setObject(*entry); JS::ResolvePromise(cx, promise, result); return true; } bool get_or_set_catch_handler(JSContext *cx, JS::HandleObject lookup_state, JS::HandleValue inner_promise_val, JS::CallArgs args) { JS::RootedValue promise_val(cx); if (!JS_GetProperty(cx, lookup_state, "promise", &promise_val)) { return false; } MOZ_ASSERT(promise_val.isObject()); JS::RootedObject promise(cx, &promise_val.toObject()); if (!promise) { return ReturnPromiseRejectedWithPendingError(cx, args); } JS::RootedObject inner_promise(cx, &inner_promise_val.toObject()); if (!inner_promise) { return ReturnPromiseRejectedWithPendingError(cx, args); } MOZ_ASSERT(JS::GetPromiseState(inner_promise) == JS::PromiseState::Rejected); JS::RootedValue promise_rejection_err(cx, JS::GetPromiseResult(inner_promise)); JS::RejectPromise(cx, promise, promise_rejection_err); return true; } bool process_pending_cache_lookup(JSContext *cx, host_api::CacheHandle::Handle handle, JS::HandleObject context_obj, JS::HandleValue) { host_api::CacheHandle pending_lookup(handle); JS::RootedValue key_val(cx); if (!JS_GetProperty(cx, context_obj, "key", &key_val)) { return false; } auto key_chars = core::encode(cx, key_val); JS::RootedValue set_function_val(cx); if (!JS_GetProperty(cx, context_obj, "set_function", &set_function_val)) { return false; } JS::RootedValue promise_val(cx); if (!JS_GetProperty(cx, context_obj, "promise", &promise_val)) { return false; } JS::RootedObject promise_obj(cx, &promise_val.toObject()); BEGIN_TRANSACTION(transaction, cx, promise_obj, pending_lookup); // Check if a fresh cache item was found, if that's the case, then we will resolve // with a SimpleCacheEntry containing the value. Else, call the content-provided // function in the `set` parameter and insert it's returned value property into the // cache under the provided `key`, and then we will resolve with a SimpleCacheEntry // containing the value. auto state_res = pending_lookup.get_state(); if (auto *err = state_res.to_err()) { return false; } auto state = state_res.unwrap(); if (state.is_usable()) { auto body_res = pending_lookup.get_body(host_api::CacheGetBodyOptions{}); if (auto *err = body_res.to_err()) { return false; } JS::RootedObject entry(cx, SimpleCacheEntry::create(cx, body_res.unwrap())); if (!entry) { return false; } JS::RootedValue result(cx); result.setObject(*entry); JS::ResolvePromise(cx, promise_obj, result); return true; } else { if (!set_function_val.isObject() || !JS::IsCallable(&set_function_val.toObject())) { JS_ReportErrorLatin1(cx, "SimpleCache.getOrSet: set argument is not a function"); return false; } JS::RootedValueArray<0> fnargs(cx); JS::RootedObject fn(cx, &set_function_val.toObject()); JS::RootedValue result(cx); if (!JS::Call(cx, JS::NullHandleValue, fn, fnargs, &result)) { return false; } // Coercion of `result` to a Promise JS::RootedObject result_promise(cx, JS::CallOriginalPromiseResolve(cx, result)); if (!result_promise) { return false; } // JS::RootedObject owner(cx, JS_NewPlainObject(cx)); JS::RootedObject lookup_state(cx, JS_NewPlainObject(cx)); JS::RootedValue handle_val(cx, JS::NumberValue(handle)); if (!JS_SetProperty(cx, lookup_state, "handle", handle_val)) { return false; } JS::RootedString key_str(cx, JS_NewStringCopyN(cx, key_chars.begin(), key_chars.len)); JS::RootedValue keyVal(cx, JS::StringValue(key_str)); if (!JS_SetProperty(cx, lookup_state, "key", keyVal)) { return false; } JS::RootedValue promise_val(cx, JS::ObjectValue(*promise_obj)); if (!JS_SetProperty(cx, lookup_state, "promise", promise_val)) { return false; } JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx)); JS::RootedObject then_handler( cx, create_internal_method(cx, lookup_state)); if (!then_handler) { return false; } JS::RootedValue result_promise_val(cx, JS::ObjectValue(*result_promise)); JS::RootedObject catch_handler( cx, create_internal_method(cx, lookup_state, result_promise_val)); if (!then_handler) { return false; } if (!JS::AddPromiseReactions(cx, result_promise, then_handler, catch_handler)) { return false; } transaction.commit(); return true; } } } // namespace // static getOrSet(key: string, set: () => Promise<{value: BodyInit, ttl: number}>): // SimpleCacheEntry | null; static getOrSet(key: string, set: () => Promise<{value: ReadableStream, // ttl: number, length: number}>): SimpleCacheEntry | null; bool SimpleCache::getOrSet(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The SimpleCache builtin"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "SimpleCache.getOrSet", 2)) { return false; } // Convert key parameter into a string and check the value adheres to our validation rules. auto key_chars = core::encode(cx, args.get(0)); if (!key_chars) { return false; } if (key_chars.len == 0) { JS_ReportErrorASCII(cx, "SimpleCache.getOrSet: key can not be an empty string"); return false; } if (key_chars.len > 8135) { JS_ReportErrorASCII( cx, "SimpleCache.getOrSet: key is too long, the maximum allowed length is 8135."); return false; } JS::RootedObject promise(cx, JS::NewPromiseObject(cx, nullptr)); if (!promise) { return ReturnPromiseRejectedWithPendingError(cx, args); } auto res = host_api::CacheHandle::transaction_lookup(key_chars, host_api::CacheLookupOptions{}); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } // The async task requires some extra state: the key, the `set` function, and the promise. // We wrap this all up into one object, so `process_pending_cache_lookup` can retrieve everything. // This could be avoided with some changes to `FastlyAsyncTask`, see // (https://github.com/fastly/js-compute-runtime/issues/1245) JS::RootedObject context_obj(cx, JS_NewPlainObject(cx)); if (!context_obj) { return false; } JS::RootedValue key_val(cx, args.get(0)); if (!JS_SetProperty(cx, context_obj, "key", key_val)) { return false; } JS::RootedValue set_func_val(cx, args.get(1)); if (!JS_SetProperty(cx, context_obj, "set_function", set_func_val)) { return false; } JS::RootedValue promise_val(cx, JS::ObjectValue(*promise)); if (!JS_SetProperty(cx, context_obj, "promise", promise_val)) { return false; } auto handle = res.unwrap(); GLOBAL_ENGINE->queue_async_task(new FastlyAsyncTask( handle.handle, context_obj, JS::UndefinedHandleValue, process_pending_cache_lookup)); args.rval().setObject(*promise); return true; } // static set(key: string, value: BodyInit, ttl: number): undefined; // static set(key: string, value: ReadableStream, ttl: number, length: number): undefined; bool SimpleCache::set(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The SimpleCache builtin"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "SimpleCache.set", 3)) { return false; } // Convert key parameter into a string and check the value adheres to our validation rules. auto key = core::encode(cx, args.get(0)); if (!key) { return false; } if (key.len == 0) { JS_ReportErrorASCII(cx, "SimpleCache.set: key can not be an empty string"); return false; } if (key.len > 8135) { JS_ReportErrorASCII(cx, "SimpleCache.set: key is too long, the maximum allowed length is 8135."); return false; } host_api::CacheWriteOptions options; // Convert ttl (time-to-live) parameter into a number and check the value adheres to our // validation rules. JS::HandleValue ttl_val = args.get(2); double ttl; if (!JS::ToNumber(cx, ttl_val, &ttl)) { return false; } if (ttl < 0 || std::isnan(ttl) || std::isinf(ttl)) { JS_ReportErrorASCII( cx, "SimpleCache.set: TTL parameter is an invalid value, only positive numbers can " "be used for TTL values."); return false; } options.max_age_ns = JS::ToUint64(ttl) * 1'000'000'000; // turn second representation into nanosecond representation JS::HandleValue body_val = args.get(1); host_api::HttpBody source_body; JS::UniqueChars buf; JS::RootedObject body_obj(cx, body_val.isObject() ? &body_val.toObject() : nullptr); // If the body parameter is a Host-backed ReadableStream we optimise our implementation // by using the ReadableStream's handle directly. if (body_obj && JS::IsReadableStream(body_obj)) { if (RequestOrResponse::body_unusable(cx, body_obj)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_READABLE_STREAM_LOCKED_OR_DISTRUBED); return false; } // If the stream is backed by a Fastly Compute body handle, we can use that handle directly. if (NativeStreamSource::stream_is_body(cx, body_obj)) { JS::RootedObject stream_source(cx, NativeStreamSource::get_stream_source(cx, body_obj)); JS::RootedObject source_owner(cx, NativeStreamSource::owner(stream_source)); source_body = RequestOrResponse::body_handle(source_owner); } else { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_SIMPLE_CACHE_SET_CONTENT_STREAM); return false; } if (args.hasDefined(3)) { JS::HandleValue length_val = args.get(3); double number; if (!JS::ToNumber(cx, length_val, &number)) { return false; } if (number < 0 || std::isnan(number) || std::isinf(number)) { JS_ReportErrorASCII( cx, "SimpleCache.set: length parameter is an invalid value, only positive numbers can " "be used for length values."); return false; } options.length = JS::ToInteger(number); } } else { auto result = convertBodyInit(cx, body_val); if (result.isErr()) { return false; } std::tie(buf, options.length) = result.unwrap(); } // We create a surrogate-key from the cache-key, as this allows the cached contents to be purgable // from within the JavaScript application // This is because the cache API currently only supports purging via surrogate-key auto key_result = createSurrogateKeysFromCacheKey(cx, key); if (key_result.isErr()) { return false; } options.surrogate_keys = key_result.inspect(); auto insert_res = host_api::CacheHandle::insert(key, options); if (auto *err = insert_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body = insert_res.unwrap(); if (!body.valid()) { return false; } // source_body will only be valid when the body parameter is a Host-backed ReadableStream if (source_body.valid()) { auto res = body.append(source_body); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } else { auto write_res = body.write_all_back(reinterpret_cast(buf.get()), options.length); if (auto *err = write_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } } auto close_res = body.close(); if (auto *err = close_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } // static get(key: string): SimpleCacheEntry | null; bool SimpleCache::get(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The SimpleCache builtin"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "SimpleCache.get", 1)) { return false; } // Convert key parameter into a string and check the value adheres to our validation rules. auto key = core::encode(cx, args[0]); if (!key) { return false; } if (key.len == 0) { JS_ReportErrorASCII(cx, "SimpleCache.get: key can not be an empty string"); return false; } if (key.len > 8135) { JS_ReportErrorASCII(cx, "SimpleCache.get: key is too long, the maximum allowed length is 8135."); return false; } auto lookup_res = host_api::CacheHandle::lookup(key, host_api::CacheLookupOptions{}); if (auto *err = lookup_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto handle = lookup_res.unwrap(); auto body_res = handle.get_body(host_api::CacheGetBodyOptions{}); if (auto *err = body_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body = body_res.unwrap(); if (!body.valid()) { args.rval().setNull(); } else { JS::RootedObject entry(cx, SimpleCacheEntry::create(cx, body)); if (!entry) { return false; } args.rval().setObject(*entry); } return true; } // static purge(key: string, options: PurgeOptions): undefined; bool SimpleCache::purge(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The SimpleCache builtin"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "SimpleCache.purge", 2)) { return false; } // Convert key parameter into a string and check the value adheres to our validation rules. auto key_chars = core::encode(cx, args.get(0)); if (!key_chars) { return false; } if (key_chars.len == 0) { JS_ReportErrorASCII(cx, "SimpleCache.purge: key can not be an empty string"); return false; } if (key_chars.len > 8135) { JS_ReportErrorASCII(cx, "SimpleCache.purge: key is too long, the maximum allowed length is 8135."); return false; } auto secondArgument = args.get(1); if (!secondArgument.isObject()) { JS_ReportErrorASCII(cx, "SimpleCache.purge: options parameter is not an object."); return false; } JS::RootedObject options(cx, &secondArgument.toObject()); JS::RootedValue scope_val(cx); if (!JS_GetProperty(cx, options, "scope", &scope_val)) { return false; } auto scope_chars = core::encode(cx, scope_val); if (!scope_chars) { return false; } std::string_view scope = scope_chars; std::string surrogate_key; if (scope == "pop") { auto surrogate_key_result = createPopSurrogateKeyFromCacheKey(cx, key_chars); if (surrogate_key_result.isErr()) { return false; } surrogate_key = surrogate_key_result.unwrap(); } else if (scope == "global") { auto surrogate_key_result = createGlobalSurrogateKeyFromCacheKey(cx, key_chars); if (surrogate_key_result.isErr()) { return false; } surrogate_key = surrogate_key_result.unwrap(); } else { JS_ReportErrorASCII( cx, "SimpleCache.purge: scope field of options parameter must be either 'pop', or 'global'."); return false; } auto purge_res = host_api::Compute::purge_surrogate_key(surrogate_key, false); if (auto *err = purge_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } MOZ_ASSERT(!purge_res.unwrap().has_value()); args.rval().setUndefined(); return true; } const JSFunctionSpec SimpleCache::static_methods[] = { JS_FN("purge", purge, 2, JSPROP_ENUMERATE), JS_FN("get", get, 1, JSPROP_ENUMERATE), JS_FN("getOrSet", getOrSet, 2, JSPROP_ENUMERATE), JS_FN("set", set, 3, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec SimpleCache::static_properties[] = { JS_PS_END, }; const JSFunctionSpec SimpleCache::methods[] = {JS_FS_END}; const JSPropertySpec SimpleCache::properties[] = { JS_STRING_SYM_PS(toStringTag, "SimpleCache", JSPROP_READONLY), JS_PS_END}; bool install(api::Engine *engine) { GLOBAL_ENGINE = engine; if (!SimpleCacheEntry::init_class_impl(engine->cx(), engine->global())) { return false; } if (!SimpleCache::init_class_impl(engine->cx(), engine->global())) { return false; } return true; } } // namespace fastly::cache_simple ================================================ FILE: runtime/fastly/builtins/cache-simple.h ================================================ #ifndef FASTLY_CACHE_SIMPLE_H #define FASTLY_CACHE_SIMPLE_H #include "../host-api/host_api_fastly.h" #include "./fetch/request-response.h" #include "builtin.h" namespace fastly::cache_simple { class SimpleCacheEntry final : public builtins::BuiltinNoConstructor { template static bool bodyAll(JSContext *cx, unsigned argc, JS::Value *vp); static bool body_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool bodyUsed_get(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "SimpleCacheEntry"; using Slots = fetch::RequestOrResponse::Slots; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static const unsigned ctor_length = 0; static JSObject *create(JSContext *cx, host_api::HttpBody body_handle); }; class SimpleCache : public builtins::BuiltinNoConstructor { private: public: static constexpr const char *class_name = "SimpleCache"; static const int ctor_length = 0; enum Slots { Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool delete_(JSContext *cx, unsigned argc, JS::Value *vp); static bool get(JSContext *cx, unsigned argc, JS::Value *vp); static bool purge(JSContext *cx, unsigned argc, JS::Value *vp); static bool set(JSContext *cx, unsigned argc, JS::Value *vp); static bool getOrSet(JSContext *cx, unsigned argc, JS::Value *vp); }; } // namespace fastly::cache_simple #endif ================================================ FILE: runtime/fastly/builtins/config-store.cpp ================================================ #include "config-store.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../host-api/host_api_fastly.h" #include "fastly.h" using builtins::BuiltinImpl; using fastly::FastlyGetErrorMessage; namespace fastly::config_store { host_api::ConfigStore ConfigStore::config_store_handle(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, ConfigStore::Slots::Handle); return host_api::ConfigStore(val.toInt32()); } bool ConfigStore::get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) auto key = core::encode(cx, args[0]); // If the converted string has a length of 0 then we throw an Error // because config-store keys have to be at-least 1 character. if (!key || key.len == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_CONFIG_STORE_KEY_EMPTY); return false; } // key has to be less than 256 if (key.len > 255) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_CONFIG_STORE_KEY_TOO_LONG); return false; } std::string_view key_str = key; // Ensure that we throw an exception for all unexpected host errors. auto get_res = ConfigStore::config_store_handle(self).get(key_str); if (auto *err = get_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } // None indicates the key wasn't found, so we return null. auto ret = std::move(get_res.unwrap()); if (!ret.has_value()) { args.rval().setNull(); return true; } JS::RootedString text(cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(ret->begin(), ret->size()))); if (!text) { return false; } args.rval().setString(text); return true; } const JSFunctionSpec ConfigStore::static_methods[] = { JS_FS_END, }; const JSPropertySpec ConfigStore::static_properties[] = { JS_PS_END, }; const JSFunctionSpec ConfigStore::methods[] = {JS_FN("get", get, 1, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec ConfigStore::properties[] = {JS_PS_END}; bool ConfigStore::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The ConfigStore builtin"); CTOR_HEADER("ConfigStore", 1); auto name = core::encode(cx, args[0]); // If the converted string has a length of 0 then we throw an Error // because config-store names have to be at-least 1 character. if (!name) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_CONFIG_STORE_NAME_EMPTY); return false; } // If the converted string has a length of more than 255 then we throw an Error // because config-store names have to be less than 255 characters. if (name.size() > 255) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_CONFIG_STORE_NAME_TOO_LONG); return false; } // Name must start with ascii alphabetical and contain only ascii alphanumeric, underscore, and // whitespace if (!std::isalpha(*name.begin())) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_CONFIG_STORE_NAME_START_WITH_ASCII_ALPHA); return false; } auto is_valid_name = std::all_of(std::next(name.begin(), 1), name.end(), [&](auto character) { return std::isalnum(character) || character == '_' || character == ' '; }); if (!is_valid_name) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_CONFIG_STORE_NAME_CONTAINS_INVALID_CHARACTER); return false; } JS::RootedObject config_store(cx, JS_NewObjectForConstructor(cx, &class_, args)); auto open_res = host_api::ConfigStore::open(name); if (auto *err = open_res.to_err()) { if (host_api::error_is_bad_handle(*err)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_CONFIG_STORE_DOES_NOT_EXIST, name.begin()); return false; } else { HANDLE_ERROR(cx, *err); return false; } } JS::SetReservedSlot(config_store, ConfigStore::Slots::Handle, JS::Int32Value(open_res.unwrap().handle)); if (!config_store) return false; args.rval().setObject(*config_store); return true; } bool install(api::Engine *engine) { if (!ConfigStore::init_class_impl(engine->cx(), engine->global())) { return false; } RootedObject config_store_ns_obj(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue config_store_ns_val(engine->cx(), JS::ObjectValue(*config_store_ns_obj)); RootedObject config_store_obj(engine->cx(), JS_GetConstructor(engine->cx(), ConfigStore::proto_obj)); RootedValue config_store_val(engine->cx(), ObjectValue(*config_store_obj)); if (!JS_SetProperty(engine->cx(), config_store_ns_obj, "ConfigStore", config_store_val)) { return false; } if (!engine->define_builtin_module("fastly:config-store", config_store_ns_val)) { return false; } return true; } } // namespace fastly::config_store ================================================ FILE: runtime/fastly/builtins/config-store.h ================================================ #ifndef FASTLY_CONFIG_STORE_H #define FASTLY_CONFIG_STORE_H #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "extension-api.h" namespace fastly::config_store { class ConfigStore : public builtins::BuiltinImpl { private: public: static constexpr const char *class_name = "ConfigStore"; static const int ctor_length = 1; enum Slots { Handle, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool get(JSContext *cx, unsigned argc, JS::Value *vp); static host_api::ConfigStore config_store_handle(JSObject *obj); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); static bool init_class(JSContext *cx, JS::HandleObject global); }; } // namespace fastly::config_store #endif ================================================ FILE: runtime/fastly/builtins/device.cpp ================================================ #include "device.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "js/JSON.h" using builtins::BuiltinNoConstructor; namespace fastly::device { namespace { bool callbackCalled; bool write_json_to_buf(const char16_t *str, uint32_t strlen, void *out) { callbackCalled = true; auto outstr = static_cast(out); outstr->append(str, strlen); return true; } JSObject *deviceToJSON(JSContext *cx, JS::HandleObject self) { MOZ_ASSERT(Device::is_instance(self)); JS::RootedValue device_info( cx, JS::GetReservedSlot(self, static_cast(Device::Slots::DeviceInfo))); JS::RootedValue value(cx); if (!device_info.isObject()) { return nullptr; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedObject result(cx, JS_NewPlainObject(cx)); if (!JS_GetProperty(cx, device_info_obj, "name", &value)) { return nullptr; } MOZ_ASSERT(value.isString() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "name", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "brand", &value)) { return nullptr; } MOZ_ASSERT(value.isString() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "brand", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "model", &value)) { return nullptr; } MOZ_ASSERT(value.isString() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "model", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "hwtype", &value)) { return nullptr; } MOZ_ASSERT(value.isString() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "hardwareType", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "is_desktop", &value)) { return nullptr; } MOZ_ASSERT(value.isBoolean() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "isDesktop", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "is_gameconsole", &value)) { return nullptr; } MOZ_ASSERT(value.isBoolean() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "isGameConsole", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "is_mediaplayer", &value)) { return nullptr; } MOZ_ASSERT(value.isBoolean() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "isMediaPlayer", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "is_mobile", &value)) { return nullptr; } MOZ_ASSERT(value.isBoolean() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "isMobile", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "is_smarttv", &value)) { return nullptr; } MOZ_ASSERT(value.isBoolean() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "isSmartTV", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "is_tablet", &value)) { return nullptr; } MOZ_ASSERT(value.isBoolean() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "isTablet", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "is_touchscreen", &value)) { return nullptr; } MOZ_ASSERT(value.isBoolean() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "isTouchscreen", value)) { return nullptr; } if (!JS_GetProperty(cx, device_info_obj, "is_bot", &value)) { return nullptr; } MOZ_ASSERT(value.isBoolean() || value.isNullOrUndefined()); if (value.isUndefined()) { value.setNull(); } if (!JS_SetProperty(cx, result, "isBot", value)) { return nullptr; } return result; } } // namespace /* * This is used by our `Console` implementation and logs all the approproiate properties for a * Device instance */ JSString *Device::ToSource(JSContext *cx, JS::HandleObject self) { MOZ_ASSERT(Device::is_instance(self)); JS::RootedValue data(cx); data.setObjectOrNull(deviceToJSON(cx, self)); JS::RootedObject replacer(cx); JS::RootedValue space(cx); std::u16string out; // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. callbackCalled = false; if (!JS::ToJSON(cx, data, replacer, space, &write_json_to_buf, &out)) { return nullptr; } if (!callbackCalled) { JS_ReportErrorASCII(cx, "The data is not JSON serializable"); return nullptr; } return JS_NewUCStringCopyN(cx, out.c_str(), out.length()); } bool Device::toJSON(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().setObjectOrNull(deviceToJSON(cx, self)); return true; } // get name(): string | null; bool Device::device_name_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setNull(); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_name(cx); if (!JS_GetProperty(cx, device_info_obj, "name", &device_name)) { return false; } MOZ_ASSERT(device_name.isString() || device_name.isNullOrUndefined()); if (device_name.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_name); } return true; } // get brand(): string | null; bool Device::brand_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setNull(); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_brand(cx); if (!JS_GetProperty(cx, device_info_obj, "brand", &device_brand)) { return false; } MOZ_ASSERT(device_brand.isString() || device_brand.isNullOrUndefined()); if (device_brand.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_brand); } return true; } // get model(): string | null; bool Device::model_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setNull(); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_model(cx); if (!JS_GetProperty(cx, device_info_obj, "model", &device_model)) { return false; } MOZ_ASSERT(device_model.isString() || device_model.isNullOrUndefined()); if (device_model.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_model); } return true; } // get hardwareType(): string | null; bool Device::hardware_type_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setNull(); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_hwtype(cx); if (!JS_GetProperty(cx, device_info_obj, "hwtype", &device_hwtype)) { return false; } MOZ_ASSERT(device_hwtype.isString() || device_hwtype.isNullOrUndefined()); if (device_hwtype.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_hwtype); } return true; } // get isDesktop(): boolean | null; bool Device::is_desktop_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setBoolean(false); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_is_desktop(cx); if (!JS_GetProperty(cx, device_info_obj, "is_desktop", &device_is_desktop)) { return false; } MOZ_ASSERT(device_is_desktop.isBoolean() || device_is_desktop.isNullOrUndefined()); if (device_is_desktop.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_is_desktop); } return true; } // get isGameConsole(): boolean | null; bool Device::is_gameconsole_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setBoolean(false); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_is_gameconsole(cx); if (!JS_GetProperty(cx, device_info_obj, "is_gameconsole", &device_is_gameconsole)) { return false; } MOZ_ASSERT(device_is_gameconsole.isBoolean() || device_is_gameconsole.isNullOrUndefined()); if (device_is_gameconsole.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_is_gameconsole); } return true; } // get isMediaPlayer(): boolean | null; bool Device::is_mediaplayer_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setBoolean(false); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_is_mediaplayer(cx); if (!JS_GetProperty(cx, device_info_obj, "is_mediaplayer", &device_is_mediaplayer)) { return false; } MOZ_ASSERT(device_is_mediaplayer.isBoolean() || device_is_mediaplayer.isNullOrUndefined()); if (device_is_mediaplayer.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_is_mediaplayer); } return true; } // get isMobile(): boolean | null; bool Device::is_mobile_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setBoolean(false); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_is_mobile(cx); if (!JS_GetProperty(cx, device_info_obj, "is_mobile", &device_is_mobile)) { return false; } MOZ_ASSERT(device_is_mobile.isBoolean() || device_is_mobile.isNullOrUndefined()); if (device_is_mobile.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_is_mobile); } return true; } // get isSmartTV(): boolean | null; bool Device::is_smarttv_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setBoolean(false); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_is_smarttv(cx); if (!JS_GetProperty(cx, device_info_obj, "is_smarttv", &device_is_smarttv)) { return false; } MOZ_ASSERT(device_is_smarttv.isBoolean() || device_is_smarttv.isNullOrUndefined()); if (device_is_smarttv.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_is_smarttv); } return true; } // get isTablet(): boolean | null; bool Device::is_tablet_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setBoolean(false); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_is_tablet(cx); if (!JS_GetProperty(cx, device_info_obj, "is_tablet", &device_is_tablet)) { return false; } MOZ_ASSERT(device_is_tablet.isBoolean() || device_is_tablet.isNullOrUndefined()); if (device_is_tablet.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_is_tablet); } return true; } // get isTouchscreen(): boolean | null; bool Device::is_touchscreen_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setBoolean(false); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_is_touchscreen(cx); if (!JS_GetProperty(cx, device_info_obj, "is_touchscreen", &device_is_touchscreen)) { return false; } MOZ_ASSERT(device_is_touchscreen.isBoolean() || device_is_touchscreen.isNullOrUndefined()); if (device_is_touchscreen.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_is_touchscreen); } return true; } // get isBot(): boolean | null; bool Device::is_bot_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue device_info(cx, JS::GetReservedSlot(self, static_cast(Slots::DeviceInfo))); if (!device_info.isObject()) { args.rval().setBoolean(false); return true; } JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); JS::RootedValue device_is_bot(cx); if (!JS_GetProperty(cx, device_info_obj, "is_bot", &device_is_bot)) { return false; } MOZ_ASSERT(device_is_bot.isBoolean() || device_is_bot.isNullOrUndefined()); if (device_is_bot.isUndefined()) { args.rval().setNull(); } else { args.rval().set(device_is_bot); } return true; } // static lookup(useragent: string): Device; bool Device::lookup(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The Device builtin"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "Device.lookup", 1)) { return false; } // Convert key parameter into a string and check the value adheres to our validation rules. auto key = core::encode(cx, args[0]); if (!key) { return false; } if (key.len == 0) { JS_ReportErrorASCII(cx, "Device.lookup: useragent parameter can not be an empty string"); return false; } auto lookup_res = host_api::DeviceDetection::lookup(key); if (auto *err = lookup_res.to_err()) { if (host_api::error_is_optional_none(*err)) { args.rval().setNull(); return true; } HANDLE_ERROR(cx, *err); return false; } auto result = std::move(lookup_res.unwrap()); JS::RootedString device_info_str(cx, JS_NewStringCopyN(cx, result.ptr.release(), result.len)); if (!device_info_str) { return false; } JS::RootedValue device_info(cx); if (!JS_ParseJSON(cx, device_info_str, &device_info)) { return false; } MOZ_ASSERT(device_info.isObject()); JS::RootedObject device_info_obj(cx, device_info.toObjectOrNull()); args.rval().setObjectOrNull(Device::create(cx, device_info_obj)); return true; } const JSFunctionSpec Device::static_methods[] = { JS_FN("lookup", lookup, 1, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec Device::static_properties[] = { JS_PS_END, }; const JSFunctionSpec Device::methods[] = {JS_FN("toJSON", toJSON, 0, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec Device::properties[] = { JS_PSG("name", Device::device_name_get, JSPROP_ENUMERATE), JS_PSG("brand", Device::brand_get, JSPROP_ENUMERATE), JS_PSG("model", Device::model_get, JSPROP_ENUMERATE), JS_PSG("hardwareType", Device::hardware_type_get, JSPROP_ENUMERATE), JS_PSG("isDesktop", Device::is_desktop_get, JSPROP_ENUMERATE), JS_PSG("isGameConsole", Device::is_gameconsole_get, JSPROP_ENUMERATE), JS_PSG("isMediaPlayer", Device::is_mediaplayer_get, JSPROP_ENUMERATE), JS_PSG("isMobile", Device::is_mobile_get, JSPROP_ENUMERATE), JS_PSG("isSmartTV", Device::is_smarttv_get, JSPROP_ENUMERATE), JS_PSG("isTablet", Device::is_tablet_get, JSPROP_ENUMERATE), JS_PSG("isTouchscreen", Device::is_touchscreen_get, JSPROP_ENUMERATE), JS_PSG("isBot", Device::is_bot_get, JSPROP_ENUMERATE), JS_STRING_SYM_PS(toStringTag, "Device", JSPROP_READONLY), JS_PS_END}; JSObject *Device::create(JSContext *cx, JS::HandleObject device_info) { JS::RootedObject instance(cx, JS_NewObjectWithGivenProto(cx, &Device::class_, Device::proto_obj)); JS::RootedValue device(cx); if (!JS_GetProperty(cx, device_info, "device", &device)) { return nullptr; } MOZ_ASSERT(device.isObject()); JS::SetReservedSlot(instance, static_cast(Slots::DeviceInfo), device); return instance; } bool install(api::Engine *engine) { if (!Device::init_class_impl(engine->cx(), engine->global())) { return false; } RootedObject device_ns_obj(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue device_ns_val(engine->cx(), JS::ObjectValue(*device_ns_obj)); RootedObject device_obj(engine->cx(), JS_GetConstructor(engine->cx(), Device::proto_obj)); RootedValue device_val(engine->cx(), ObjectValue(*device_obj)); if (!JS_SetProperty(engine->cx(), device_ns_obj, "Device", device_val)) { return false; } if (!engine->define_builtin_module("fastly:device", device_ns_val)) { return false; } return true; } } // namespace fastly::device ================================================ FILE: runtime/fastly/builtins/device.h ================================================ #ifndef FASTLY_DEVICE_H #define FASTLY_DEVICE_H #include "builtin.h" #include "extension-api.h" namespace fastly::device { class Device : public builtins::BuiltinNoConstructor { private: public: static constexpr const char *class_name = "Device"; static const int ctor_length = 0; // { // "brand": null, // "hwtype": null, // "is_desktop": false, // "is_ereader": false, // "is_gameconsole": false, // "is_mediaplayer": false, // "is_mobile": false, // "is_smarttv": false, // "is_tablet": false, // "is_touchscreen": false, // "is_tvplayer": false, // "model": null, // "name": null // } enum Slots { DeviceInfo, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool device_name_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool brand_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool model_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool hardware_type_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool is_gameconsole_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool is_mediaplayer_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool is_mobile_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool is_smarttv_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool is_tablet_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool is_desktop_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool is_touchscreen_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool is_bot_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool toJSON(JSContext *cx, unsigned argc, JS::Value *vp); static bool lookup(JSContext *cx, unsigned argc, JS::Value *vp); static JSObject *create(JSContext *cx, JS::HandleObject deviceInfo); static JSString *ToSource(JSContext *cx, JS::HandleObject self); }; } // namespace fastly::device #endif ================================================ FILE: runtime/fastly/builtins/dictionary.cpp ================================================ #include "dictionary.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../host-api/host_api_fastly.h" #include "fastly.h" using fastly::FastlyGetErrorMessage; namespace fastly::dictionary { host_api::Dict Dictionary::dictionary_handle(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, Dictionary::Slots::Handle); return host_api::Dict(val.toInt32()); } bool Dictionary::get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::HandleValue name_arg = args.get(0); // Convert into a String following https://tc39.es/ecma262/#sec-tostring auto name = core::encode(cx, name_arg); if (!name) { return false; } // If the converted string has a length of 0 then we throw an Error // because Dictionary keys have to be at-least 1 character. if (name.len == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_DICTIONARY_KEY_EMPTY); return false; } // key has to be less than 256 if (name.len > 255) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_DICTIONARY_KEY_TOO_LONG); return false; } // Ensure that we throw an exception for all unexpected host errors. auto res = Dictionary::dictionary_handle(self).get(name); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto ret = std::move(res.unwrap()); if (!ret.has_value()) { args.rval().setNull(); return true; } JS::RootedString text(cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(ret->ptr.get(), ret->len))); if (!text) return false; args.rval().setString(text); return true; } const JSFunctionSpec Dictionary::static_methods[] = { JS_FS_END, }; const JSPropertySpec Dictionary::static_properties[] = { JS_PS_END, }; const JSFunctionSpec Dictionary::methods[] = {JS_FN("get", get, 1, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec Dictionary::properties[] = {JS_PS_END}; bool Dictionary::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The Dictionary builtin"); CTOR_HEADER("Dictionary", 1); JS::HandleValue name_arg = args.get(0); // Convert into a String following https://tc39.es/ecma262/#sec-tostring auto name = core::encode(cx, name_arg); if (!name) { return false; } // If the converted string has a length of 0 then we throw an Error // because Dictionary names have to be at-least 1 character. if (name.len == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_DICTIONARY_NAME_EMPTY); return false; } // If the converted string has a length of more than 255 then we throw an Error // because Dictionary names have to be less than 255 characters. if (name.len > 255) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_DICTIONARY_NAME_TOO_LONG); return false; } // Name must start with ascii alphabetical and contain only ascii alphanumeric, underscore, and // whitespace std::string_view name_view = name; if (!std::isalpha(name_view.front())) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_DICTIONARY_NAME_START_WITH_ASCII_ALPHA); return false; } auto is_valid_name = std::all_of(std::next(name_view.begin(), 1), name_view.end(), [&](auto character) { return std::isalnum(character) || character == '_' || character == ' '; }); if (!is_valid_name) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_DICTIONARY_NAME_CONTAINS_INVALID_CHARACTER); return false; } JS::RootedObject dictionary(cx, JS_NewObjectForConstructor(cx, &class_, args)); auto res = host_api::Dict::open(name_view); if (auto *err = res.to_err()) { if (host_api::error_is_bad_handle(*err)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_DICTIONARY_DOES_NOT_EXIST, name_view.data()); return false; } else { HANDLE_ERROR(cx, *err); return false; } } auto dict = res.unwrap(); JS::SetReservedSlot(dictionary, Dictionary::Slots::Handle, JS::Int32Value(dict.handle)); if (!dictionary) { return false; } args.rval().setObject(*dictionary); return true; } bool install(api::Engine *engine) { if (!Dictionary::init_class_impl(engine->cx(), engine->global())) { return false; } RootedObject dictionary_ns_obj(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue dictionary_ns_val(engine->cx(), JS::ObjectValue(*dictionary_ns_obj)); RootedObject dictionary_obj(engine->cx(), JS_GetConstructor(engine->cx(), Dictionary::proto_obj)); RootedValue dictionary_val(engine->cx(), ObjectValue(*dictionary_obj)); if (!JS_SetProperty(engine->cx(), dictionary_ns_obj, "Dictionary", dictionary_val)) { return false; } if (!engine->define_builtin_module("fastly:dictionary", dictionary_ns_val)) { return false; } return true; } } // namespace fastly::dictionary ================================================ FILE: runtime/fastly/builtins/dictionary.h ================================================ #ifndef FASTLYE_DICTIONARY_H #define FASTLYE_DICTIONARY_H #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "extension-api.h" namespace fastly::dictionary { class Dictionary : public builtins::BuiltinImpl { private: public: static constexpr const char *class_name = "Dictionary"; static const int ctor_length = 1; enum Slots { Handle, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool get(JSContext *cx, unsigned argc, JS::Value *vp); static host_api::Dict dictionary_handle(JSObject *obj); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); }; } // namespace fastly::dictionary #endif ================================================ FILE: runtime/fastly/builtins/edge-rate-limiter.cpp ================================================ #include "edge-rate-limiter.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "js/Result.h" #include namespace fastly::edge_rate_limiter { JSString *PenaltyBox::get_name(JSObject *self) { MOZ_ASSERT(is_instance(self)); MOZ_ASSERT(JS::GetReservedSlot(self, Slots::Name).isString()); return JS::GetReservedSlot(self, Slots::Name).toString(); } // add(entry: string, timeToLive: number): void; bool PenaltyBox::add(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The PenaltyBox builtin"); METHOD_HEADER(2); // Convert entry parameter into a string auto entry = core::encode(cx, args.get(0)); if (!entry) { return false; } // Convert timeToLive parameter into a number double timeToLive; if (!JS::ToNumber(cx, args.get(1), &timeToLive)) { return false; } // This needs to happen on the happy-path as these all end up being valid uint32_t values that the // host-call accepts if (std::isnan(timeToLive) || std::isinf(timeToLive) || timeToLive < 1 || timeToLive > 60) { JS_ReportErrorASCII(cx, "add: timeToLive parameter is an invalid value, only numbers from 1 to " "60 can be used for timeToLive values."); return false; } // We expose it in minutes as the value gets truncated to minutes however the host expects it in // seconds timeToLive = timeToLive * 60; MOZ_ASSERT(JS::GetReservedSlot(self, Slots::Name).isString()); JS::RootedString name_val(cx, JS::GetReservedSlot(self, Slots::Name).toString()); auto name = core::encode(cx, name_val); if (!name) { return false; } auto res = host_api::PenaltyBox::add(name, entry, timeToLive); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } // has(entry: string): boolean; bool PenaltyBox::has(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The PenaltyBox builtin"); METHOD_HEADER(1); // Convert entry parameter into a string auto entry = core::encode(cx, args.get(0)); if (!entry) { return false; } MOZ_ASSERT(JS::GetReservedSlot(self, Slots::Name).isString()); JS::RootedString name_val(cx, JS::GetReservedSlot(self, Slots::Name).toString()); auto name = core::encode(cx, name_val); if (!name) { return false; } auto res = host_api::PenaltyBox::has(name, entry); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setBoolean(res.unwrap()); return true; } const JSFunctionSpec PenaltyBox::static_methods[] = { JS_FS_END, }; const JSPropertySpec PenaltyBox::static_properties[] = { JS_PS_END, }; const JSFunctionSpec PenaltyBox::methods[] = { JS_FN("add", add, 2, JSPROP_ENUMERATE), JS_FN("has", has, 1, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec PenaltyBox::properties[] = { JS_STRING_SYM_PS(toStringTag, "PenaltyBox", JSPROP_READONLY), JS_PS_END}; // Open a penalty-box identified by the given name // constructor(name: string); bool PenaltyBox::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The PenaltyBox builtin"); CTOR_HEADER("PenaltyBox", 1); auto name = core::encode(cx, args.get(0)); if (!name) { return false; } if (name.len == 0) { JS_ReportErrorASCII(cx, "PenaltyBox constructor: name parameter can not be an empty string."); return false; } JS::RootedObject instance(cx, JS_NewObjectForConstructor(cx, &class_, args)); if (!instance) { return false; } JS::RootedString name_str(cx, JS_NewStringCopyN(cx, name.begin(), name.len)); if (!name_str) { return false; } JS::SetReservedSlot(instance, static_cast(Slots::Name), JS::StringValue(name_str)); args.rval().setObject(*instance); return true; } JSString *RateCounter::get_name(JSObject *self) { MOZ_ASSERT(is_instance(self)); MOZ_ASSERT(JS::GetReservedSlot(self, Slots::Name).isString()); return JS::GetReservedSlot(self, Slots::Name).toString(); } // increment(entry: string, delta: number): void; bool RateCounter::increment(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The RateCounter builtin"); METHOD_HEADER(2); // Convert entry parameter into a string auto entry = core::encode(cx, args.get(0)); if (!entry) { return false; } // Convert delta parameter into a number double delta; if (!JS::ToNumber(cx, args.get(1), &delta)) { return false; } // This needs to happen on the happy-path as these all end up being valid uint32_t values that the // host-call accepts if (delta < 0 || std::isnan(delta) || std::isinf(delta)) { JS_ReportErrorASCII(cx, "increment: delta parameter is an invalid value, only positive numbers can " "be used for delta values."); return false; } MOZ_ASSERT(JS::GetReservedSlot(self, Slots::Name).isString()); JS::RootedString name_val(cx, JS::GetReservedSlot(self, Slots::Name).toString()); auto name = core::encode(cx, name_val); if (!name) { return false; } auto res = host_api::RateCounter::increment(name, entry, delta); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } // lookupRate(entry: string, window: [1, 10, 60]): number; bool RateCounter::lookupRate(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The RateCounter builtin"); METHOD_HEADER(2); // Convert entry parameter into a string auto entry = core::encode(cx, args.get(0)); if (!entry) { return false; } // Convert window parameter into a number double window; if (!JS::ToNumber(cx, args.get(1), &window)) { return false; } MOZ_ASSERT(JS::GetReservedSlot(self, Slots::Name).isString()); JS::RootedString name_val(cx, JS::GetReservedSlot(self, Slots::Name).toString()); auto name = core::encode(cx, name_val); if (!name) { return false; } auto res = host_api::RateCounter::lookup_rate(name, entry, window); if (auto *err = res.to_err()) { if (host_api::error_is_generic(*err) || host_api::error_is_invalid_argument(*err)) { if (window != 1 && window != 10 && window != 60) { JS_ReportErrorASCII(cx, "lookupRate: window parameter must be either: 1, 10, or 60"); return false; } } HANDLE_ERROR(cx, *err); return false; } JS::RootedValue rate(cx, JS::NumberValue(res.unwrap())); args.rval().set(rate); return true; } // lookupCount(entry: string, duration: [10, 20, 30, 40, 50, 60]): number; bool RateCounter::lookupCount(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The RateCounter builtin"); METHOD_HEADER(2); // Convert entry parameter into a string auto entry = core::encode(cx, args.get(0)); if (!entry) { return false; } // Convert duration parameter into a number double duration; if (!JS::ToNumber(cx, args.get(1), &duration)) { return false; } MOZ_ASSERT(JS::GetReservedSlot(self, Slots::Name).isString()); JS::RootedString name_val(cx, JS::GetReservedSlot(self, Slots::Name).toString()); auto name = core::encode(cx, name_val); if (!name) { return false; } auto res = host_api::RateCounter::lookup_count(name, entry, duration); if (auto *err = res.to_err()) { if (host_api::error_is_generic(*err) || host_api::error_is_invalid_argument(*err)) { if (duration != 10 && duration != 20 && duration != 30 && duration != 40 && duration != 50 && duration != 60) { JS_ReportErrorASCII( cx, "lookupCount: duration parameter must be either: 10, 20, 30, 40, 50, or 60"); return false; } } HANDLE_ERROR(cx, *err); return false; } JS::RootedValue rate(cx, JS::NumberValue(res.unwrap())); args.rval().set(rate); return true; } const JSFunctionSpec RateCounter::static_methods[] = { JS_FS_END, }; const JSPropertySpec RateCounter::static_properties[] = { JS_PS_END, }; const JSFunctionSpec RateCounter::methods[] = { JS_FN("increment", increment, 2, JSPROP_ENUMERATE), JS_FN("lookupRate", lookupRate, 2, JSPROP_ENUMERATE), JS_FN("lookupCount", lookupCount, 2, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec RateCounter::properties[] = { JS_STRING_SYM_PS(toStringTag, "RateCounter", JSPROP_READONLY), JS_PS_END}; // Open a RateCounter instance with the given name // constructor(name: string); bool RateCounter::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The RateCounter builtin"); CTOR_HEADER("RateCounter", 1); auto name = core::encode(cx, args.get(0)); if (!name) { return false; } if (name.len == 0) { JS_ReportErrorASCII(cx, "RateCounter constructor: name parameter can not be an empty string."); return false; } JS::RootedObject instance(cx, JS_NewObjectForConstructor(cx, &class_, args)); if (!instance) { return false; } JS::RootedString name_str(cx, JS_NewStringCopyN(cx, name.begin(), name.len)); JS::SetReservedSlot(instance, static_cast(Slots::Name), JS::StringValue(name_str)); args.rval().setObject(*instance); return true; } // checkRate(entry: string, delta: number, window: [1, 10, 60], limit: number, timeToLive: number): // boolean; bool EdgeRateLimiter::checkRate(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The EdgeRateLimiter builtin"); METHOD_HEADER(5); // Convert entry parameter into a string auto entry = core::encode(cx, args.get(0)); if (!entry) { return false; } // Convert delta parameter into a number double delta; if (!JS::ToNumber(cx, args.get(1), &delta)) { return false; } if (delta < 0 || std::isnan(delta) || std::isinf(delta)) { JS_ReportErrorASCII(cx, "checkRate: delta parameter is an invalid value, only positive numbers can " "be used for delta values."); return false; } // Convert window parameter into a number double window; if (!JS::ToNumber(cx, args.get(2), &window)) { return false; } if (window != 1 && window != 10 && window != 60) { JS_ReportErrorASCII(cx, "checkRate: window parameter must be either: 1, 10, or 60"); return false; } // Convert limit parameter into a number double limit; if (!JS::ToNumber(cx, args.get(3), &limit)) { return false; } // This needs to happen on the happy-path as these all end up being valid uint32_t values that the // host-call accepts if (limit < 0 || std::isnan(limit) || std::isinf(limit)) { JS_ReportErrorASCII(cx, "checkRate: limit parameter is an invalid value, only positive numbers can " "be used for limit values."); return false; } // Convert timeToLive parameter into a number double timeToLive; if (!JS::ToNumber(cx, args.get(4), &timeToLive)) { return false; } // This needs to happen on the happy-path as these all end up being valid uint32_t values that the // host-call accepts if (std::isnan(timeToLive) || std::isinf(timeToLive) || timeToLive < 1 || timeToLive > 60) { JS_ReportErrorASCII( cx, "checkRate: timeToLive parameter is an invalid value, only numbers from 1 to " "60 can be used for timeToLive values."); return false; } // We expose it in minutes as the value gets truncated to minutes however the host expects it in // seconds timeToLive = timeToLive * 60; MOZ_ASSERT(JS::GetReservedSlot(self, Slots::RateCounterName).isString()); JS::RootedString rc_name_val(cx, JS::GetReservedSlot(self, Slots::RateCounterName).toString()); auto rc_name = core::encode(cx, rc_name_val); if (!rc_name) { return false; } MOZ_ASSERT(JS::GetReservedSlot(self, Slots::PenaltyBoxName).isString()); JS::RootedString pb_name_val(cx, JS::GetReservedSlot(self, Slots::PenaltyBoxName).toString()); auto pb_name = core::encode(cx, pb_name_val); if (!pb_name) { return false; } auto res = host_api::EdgeRateLimiter::check_rate(rc_name, entry, delta, window, limit, pb_name, timeToLive); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setBoolean(res.unwrap()); return true; } const JSFunctionSpec EdgeRateLimiter::static_methods[] = { JS_FS_END, }; const JSPropertySpec EdgeRateLimiter::static_properties[] = { JS_PS_END, }; const JSFunctionSpec EdgeRateLimiter::methods[] = { JS_FN("checkRate", checkRate, 5, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec EdgeRateLimiter::properties[] = { JS_STRING_SYM_PS(toStringTag, "EdgeRateLimiter", JSPROP_READONLY), JS_PS_END}; // Open a penalty-box identified by the given name // constructor(name: string); bool EdgeRateLimiter::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The EdgeRateLimiter builtin"); CTOR_HEADER("EdgeRateLimiter", 2); auto rc = args.get(0); if (!RateCounter::is_instance(rc)) { JS_ReportErrorASCII( cx, "EdgeRateLimiter constructor: rateCounter parameter must be an instance of RateCounter"); return false; } JS::RootedString rc_name(cx, RateCounter::get_name(rc.toObjectOrNull())); if (!rc_name) { return false; } auto pb = args.get(1); if (!PenaltyBox::is_instance(pb)) { JS_ReportErrorASCII( cx, "EdgeRateLimiter constructor: penaltyBox parameter must be an instance of PenaltyBox"); return false; } JS::RootedString pb_name(cx, PenaltyBox::get_name(pb.toObjectOrNull())); if (!pb_name) { return false; } JS::RootedObject instance(cx, JS_NewObjectForConstructor(cx, &class_, args)); if (!instance) { return false; } JS::SetReservedSlot(instance, static_cast(Slots::RateCounterName), JS::StringValue(rc_name)); JS::SetReservedSlot(instance, static_cast(Slots::PenaltyBoxName), JS::StringValue(pb_name)); args.rval().setObject(*instance); return true; } bool install(api::Engine *engine) { if (!PenaltyBox::init_class_impl(engine->cx(), engine->global())) { return false; } if (!EdgeRateLimiter::init_class_impl(engine->cx(), engine->global())) { return false; } if (!RateCounter::init_class_impl(engine->cx(), engine->global())) { return false; } RootedObject edge_rate_limiter_ns_obj(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue edge_rate_limiter_ns_val(engine->cx(), JS::ObjectValue(*edge_rate_limiter_ns_obj)); RootedObject edge_rate_limiter_obj(engine->cx(), JS_GetConstructor(engine->cx(), EdgeRateLimiter::proto_obj)); RootedValue edge_rate_limiter_val(engine->cx(), ObjectValue(*edge_rate_limiter_obj)); if (!JS_SetProperty(engine->cx(), edge_rate_limiter_ns_obj, "EdgeRateLimiter", edge_rate_limiter_val)) { return false; } RootedObject penalty_box_obj(engine->cx(), JS_GetConstructor(engine->cx(), PenaltyBox::proto_obj)); RootedValue penalty_box_val(engine->cx(), ObjectValue(*penalty_box_obj)); if (!JS_SetProperty(engine->cx(), edge_rate_limiter_ns_obj, "PenaltyBox", penalty_box_val)) { return false; } RootedObject rate_counter_obj(engine->cx(), JS_GetConstructor(engine->cx(), RateCounter::proto_obj)); RootedValue rate_counter_val(engine->cx(), ObjectValue(*rate_counter_obj)); if (!JS_SetProperty(engine->cx(), edge_rate_limiter_ns_obj, "RateCounter", rate_counter_val)) { return false; } if (!engine->define_builtin_module("fastly:edge-rate-limiter", edge_rate_limiter_ns_val)) { return false; } return true; } } // namespace fastly::edge_rate_limiter ================================================ FILE: runtime/fastly/builtins/edge-rate-limiter.h ================================================ #ifndef FASTLY_EDGE_RATE_LIMITER_H #define FASTLY_EDGE_RATE_LIMITER_H #include "builtin.h" #include "extension-api.h" namespace fastly::edge_rate_limiter { class PenaltyBox final : public builtins::BuiltinImpl { static bool add(JSContext *cx, unsigned argc, JS::Value *vp); static bool has(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "PenaltyBox"; enum Slots { Name, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static const unsigned ctor_length = 0; static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); static JSString *get_name(JSObject *self); }; class RateCounter final : public builtins::BuiltinImpl { static bool increment(JSContext *cx, unsigned argc, JS::Value *vp); static bool lookupRate(JSContext *cx, unsigned argc, JS::Value *vp); static bool lookupCount(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "RateCounter"; enum Slots { Name, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static const unsigned ctor_length = 0; static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); static JSString *get_name(JSObject *self); }; class EdgeRateLimiter final : public builtins::BuiltinImpl { static bool checkRate(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "EdgeRateLimiter"; enum Slots { RateCounterName, PenaltyBoxName, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static const unsigned ctor_length = 0; static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); }; } // namespace fastly::edge_rate_limiter #endif ================================================ FILE: runtime/fastly/builtins/fastly.cpp ================================================ // TODO: remove these once the warnings are fixed #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" #include "js/experimental/TypedData.h" // used in "js/Conversions.h" #pragma clang diagnostic pop #include "../../StarlingMonkey/builtins/web/url.h" #include "./fetch/request-response.h" #include "backend.h" #include "encode.h" #include "fastly.h" #include "js/Conversions.h" #include "js/JSON.h" #include "kv-store.h" #include "logger.h" #include using builtins::web::url::URL; using builtins::web::url::URLSearchParams; using fastly::fastly::Fastly; using fastly::fetch::RequestOrResponse; using fastly::fetch::Response; using fastly::logger::Logger; extern char **environ; namespace { api::Engine *ENGINE; // Global storage for Wizer-time environment std::unordered_map initialized_env; static void oom_callback(JSContext *cx, void *data) { fprintf(stderr, "Critical Error: out of memory\n"); fflush(stderr); } #ifdef DEBUG static std::vector debug_messages; #endif } // namespace bool debug_logging_enabled() { return fastly::fastly::DEBUG_LOGGING_ENABLED; } namespace fastly::fastly { bool DEBUG_LOGGING_ENABLED = false; JS::PersistentRooted Fastly::env; JS::PersistentRooted Fastly::baseURL; JS::PersistentRooted Fastly::defaultBackend; bool allowDynamicBackendsCalled = false; bool Fastly::allowDynamicBackends = true; bool ENABLE_EXPERIMENTAL_HTTP_CACHE = false; ReusableSandboxOptions Fastly::reusableSandboxOptions{}; bool Fastly::dump(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, __func__, 1)) return false; // special debug mode operations #ifndef NDEBUG if (args.get(0).isNull() && args.get(1).isString()) { JS::RootedString str(cx, args.get(1).toString()); auto str_chars = core::encode(cx, str); if (!str_chars) { return false; } if (!strcmp(str_chars.ptr.get(), "invalidkv")) { host_api::HttpBody body(-1); host_api::HostBytes metadata{}; // uint32_t gen = std::get<2>(res.unwrap()); JS::RootedObject entry( cx, ::fastly::kv_store::KVStoreEntry::create(cx, body, std::move(metadata))); args.rval().setObject(*entry); return true; } } #endif ENGINE->dump_value(args[0], stdout); args.rval().setUndefined(); return true; } bool Fastly::enableDebugLogging(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, __func__, 1)) return false; DEBUG_LOGGING_ENABLED = JS::ToBoolean(args[0]); args.rval().setUndefined(); return true; } bool debugLog(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, __func__, 1)) return false; JS::RootedString msg_str(cx, JS::ToString(cx, args[0])); if (!msg_str) { return false; } auto msg_host_str = core::encode(cx, msg_str); if (!msg_host_str) { return false; } #ifdef DEBUG debug_messages.push_back(std::string(msg_host_str)); #endif args.rval().setUndefined(); return true; } bool Fastly::getGeolocationForIpAddress(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); REQUEST_HANDLER_ONLY("fastly.getGeolocationForIpAddress"); if (!args.requireAtLeast(cx, "fastly.getGeolocationForIpAddress", 1)) return false; JS::RootedString address_str(cx, JS::ToString(cx, args[0])); if (!address_str) return false; auto address = core::encode(cx, address_str); if (!address) { return false; } // TODO: Remove all of this and rely on the host for validation as the hostcall only takes one // user-supplied parameter int format = AF_INET; size_t octets_len = 4; if (std::find(address.begin(), address.end(), ':') != address.end()) { format = AF_INET6; octets_len = 16; } uint8_t octets[sizeof(struct in6_addr)]; if (inet_pton(format, address.begin(), octets) != 1) { // While get_geo_info can be invoked through FetchEvent#client.geo, too, // that path can't result in an invalid address here, so we can be more // specific in the error message. // TODO: Make a TypeError JS_ReportErrorLatin1(cx, "Invalid address passed to fastly.getGeolocationForIpAddress"); return false; } auto res = host_api::GeoIp::lookup(std::span{octets, octets_len}); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); return true; } auto ret = std::move(res.unwrap().value()); JS::RootedString geo_info_str( cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(ret.ptr.release(), ret.len))); if (!geo_info_str) return false; return JS_ParseJSON(cx, geo_info_str, args.rval()); } bool Fastly::inspect(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); REQUEST_HANDLER_ONLY("fastly.inspect"); if (!args.requireAtLeast(cx, "fastly.inspect", 1)) { return false; } auto request_value = args.get(0); if (!Request::is_instance(request_value)) { JS_ReportErrorUTF8(cx, "inspect: request parameter must be an instance of Request"); return false; } JS::RootedObject request(cx, &request_value.toObject()); auto req{Request::request_handle(request)}; auto bod{RequestOrResponse::body_handle(request)}; auto options_value = args.get(1); JS::RootedObject options_obj(cx, options_value.isObject() ? &options_value.toObject() : nullptr); host_api::InspectOptions inspect_options(req.handle, bod.handle); host_api::HostString corp_str; JS::RootedValue corp_val(cx); host_api::HostString workspace_str; JS::RootedValue workspace_val(cx); host_api::HostString override_client_ip_str; JS::RootedValue override_client_ip_val(cx); alignas(struct in6_addr) uint8_t octets[sizeof(struct in6_addr)]; if (options_obj != nullptr) { if (JS_GetProperty(cx, options_obj, "corp", &corp_val)) { if (!corp_val.isNullOrUndefined()) { if (!corp_val.isString()) { api::throw_error(cx, api::Errors::TypeError, "fastly.inspect", "corp", "be a string"); return false; } corp_str = core::encode(cx, corp_val); if (!corp_str) { return false; } inspect_options.corp_len = corp_str.size(); inspect_options.corp = std::move(corp_str.begin()); } } if (JS_GetProperty(cx, options_obj, "workspace", &workspace_val)) { if (!workspace_val.isNullOrUndefined()) { if (!workspace_val.isString()) { api::throw_error(cx, api::Errors::TypeError, "fastly.inspect", "workspace", "be a string"); return false; } workspace_str = core::encode(cx, workspace_val); if (!workspace_str) { return false; } inspect_options.workspace_len = workspace_str.size(); inspect_options.workspace = std::move(workspace_str.begin()); } } if (JS_GetProperty(cx, options_obj, "overrideClientIp", &override_client_ip_val)) { if (!override_client_ip_val.isNullOrUndefined()) { if (!override_client_ip_val.isString()) { api::throw_error(cx, api::Errors::TypeError, "fastly.inspect", "overrideClientIp", "be a string"); return false; } override_client_ip_str = core::encode(cx, override_client_ip_val); if (!override_client_ip_str) { return false; } // TODO: Remove all of this and rely on the host for validation as the hostcall only takes // one user-supplied parameter int format = AF_INET; size_t octets_len = 4; if (std::find(override_client_ip_str.begin(), override_client_ip_str.end(), ':') != override_client_ip_str.end()) { format = AF_INET6; octets_len = 16; } if (inet_pton(format, override_client_ip_str.begin(), &octets) != 1) { api::throw_error(cx, api::Errors::TypeError, "fastly.inspect", "overrideClientIp", "be a valid IP address"); return false; } inspect_options.override_client_ip_len = octets_len; inspect_options.override_client_ip_ptr = reinterpret_cast(&octets); } } } host_api::Request host_request{req, bod}; auto res = host_request.inspect(&inspect_options); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto ret{std::move(res.unwrap())}; JS::RootedString js_str(cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(ret.ptr.release(), ret.len))); return JS_ParseJSON(cx, js_str, args.rval()); } // TODO(performance): consider allowing logger creation during initialization, but then throw // when trying to log. // https://github.com/fastly/js-compute-runtime/issues/225 bool Fastly::getLogger(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); REQUEST_HANDLER_ONLY("fastly.getLogger"); JS::RootedObject self(cx, &args.thisv().toObject()); if (!args.requireAtLeast(cx, "fastly.getLogger", 1)) return false; JS::RootedObject logger(cx, Logger::create(cx, args[0])); if (!logger) { return false; } args.rval().setObject(*logger); return true; } bool Fastly::includeBytes(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); INIT_ONLY("fastly.includeBytes"); if (!args.requireAtLeast(cx, "fastly.includeBytes", 1)) return false; auto path = core::encode(cx, args[0]); if (!path) { return false; } FILE *fp = fopen(path.begin(), "r"); if (!fp) { JS_ReportErrorUTF8(cx, "Error opening file %s", path.begin()); return false; } fseek(fp, 0L, SEEK_END); size_t size = ftell(fp); rewind(fp); JS::RootedObject typed_array(cx, JS_NewUint8Array(cx, size)); if (!typed_array) return false; size_t read_bytes; { JS::AutoCheckCannotGC noGC(cx); bool is_shared; void *buffer = JS_GetArrayBufferViewData(typed_array, &is_shared, noGC); read_bytes = fread(buffer, 1, size, fp); } if (read_bytes != size) { JS_ReportErrorUTF8(cx, "Failed to read contents of file %s", path.begin()); return false; } args.rval().setObject(*typed_array); return true; } bool Fastly::createFanoutHandoff(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); REQUEST_HANDLER_ONLY("createFanoutHandoff"); if (!args.requireAtLeast(cx, "createFanoutHandoff", 2)) { return false; } auto request_value = args.get(0); if (!Request::is_instance(request_value)) { JS_ReportErrorUTF8(cx, "createFanoutHandoff: request parameter must be an instance of Request"); return false; } JS::RootedObject grip_upgrade_request(cx, &request_value.toObject()); RootedObject request(cx, grip_upgrade_request); if (!RequestOrResponse::commit_headers(cx, request)) { return false; } auto response_handle = host_api::HttpResp::make(); if (auto *err = response_handle.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body_handle = host_api::HttpBody::make(); if (auto *err = body_handle.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::RootedObject response_instance( cx, JS_NewObjectWithGivenProto(cx, &Response::class_, Response::proto_obj)); if (!response_instance) { return false; } auto backend_value = args.get(1); JS::RootedString backend_str(cx, JS::ToString(cx, backend_value)); if (!backend_str) { return false; } auto backend_chars = core::encode(cx, backend_str); if (!backend_chars) { return false; } if (backend_chars.len == 0) { JS_ReportErrorUTF8(cx, "createFanoutHandoff: Backend parameter can not be an empty string"); return false; } if (backend_chars.len > 254) { JS_ReportErrorUTF8(cx, "createFanoutHandoff: name can not be more than 254 characters"); return false; } bool is_upstream = true; JS::RootedObject response(cx, Response::create(cx, response_instance, response_handle.unwrap(), body_handle.unwrap(), is_upstream, grip_upgrade_request, nullptr, backend_str)); if (!response) { return false; } RequestOrResponse::set_url(response, RequestOrResponse::url(&request_value.toObject())); args.rval().setObject(*response); return true; } bool Fastly::createWebsocketHandoff(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); REQUEST_HANDLER_ONLY("createWebsocketHandoff"); if (!args.requireAtLeast(cx, "createWebsocketHandoff", 2)) { return false; } auto request_value = args.get(0); if (!Request::is_instance(request_value)) { JS_ReportErrorUTF8(cx, "createWebsocketHandoff: request parameter must be an instance of Request"); return false; } JS::RootedObject websocket_upgrade_request(cx, &request_value.toObject()); RootedObject request(cx, websocket_upgrade_request); if (!RequestOrResponse::commit_headers(cx, request)) { return false; } auto response_handle = host_api::HttpResp::make(); if (auto *err = response_handle.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body_handle = host_api::HttpBody::make(); if (auto *err = body_handle.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::RootedObject response_instance( cx, JS_NewObjectWithGivenProto(cx, &Response::class_, Response::proto_obj)); if (!response_instance) { return false; } auto backend_value = args.get(1); JS::RootedString backend_str(cx, JS::ToString(cx, backend_value)); if (!backend_str) { return false; } auto backend_chars = core::encode(cx, backend_str); if (!backend_chars) { return false; } if (backend_chars.len == 0) { JS_ReportErrorUTF8(cx, "createWebsocketHandoff: Backend parameter can not be an empty string"); return false; } if (backend_chars.len > 254) { JS_ReportErrorUTF8(cx, "createWebsocketHandoff: name can not be more than 254 characters"); return false; } bool is_upstream = true; JS::RootedObject response(cx, Response::create(cx, response_instance, response_handle.unwrap(), body_handle.unwrap(), is_upstream, nullptr, websocket_upgrade_request, backend_str)); if (!response) { return false; } RequestOrResponse::set_url(response, RequestOrResponse::url(&request_value.toObject())); args.rval().setObject(*response); return true; } bool Fastly::now(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); args.rval().setNumber(JS_Now()); return true; } bool Fastly::env_get(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); args.rval().setObject(*env); return true; } bool compute_get_vcpu_time(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); auto res = host_api::Compute::get_vcpu_ms(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setNumber(res.unwrap()); return true; } bool compute_purge_surrogate_key(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "purgeSurrogateKey", 1)) { return false; } JS::RootedString surrogate_key(cx, JS::ToString(cx, args.get(0))); if (!surrogate_key) { return false; } auto surrogate_key_chars = core::encode(cx, surrogate_key); bool soft = false; auto soft_val = args.get(1); if (soft_val.isBoolean()) { soft = soft_val.toBoolean(); } auto purge_res = host_api::Compute::purge_surrogate_key(surrogate_key_chars, soft); if (auto *err = purge_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } MOZ_ASSERT(!purge_res.unwrap().has_value()); args.rval().setUndefined(); return true; } bool Env::env_get(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "fastly.env.get", 1)) return false; JS::RootedString str(cx, JS::ToString(cx, args[0])); if (!str) { return false; } JS::UniqueChars ptr = JS_EncodeStringToUTF8(cx, str); if (!ptr) { return false; } // This shouldn't fail, since the encode operation ensured `str` is linear. JSLinearString *linear = JS_EnsureLinearString(cx, str); uint32_t len = JS::GetDeflatedUTF8StringLength(linear); std::string key_str(ptr.get(), len); // First check initialized environment if (auto it = initialized_env.find(key_str); it != initialized_env.end()) { JS::RootedString env_var(cx, JS_NewStringCopyN(cx, it->second.data(), it->second.size())); if (!env_var) return false; args.rval().setString(env_var); return true; } // Fallback to getenv with caching if (const char *value = std::getenv(key_str.c_str())) { auto [it, _] = initialized_env.emplace(key_str, value); JS::RootedString env_var(cx, JS_NewStringCopyN(cx, it->second.data(), it->second.size())); if (!env_var) return false; args.rval().setString(env_var); return true; } args.rval().setUndefined(); return true; } const JSFunctionSpec Env::static_methods[] = { JS_FS_END, }; const JSPropertySpec Env::static_properties[] = { JS_PS_END, }; const JSFunctionSpec Env::methods[] = {JS_FN("get", env_get, 1, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec Env::properties[] = {JS_PS_END}; JSObject *Env::create(JSContext *cx) { JS::RootedObject env(cx, JS_NewPlainObject(cx)); if (!env || !JS_DefineFunctions(cx, env, methods)) return nullptr; return env; } bool Fastly::version_get(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); JS::RootedString version_str(cx, JS_NewStringCopyN(cx, RUNTIME_VERSION, strlen(RUNTIME_VERSION))); args.rval().setString(version_str); return true; } bool Fastly::baseURL_get(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); args.rval().setObjectOrNull(baseURL); return true; } bool Fastly::baseURL_set(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); if (args.get(0).isNullOrUndefined()) { baseURL.set(nullptr); } else if (!URL::is_instance(args.get(0))) { JS_ReportErrorUTF8(cx, "Invalid value assigned to fastly.baseURL, must be an instance of " "URL, null, or undefined"); return false; } baseURL.set(&args.get(0).toObject()); args.rval().setObjectOrNull(baseURL); return true; } bool Fastly::defaultBackend_get(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); args.rval().setString(defaultBackend); return true; } bool Fastly::defaultBackend_set(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); JS::RootedString backend(cx, JS::ToString(cx, args.get(0))); if (!backend) return false; defaultBackend = backend; if (!allowDynamicBackendsCalled) { allowDynamicBackends = false; } args.rval().setUndefined(); return true; } #ifdef DEBUG bool debugMessages_get(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); JS::RootedObject debugMessages(cx, JS::NewArrayObject(cx, 0)); for (const auto &msg : debug_messages) { JS::RootedString str(cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(msg.data(), msg.length()))); MOZ_ASSERT(str); bool res; uint32_t len; res = JS::GetArrayLength(cx, debugMessages, &len); MOZ_ASSERT(res); res = JS_SetElement(cx, debugMessages, len, str); MOZ_ASSERT(res); } args.rval().setObject(*debugMessages); return true; } #endif bool Fastly::allowDynamicBackends_get(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); args.rval().setBoolean(allowDynamicBackends); return true; } bool Fastly::allowDynamicBackends_set(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); JS::HandleValue set_value = args.get(0); if (set_value.isObject()) { RootedObject options_value(cx, &set_value.toObject()); if (!backend::set_default_backend_config(cx, argc, vp)) { return false; } allowDynamicBackends = true; } else { allowDynamicBackends = JS::ToBoolean(set_value); } allowDynamicBackendsCalled = true; args.rval().setUndefined(); return true; } bool Fastly::setReusableSandboxOptions(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); if (Fastly::reusableSandboxOptions.frozen()) { JS_ReportErrorUTF8(cx, "Reusable sandbox options can only be set at initialization time"); return false; } if (!args.requireAtLeast(cx, "fastly.setReusableSandboxOptions", 1)) { return false; } JS::HandleValue options_value = args.get(0); if (!options_value.isObject()) { JS_ReportErrorUTF8(cx, "Options parameter must be an object"); return false; } RootedObject options_obj(cx, &options_value.toObject()); auto get_non_negative_int = [cx, &options_obj](const char *prop_name, bool *defined, int32_t *out_value) -> bool { RootedValue val(cx); if (!JS_GetProperty(cx, options_obj, prop_name, &val)) { return false; } if (val.isUndefined()) { *defined = false; return true; } *defined = true; if (!val.isInt32()) { JS_ReportErrorUTF8(cx, "%s option must be an integer", prop_name); return false; } int32_t int_val = val.toInt32(); if (int_val < 0) { JS_ReportErrorUTF8(cx, "%s option must be a non-negative integer", prop_name); return false; } *out_value = int_val; return true; }; bool defined = false; int32_t max_requests; if (get_non_negative_int("maxRequests", &defined, &max_requests)) { if (defined) { Fastly::reusableSandboxOptions.set_max_requests(max_requests); } } else { return false; } int32_t between_request_timeout_ms; if (get_non_negative_int("betweenRequestTimeoutMs", &defined, &between_request_timeout_ms)) { if (defined) { Fastly::reusableSandboxOptions.set_between_request_timeout( std::chrono::milliseconds(between_request_timeout_ms)); } } else { return false; } int32_t max_memory_mib; if (get_non_negative_int("maxMemoryMiB", &defined, &max_memory_mib)) { if (defined) { Fastly::reusableSandboxOptions.set_max_memory_mib(max_memory_mib); } } else { return false; } int32_t sandbox_timeout_ms; if (get_non_negative_int("sandboxTimeoutMs", &defined, &sandbox_timeout_ms)) { if (defined) { Fastly::reusableSandboxOptions.set_sandbox_timeout( std::chrono::milliseconds(sandbox_timeout_ms)); } } else { return false; } args.rval().setUndefined(); return true; } const JSPropertySpec Fastly::properties[] = { JS_PSG("env", env_get, JSPROP_ENUMERATE), JS_PSGS("baseURL", baseURL_get, baseURL_set, JSPROP_ENUMERATE), JS_PSGS("defaultBackend", defaultBackend_get, defaultBackend_set, JSPROP_ENUMERATE), JS_PSGS("allowDynamicBackends", allowDynamicBackends_get, allowDynamicBackends_set, JSPROP_ENUMERATE), JS_PSG("sdkVersion", version_get, JSPROP_ENUMERATE), #ifdef DEBUG JS_PSG("debugMessages", debugMessages_get, JSPROP_ENUMERATE), #endif JS_PS_END}; bool install(api::Engine *engine) { ENGINE = engine; bool ENABLE_EXPERIMENTAL_HIGH_RESOLUTION_TIME_METHODS = std::string(std::getenv("ENABLE_EXPERIMENTAL_HIGH_RESOLUTION_TIME_METHODS")) == "1"; ENABLE_EXPERIMENTAL_HTTP_CACHE = std::string(std::getenv("ENABLE_EXPERIMENTAL_HTTP_CACHE")) == "1"; JS::SetOutOfMemoryCallback(engine->cx(), oom_callback, nullptr); JS::RootedObject fastly(engine->cx()); get_fastly_object(engine, &fastly); if (!fastly) { return false; } Fastly::env.init(engine->cx(), Env::create(engine->cx())); if (!Fastly::env) { return false; } Fastly::baseURL.init(engine->cx()); Fastly::defaultBackend.init(engine->cx()); JSFunctionSpec nowfn = JS_FN("now", Fastly::now, 0, JSPROP_ENUMERATE); JSFunctionSpec end = JS_FS_END; const JSFunctionSpec methods[] = { JS_FN("dump", Fastly::dump, 1, 0), JS_FN("enableDebugLogging", Fastly::enableDebugLogging, 1, JSPROP_ENUMERATE), JS_FN("debugLog", debugLog, 1, JSPROP_ENUMERATE), JS_FN("getGeolocationForIpAddress", Fastly::getGeolocationForIpAddress, 1, JSPROP_ENUMERATE), JS_FN("inspect", Fastly::inspect, 1, JSPROP_ENUMERATE), JS_FN("getLogger", Fastly::getLogger, 1, JSPROP_ENUMERATE), JS_FN("includeBytes", Fastly::includeBytes, 1, JSPROP_ENUMERATE), JS_FN("createFanoutHandoff", Fastly::createFanoutHandoff, 2, JSPROP_ENUMERATE), JS_FN("createWebsocketHandoff", Fastly::createWebsocketHandoff, 2, JSPROP_ENUMERATE), JS_FN("setReusableSandboxOptions", Fastly::setReusableSandboxOptions, 1, JSPROP_ENUMERATE), ENABLE_EXPERIMENTAL_HIGH_RESOLUTION_TIME_METHODS ? nowfn : end, end}; if (!JS_DefineFunctions(engine->cx(), fastly, methods) || !JS_DefineProperties(engine->cx(), fastly, Fastly::properties)) { return false; } // fastly:env // first, store the initialized environment vars from Wizer initialized_env.clear(); for (char **env = environ; *env; env++) { const char *entry = *env; const char *eq = entry; while (*eq && *eq != '=') eq++; if (*eq == '=') { initialized_env.emplace(std::string(entry, eq - entry), std::string(eq + 1)); } } RootedValue env_get(engine->cx()); if (!JS_GetProperty(engine->cx(), Fastly::env, "get", &env_get)) { return false; } RootedObject env_builtin(engine->cx(), JS_NewObject(engine->cx(), nullptr)); if (!JS_SetProperty(engine->cx(), env_builtin, "env", env_get)) { return false; } RootedValue env_builtin_val(engine->cx(), JS::ObjectValue(*env_builtin)); if (!engine->define_builtin_module("fastly:env", env_builtin_val)) { return false; } // fastly:compute RootedObject compute_builtin(engine->cx(), JS_NewObject(engine->cx(), nullptr)); auto compute_purge_surrogate_key_fn = JS_NewFunction(engine->cx(), &compute_purge_surrogate_key, 1, 0, "purgeSurrogateKey"); RootedObject compute_purge_surrogate_key_obj( engine->cx(), JS_GetFunctionObject(compute_purge_surrogate_key_fn)); RootedValue compute_purge_surrogate_key_val(engine->cx(), ObjectValue(*compute_purge_surrogate_key_obj)); if (!JS_SetProperty(engine->cx(), compute_builtin, "purgeSurrogateKey", compute_purge_surrogate_key_val)) { return false; } if (!JS_SetProperty(engine->cx(), fastly, "purgeSurrogateKey", compute_purge_surrogate_key_val)) { return false; } auto compute_vcpu_time_get = JS_NewFunction(engine->cx(), &compute_get_vcpu_time, 0, 0, "vCpuTime"); RootedObject compute_vcpu_time_get_obj(engine->cx(), JS_GetFunctionObject(compute_vcpu_time_get)); RootedValue compute_vcpu_time_get_val(engine->cx(), ObjectValue(*compute_vcpu_time_get_obj)); if (!JS_SetProperty(engine->cx(), compute_builtin, "vCpuTime", compute_vcpu_time_get_val)) { return false; } if (!JS_SetProperty(engine->cx(), fastly, "vCpuTime", compute_vcpu_time_get_val)) { return false; } RootedValue compute_builtin_val(engine->cx(), JS::ObjectValue(*compute_builtin)); if (!engine->define_builtin_module("fastly:compute", compute_builtin_val)) { return false; } // fastly:experimental RootedObject experimental(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue experimental_val(engine->cx(), JS::ObjectValue(*experimental)); RootedValue include_bytes_val(engine->cx()); if (!JS_GetProperty(engine->cx(), fastly, "includeBytes", &include_bytes_val)) { return false; } if (!JS_SetProperty(engine->cx(), experimental, "includeBytes", include_bytes_val)) { return false; } auto set_default_backend = JS_NewFunction(engine->cx(), &Fastly::defaultBackend_set, 1, 0, "setDefaultBackend"); RootedObject set_default_backend_obj(engine->cx(), JS_GetFunctionObject(set_default_backend)); RootedValue set_default_backend_val(engine->cx(), ObjectValue(*set_default_backend_obj)); if (!JS_SetProperty(engine->cx(), experimental, "setDefaultBackend", set_default_backend_val)) { return false; } auto enable_debug_logging = JS_NewFunction(engine->cx(), &Fastly::enableDebugLogging, 1, 0, "enableDebugLogging"); RootedObject enable_debug_logging_obj(engine->cx(), JS_GetFunctionObject(enable_debug_logging)); RootedValue enable_debug_logging_val(engine->cx(), ObjectValue(*enable_debug_logging_obj)); if (!JS_SetProperty(engine->cx(), experimental, "enableDebugLogging", enable_debug_logging_val)) { return false; } auto allow_dynamic_backends = JS_NewFunction(engine->cx(), &Fastly::allowDynamicBackends_set, 1, 0, "allowDynamicBackends"); RootedObject allow_dynamic_backends_obj(engine->cx(), JS_GetFunctionObject(allow_dynamic_backends)); RootedValue allow_dynamic_backends_val(engine->cx(), ObjectValue(*allow_dynamic_backends_obj)); if (!JS_SetProperty(engine->cx(), experimental, "allowDynamicBackends", allow_dynamic_backends_val)) { return false; } auto set_reusable_sandbox_options = JS_NewFunction( engine->cx(), &Fastly::setReusableSandboxOptions, 1, 0, "setReusableSandboxOptions"); RootedObject set_reusable_sandbox_options_obj(engine->cx(), JS_GetFunctionObject(set_reusable_sandbox_options)); RootedValue set_reusable_sandbox_options_val(engine->cx(), ObjectValue(*set_reusable_sandbox_options_obj)); if (!JS_SetProperty(engine->cx(), experimental, "setReusableSandboxOptions", set_reusable_sandbox_options_val)) { return false; } RootedString version_str( engine->cx(), JS_NewStringCopyN(engine->cx(), RUNTIME_VERSION, strlen(RUNTIME_VERSION))); RootedValue version_str_val(engine->cx(), StringValue(version_str)); if (!JS_SetProperty(engine->cx(), experimental, "sdkVersion", version_str_val)) { return false; } if (!engine->define_builtin_module("fastly:experimental", experimental_val)) { return false; } // fastly:geo RootedValue get_geolocation_for_ip_address_val(engine->cx()); if (!JS_GetProperty(engine->cx(), fastly, "getGeolocationForIpAddress", &get_geolocation_for_ip_address_val)) { return false; } RootedObject geo_builtin(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue geo_builtin_val(engine->cx(), JS::ObjectValue(*geo_builtin)); if (!JS_SetProperty(engine->cx(), geo_builtin, "getGeolocationForIpAddress", get_geolocation_for_ip_address_val)) { return false; } if (!engine->define_builtin_module("fastly:geolocation", geo_builtin_val)) { return false; } // fastly:fanout RootedObject fanout(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue fanout_val(engine->cx(), JS::ObjectValue(*fanout)); RootedValue create_fanout_handoff_val(engine->cx()); if (!JS_GetProperty(engine->cx(), fastly, "createFanoutHandoff", &create_fanout_handoff_val)) { return false; } if (!JS_SetProperty(engine->cx(), fanout, "createFanoutHandoff", create_fanout_handoff_val)) { return false; } if (!engine->define_builtin_module("fastly:fanout", fanout_val)) { return false; } // fastly:security RootedValue inspect_val(engine->cx()); if (!JS_GetProperty(engine->cx(), fastly, "inspect", &inspect_val)) { return false; } RootedObject security_builtin(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue security_builtin_val(engine->cx(), JS::ObjectValue(*security_builtin)); if (!JS_SetProperty(engine->cx(), security_builtin, "inspect", inspect_val)) { return false; } if (!engine->define_builtin_module("fastly:security", security_builtin_val)) { return false; } // fastly:websocket RootedObject websocket(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue websocket_val(engine->cx(), JS::ObjectValue(*websocket)); RootedValue create_websocket_handoff_val(engine->cx()); if (!JS_GetProperty(engine->cx(), fastly, "createWebsocketHandoff", &create_websocket_handoff_val)) { return false; } if (!JS_SetProperty(engine->cx(), websocket, "createWebsocketHandoff", create_websocket_handoff_val)) { return false; } if (!engine->define_builtin_module("fastly:websocket", websocket_val)) { return false; } // debugMessages for debug-only builds #ifdef DEBUG debug_messages.clear(); #endif return true; } // We currently support five types of body inputs: // - byte sequence // - buffer source // - USV strings // - URLSearchParams // After the other other options are checked explicitly, all other inputs are // encoded to a UTF8 string to be treated as a USV string. // TODO: Support the other possible inputs to Body. JS::Result> convertBodyInit(JSContext *cx, JS::HandleValue bodyInit) { JS::RootedObject bodyObj(cx, bodyInit.isObject() ? &bodyInit.toObject() : nullptr); JS::UniqueChars buf; size_t length; if (bodyObj && JS_IsArrayBufferViewObject(bodyObj)) { length = JS_GetArrayBufferViewByteLength(bodyObj); buf.reset(reinterpret_cast(JS_malloc(cx, length))); // `maybeNoGC` needs to be populated for the lifetime of `buf` because // short typed arrays have inline data which can move on GC, so assert // that no GC happens. (Which it doesn't, because we're not allocating // before `buf` goes out of scope.) JS::AutoCheckCannotGC noGC; bool is_shared; auto *data = JS_GetArrayBufferViewData(bodyObj, &is_shared, noGC); std::memcpy(buf.get(), data, length); MOZ_ASSERT(!is_shared); return JS::Result>(std::make_tuple(std::move(buf), length)); } else if (bodyObj && JS::IsArrayBufferObject(bodyObj)) { bool is_shared; uint8_t *bytes; JS::GetArrayBufferLengthAndData(bodyObj, &length, &is_shared, &bytes); MOZ_ASSERT(!is_shared); buf.reset(reinterpret_cast(JS_malloc(cx, length))); std::memcpy(buf.get(), bytes, length); return JS::Result>(std::make_tuple(std::move(buf), length)); } else if (bodyObj && URLSearchParams::is_instance(bodyObj)) { jsurl::SpecSlice slice = URLSearchParams::serialize(cx, bodyObj); buf.reset(reinterpret_cast(JS_malloc(cx, slice.len))); std::memcpy(buf.get(), slice.data, slice.len); length = slice.len; return JS::Result>(std::make_tuple(std::move(buf), length)); } else { // Convert into a String following https://tc39.es/ecma262/#sec-tostring auto str = core::encode(cx, bodyInit); buf = std::move(str.ptr); length = str.len; if (!buf) { return JS::Result>(JS::Error()); } return JS::Result>(std::make_tuple(std::move(buf), length)); } abort(); } } // namespace fastly::fastly void fastly_push_debug_message(std::string msg) { #ifdef DEBUG if (fastly::fastly::DEBUG_LOGGING_ENABLED) { // Log to both stderr and debug message log fprintf(stderr, "%.*s\n", static_cast(msg.size()), msg.data()); fflush(stderr); debug_messages.push_back(msg); } #endif } ================================================ FILE: runtime/fastly/builtins/fastly.h ================================================ #ifndef FASTLY_FASTLY_H #define FASTLY_FASTLY_H #include "../../StarlingMonkey/builtins/web/url.h" #include "../host-api/host_api_fastly.h" #include "./fetch/request-response.h" #include "builtin.h" #include "extension-api.h" #include "fastly.h" #include "host_api.h" namespace fastly::fastly { extern bool DEBUG_LOGGING_ENABLED; extern bool ENABLE_EXPERIMENTAL_HTTP_CACHE; class Env : public builtins::BuiltinNoConstructor { private: static bool env_get(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "Env"; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static JSObject *create(JSContext *cx); }; class ReusableSandboxOptions { public: ReusableSandboxOptions() = default; ReusableSandboxOptions(const ReusableSandboxOptions &) = delete; ReusableSandboxOptions &operator=(const ReusableSandboxOptions &) = delete; std::optional max_requests() const { return max_requests_; } bool set_max_requests(uint32_t max_requests) { if (frozen_) { return false; } max_requests_ = max_requests; return true; } std::optional between_request_timeout() const { return between_request_timeout_; } bool set_between_request_timeout(std::chrono::milliseconds timeout) { if (frozen_) { return false; } between_request_timeout_ = timeout; return true; } std::optional max_memory_mib() const { return max_memory_mib_; } bool set_max_memory_mib(uint32_t max_memory_mib) { if (frozen_) { return false; } max_memory_mib_ = max_memory_mib; return true; } std::optional sandbox_timeout() const { return sandbox_timeout_; } bool set_sandbox_timeout(std::chrono::milliseconds timeout) { if (frozen_) { return false; } sandbox_timeout_ = timeout; return true; } bool frozen() const { return frozen_; } void freeze() { frozen_ = true; } private: bool frozen_ = false; std::optional max_requests_; std::optional between_request_timeout_; std::optional max_memory_mib_; std::optional sandbox_timeout_; }; class Fastly : public builtins::BuiltinNoConstructor { private: static bool log(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "Fastly"; static JS::PersistentRooted env; static JS::PersistentRooted baseURL; static JS::PersistentRooted defaultBackend; static bool allowDynamicBackends; static host_api::BackendConfig defaultDynamicBackendConfig; static ReusableSandboxOptions reusableSandboxOptions; static const JSPropertySpec properties[]; static bool createFanoutHandoff(JSContext *cx, unsigned argc, JS::Value *vp); static bool createWebsocketHandoff(JSContext *cx, unsigned argc, JS::Value *vp); static bool now(JSContext *cx, unsigned argc, JS::Value *vp); static bool dump(JSContext *cx, unsigned argc, JS::Value *vp); static bool enableDebugLogging(JSContext *cx, unsigned argc, JS::Value *vp); static bool getGeolocationForIpAddress(JSContext *cx, unsigned argc, JS::Value *vp); static bool getLogger(JSContext *cx, unsigned argc, JS::Value *vp); static bool includeBytes(JSContext *cx, unsigned argc, JS::Value *vp); static bool version_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool env_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool baseURL_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool baseURL_set(JSContext *cx, unsigned argc, JS::Value *vp); static bool defaultBackend_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool defaultBackend_set(JSContext *cx, unsigned argc, JS::Value *vp); static bool allowDynamicBackends_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool allowDynamicBackends_set(JSContext *cx, unsigned argc, JS::Value *vp); static bool inspect(JSContext *cx, unsigned argc, JS::Value *vp); static bool setReusableSandboxOptions(JSContext *cx, unsigned argc, JS::Value *vp); }; JS::Result> convertBodyInit(JSContext *cx, JS::HandleValue bodyInit); inline bool get_fastly_object(api::Engine *engine, JS::MutableHandleObject out) { JS::RootedValue fastly_val(engine->cx()); if (!JS_GetProperty(engine->cx(), engine->global(), "fastly", &fastly_val)) { return false; } if (fastly_val.isObject()) { out.set(&fastly_val.toObject()); return true; } JS::RootedObject fastly_obj(engine->cx(), JS_NewPlainObject(engine->cx())); if (!fastly_obj) { return false; } if (!JS_DefineProperty(engine->cx(), engine->global(), "fastly", fastly_obj, 0)) { return false; } out.set(fastly_obj); return true; } /** * Debug only logging system, adding messages to `fastly.debugMessages` * * This is useful for debugging compute, allowing messages to be inlined into the response in test * case debugging, where other logging systems may introduce greater latency than this. */ } // namespace fastly::fastly void fastly_push_debug_message(std::string msg); #endif ================================================ FILE: runtime/fastly/builtins/fetch/fetch.cpp ================================================ #include "fetch.h" #include "../../../StarlingMonkey/builtins/web/fetch/headers.h" #include "../../../StarlingMonkey/builtins/web/streams/native-stream-sink.h" #include "../../../StarlingMonkey/builtins/web/streams/native-stream-source.h" #include "../backend.h" #include "../body.h" #include "../cache-override.h" #include "../fastly.h" #include "../fetch-event.h" #include "../image-optimizer.h" #include "./request-response.h" #include "builtin.h" #include "encode.h" #include "extension-api.h" #include "picosha2.h" using builtins::web::streams::NativeStreamSink; using builtins::web::streams::NativeStreamSource; using fastly::FastlyGetErrorMessage; using fastly::backend::Backend; using fastly::body::FastlyBody; using fastly::cache_override::CacheOverride; using fastly::fastly::Fastly; using fastly::fetch::ENGINE; using fastly::fetch::Request; using fastly::fetch::RequestOrResponse; using fastly::fetch::Response; using fastly::fetch_event::FetchEvent; namespace { class FetchTask final : public api::AsyncTask { Heap request_; Heap promise_; public: explicit FetchTask(host_api::HttpPendingReq::Handle handle, JS::HandleObject request, JS::HandleObject promise) : request_(request), promise_(promise) { if (static_cast(handle) < 0) abort(); handle_ = static_cast(handle); } [[nodiscard]] bool run(api::Engine *engine) override { JSContext *cx = engine->cx(); const RootedObject request(cx, request_); const RootedValue promise(cx, JS::ObjectValue(*promise_)); return RequestOrResponse::process_pending_request(cx, handle_, request, promise); } [[nodiscard]] bool cancel(api::Engine *engine) override { return false; } void trace(JSTracer *trc) override { TraceEdge(trc, &request_, "Fetch request"); TraceEdge(trc, &promise_, "Fetch promise"); } }; template JSObject *internal_method_then(JSContext *cx, JS::HandleObject promise, JS::HandleObject receiver, const JS::HandleValue extra = UndefinedHandleValue) { JS::RootedObject then_handler_obj(cx, create_internal_method(cx, receiver, extra)); if (!then_handler_obj) { return nullptr; } JS::RootedObject catch_handler_obj(cx, create_internal_method(cx, receiver, extra)); if (!catch_handler_obj) { return nullptr; } JS::RootedObject return_promise( cx, JS::CallOriginalPromiseThen(cx, promise, then_handler_obj, catch_handler_obj)); if (!return_promise) { return nullptr; } return return_promise; } JSString *get_backend(JSContext *cx, JS::HandleObject request) { RootedString backend(cx, RequestOrResponse::backend(request)); if (!backend) { if (Fastly::allowDynamicBackends) { JS::RootedObject dynamicBackend(cx, Backend::create(cx, request)); if (!dynamicBackend) { return nullptr; } backend.set(Backend::name(cx, dynamicBackend)); } else { backend = Fastly::defaultBackend; if (!backend) { auto handle = Request::request_handle(request); auto res = handle.get_uri(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); } else { JS_ReportErrorLatin1(cx, "No backend specified for request with url %s. " "Must provide a `backend` property on the `init` object " "passed to either `new Request()` or `fetch`", res.unwrap().begin()); } return nullptr; } } } return backend; } bool must_use_guest_caching(JSContext *cx, HandleObject request) { JS::RootedObject cache_override( cx, JS::GetReservedSlot(request, static_cast(Request::Slots::CacheOverride)) .toObjectOrNull()); if (cache_override) { return CacheOverride::beforeSend(cache_override) || CacheOverride::afterSend(cache_override); } return false; } bool http_caching_unsupported = false; enum CachingMode { Guest, Host, ImageOptimizer }; bool get_caching_mode(JSContext *cx, HandleObject request, CachingMode *caching_mode) { *caching_mode = CachingMode::Guest; // Check for pass cache override MOZ_ASSERT(Request::is_instance(request)); JS::RootedObject cache_override( cx, JS::GetReservedSlot(request, static_cast(Request::Slots::CacheOverride)) .toObjectOrNull()); if (cache_override) { if (CacheOverride::mode(cache_override) == CacheOverride::CacheOverrideMode::Pass) { // Pass requests have to go through the host for now *caching_mode = CachingMode::Host; return true; } } // Check for PURGE method RootedString method_str(cx, Request::method(cx, request)); bool is_purge = false; if (method_str && !JS_StringEqualsLiteral(cx, method_str, "PURGE", &is_purge)) { return false; } if (is_purge) { // We don't yet implement guest-side URL purges *caching_mode = CachingMode::Host; return true; } // Requests meant for Image Optimizer should not be cached at this point, // as the caching behavior is determined by the origin image, which is // fetched after the request reaches the Image Optimizer WASM service. // The WASM service uses cache_on_behalf to insert the result into // the service's cache. auto image_optimizer_opts = JS::GetReservedSlot(request, static_cast(Request::Slots::ImageOptimizerOptions)); if (!image_optimizer_opts.isNullOrUndefined()) { *caching_mode = CachingMode::ImageOptimizer; return true; } // If we previously found guest caching unsupported then remember that if (http_caching_unsupported || !fastly::fastly::ENABLE_EXPERIMENTAL_HTTP_CACHE) { if (must_use_guest_caching(cx, request)) { if (!fastly::fastly::ENABLE_EXPERIMENTAL_HTTP_CACHE) { JS_ReportErrorASCII(cx, "HTTP caching API is not enabled for JavaScript; enable it with " "the --enable-http-cache flag " "to the js-compute build command, or contact support for help"); } else { JS_ReportErrorASCII( cx, "HTTP caching API is not enabled for this service; please contact support for help"); } return false; } *caching_mode = CachingMode::Host; return true; } // Check if we must use host caching by checking if guest caching is unsupported auto request_handle = Request::request_handle(request); auto res = request_handle.is_cacheable(); if (auto *err = res.to_err()) { if (host_api::error_is_unsupported(*err)) { http_caching_unsupported = true; // Guest-side caching is unsupported, so we must use host caching. // If we have hooks we must fail since they require guest caching. if (must_use_guest_caching(cx, request)) { JS_ReportErrorASCII(cx, "HTTP caching API is not enabled; please contact support for help"); return false; } *caching_mode = CachingMode::Host; return true; } HANDLE_ERROR(cx, *err); return false; } return true; } // Sends the request body, resolving the response promise with the response template bool fetch_send_body(JSContext *cx, HandleObject request, JS::MutableHandleValue ret) { RootedString backend(cx, get_backend(cx, request)); if (!backend) { JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } ret.setObject(*promise); return true; } host_api::HostString backend_chars = core::encode(cx, backend); if (!backend_chars.ptr) { JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } ret.setObject(*promise); return true; } // commit the headers into the headers handle if (!RequestOrResponse::commit_headers(cx, request)) { return false; } // cache override only applies to requests with caching if (caching_mode == CachingMode::Host) { if (!Request::apply_cache_override(cx, request)) { return false; } } else { // track requests without caching via CacheEntry false convention // this is used to track that we later must set Fastly headers in this case JS::SetReservedSlot(request, static_cast(RequestOrResponse::Slots::CacheEntry), JS::BooleanValue(false)); } if (!Request::apply_auto_decompress_gzip(cx, request)) { return false; } RootedObject response_promise(cx, JS::NewPromiseObject(cx, nullptr)); if (!response_promise) { return false; } // The image optimizer does not support streaming, so never stream in this case bool streaming = false; if (caching_mode != CachingMode::ImageOptimizer && !RequestOrResponse::maybe_stream_body(cx, request, &streaming)) { return false; } host_api::HttpPendingReq pending_handle; { auto request_handle = Request::request_handle(request); auto body = RequestOrResponse::body_handle(request); host_api::Result res; switch (caching_mode) { case CachingMode::Host: { if (streaming) { res = request_handle.send_async_streaming(body, backend_chars); } else { res = request_handle.send_async(body, backend_chars); } break; } case CachingMode::Guest: res = request_handle.send_async_without_caching(body, backend_chars, streaming); break; case CachingMode::ImageOptimizer: { auto config = reinterpret_cast( JS::GetReservedSlot(request, static_cast(Request::Slots::ImageOptimizerOptions)) .toPrivate()); auto config_str = config->to_string(); auto res = request_handle.send_image_optimizer(body, backend_chars, config_str); if (auto *err = res.to_err()) { HANDLE_IMAGE_OPTIMIZER_ERROR(cx, *err); ret.setObject(*PromiseRejectedWithPendingError(cx)); return true; } JS::RootedObject response(cx, Response::create(cx, request, res.unwrap())); JS::RootedValue response_val(cx, JS::ObjectValue(*response)); if (!JS::ResolvePromise(cx, response_promise, response_val)) { return false; } ret.setObject(*response_promise); return true; } } if (auto *err = res.to_err()) { if (host_api::error_is_generic(*err) || host_api::error_is_invalid_argument(*err)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, fastly::JSMSG_REQUEST_BACKEND_DOES_NOT_EXIST, backend_chars.ptr.get()); } else { HANDLE_ERROR(cx, *err); } ret.setObject(*PromiseRejectedWithPendingError(cx)); return true; } pending_handle = res.unwrap(); } // If the request body is streamed, we need to wait for streaming to complete before marking the // request as pending. if (!streaming) { ENGINE->queue_async_task(new FetchTask(pending_handle.handle, request, response_promise)); } JS::SetReservedSlot(request, static_cast(Request::Slots::PendingRequest), JS::Int32Value(pending_handle.handle)); JS::SetReservedSlot(request, static_cast(Request::Slots::ResponsePromise), JS::ObjectValue(*response_promise)); ret.setObject(*response_promise); return true; } bool fetch_process_cache_hooks_origin_request(JSContext *cx, JS::HandleObject request, JS::HandleValue ret_promise, JS::CallArgs args) { JS::RootedObject ret_promise_obj(cx, &ret_promise.toObject()); JS::SetReservedSlot(request, static_cast(RequestOrResponse::Slots::BodyUsed), JS::BooleanValue(false)); RootedString backend(cx, get_backend(cx, request)); if (!backend) { RejectPromiseWithPendingError(cx, ret_promise_obj); return true; } host_api::HostString backend_chars = core::encode(cx, backend); if (!backend_chars.ptr) { RejectPromiseWithPendingError(cx, ret_promise_obj); return true; } if (!RequestOrResponse::commit_headers(cx, request)) { return false; } if (!Request::apply_auto_decompress_gzip(cx, request)) { return false; } bool streaming = false; if (!RequestOrResponse::maybe_stream_body(cx, request, &streaming)) { RequestOrResponse::close_if_cache_entry(cx, request); return false; } host_api::HttpPendingReq pending_handle; { auto request_handle = Request::request_handle(request); auto body = RequestOrResponse::body_handle(request); auto res = request_handle.send_async_without_caching(body, backend_chars, streaming); if (auto *err = res.to_err()) { if (!RequestOrResponse::close_if_cache_entry(cx, request)) { return false; } if (host_api::error_is_generic(*err) || host_api::error_is_invalid_argument(*err)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, fastly::JSMSG_REQUEST_BACKEND_DOES_NOT_EXIST, backend_chars.ptr.get()); } else { HANDLE_ERROR(cx, *err); } RejectPromiseWithPendingError(cx, ret_promise_obj); return true; } pending_handle = res.unwrap(); } // If the request body is streamed, we need to wait for streaming to complete before marking // the request as pending. if (!streaming) { ENGINE->queue_async_task(new FetchTask(pending_handle.handle, request, ret_promise_obj)); } JS::SetReservedSlot(request, static_cast(Request::Slots::PendingRequest), JS::Int32Value(pending_handle.handle)); return true; } bool fetch_process_cache_hooks_before_send_reject(JSContext *cx, JS::HandleObject request, JS::HandleValue ret_promise, JS::CallArgs args) { if (!RequestOrResponse::close_if_cache_entry(cx, request)) { return false; } JS::RootedObject ret_promise_obj(cx, &ret_promise.toObject()); JS::RejectPromise(cx, ret_promise_obj, args.get(0)); return true; } // Sends the request body, applying the beforeSend and afterSend HTTP caching hook lifecycle bool fetch_send_body_with_cache_hooks(JSContext *cx, HandleObject request, host_api::HttpCacheEntry &cache_entry, JS::MutableHandleValue ret_promise) { auto suggested_backend_request_res = cache_entry.get_suggested_backend_request(); if (auto *err = suggested_backend_request_res.to_err()) { HANDLE_ERROR(cx, *err); ret_promise.setObject(*PromiseRejectedWithPendingError(cx)); return true; } auto backend_request_handle = suggested_backend_request_res.unwrap(); // We carefully patch just the request handle on the original request to refer to the new request // handle. This retains the normal fetch logic that the body will stream then wait for the request // and use the request response, even though the other request details will be different under the // hood, but it is the simplest approach to ensure the original body runs through the correct // request logic. Setting the cache handle on the request indicates this is the situation for a // cache origin request. JS::SetReservedSlot(request, static_cast(Request::Slots::Request), JS::Int32Value(backend_request_handle.handle)); JS::SetReservedSlot(request, static_cast(RequestOrResponse::Slots::CacheEntry), JS::Int32Value(cache_entry.handle)); // Next, if we have a beforeSend hook, we invoke this hook prior to sending to the backend, with // a newly created request object to match this request. This ensures it gets its headers freshly // linked to the new host request correctly without the previous header cache state from the // original request. We lock the body on this request as it is still owned by the initiating // request object. If there is no beforeSend hook, we don't need to create this request. RootedObject cache_override( cx, JS::GetReservedSlot(request, static_cast(Request::Slots::CacheOverride)) .toObjectOrNull()); RootedObject before_send(cx); if (cache_override) { before_send.set(CacheOverride::beforeSend(cache_override)); } JS::RootedObject before_send_promise(cx); if (before_send) { JS::RootedValue ret_val(cx); JS::RootedValueArray<1> args(cx); args[0].set(JS::ObjectValue(*request)); // lock the body temporarily (throwing if already used here, earlier than usual, instead) if (RequestOrResponse::body_used(request)) { JS_ReportErrorASCII(cx, "Body has already been consumed"); ret_promise.setObject(*PromiseRejectedWithPendingError(cx)); } JS::SetReservedSlot(request, static_cast(RequestOrResponse::Slots::BodyUsed), JS::BooleanValue(true)); // now call before_send with the candidate_request, allowing any async work if (!JS::Call(cx, JS::NullHandleValue, before_send, args, &ret_val)) { ret_promise.setObject(*PromiseRejectedWithPendingError(cx)); return true; } before_send_promise.set(JS::CallOriginalPromiseResolve(cx, ret_val)); if (!before_send_promise) { return false; } } else { before_send_promise.set(JS::NewPromiseObject(cx, nullptr)); if (!before_send_promise) { return false; } if (!JS::ResolvePromise(cx, before_send_promise, JS::UndefinedHandleValue)) { return false; } } // when we resume, we pick up in fetch_send_body_with_cache_hooks_origin_request ret_promise.setObject(*JS::NewPromiseObject(cx, nullptr)); JS::RootedObject then_handler_obj( cx, create_internal_method(cx, request, ret_promise)); if (!then_handler_obj) { return false; } JS::RootedObject catch_handler_obj( cx, create_internal_method(cx, request, ret_promise)); if (!catch_handler_obj) { return false; } return JS::AddPromiseReactions(cx, before_send_promise, then_handler_obj, catch_handler_obj); } bool apply_body_transform_transform_then(JSContext *cx, JS::HandleObject fastly_body, JS::HandleValue response, JS::CallArgs args) { JS::RootedValue transformed_array_buffer(cx, args.get(0)); JS::RootedObject transformed_array_buffer_obj(cx); bool valid = false; if (transformed_array_buffer.isObject()) { transformed_array_buffer_obj.set(&transformed_array_buffer.toObject()); if (JS_IsArrayBufferViewObject(transformed_array_buffer_obj) || JS_IsTypedArrayObject(transformed_array_buffer_obj)) { valid = true; } } if (!valid) { JS::RootedObject response_obj(cx, &response.toObject()); JS::RootedValue result_promise_val( cx, JS::GetReservedSlot(response_obj, static_cast(RequestOrResponse::Slots::BodyAllPromise))); JS_ReportErrorASCII( cx, "transformBodyFn did not return a valid array buffer or promise for an array buffer"); return false; } JS::RootedValueArray<1> append_args(cx); append_args[0].setObject(*transformed_array_buffer_obj); JS::RootedValue rval(cx); if (!JS::Call(cx, fastly_body, "append", append_args, &rval)) { return false; } if (!JS::Call(cx, fastly_body, "close", JS::HandleValueArray::empty(), &rval)) { return false; } return true; } // These are constructed as thens that can return promises to extend the outer promise bool apply_body_transform_response_array_buffer_then(JSContext *cx, JS::HandleObject fastly_body, JS::HandleValue response, JS::CallArgs args) { JS::RootedObject response_obj(cx, &response.toObject()); JS::RootedObject response_transform( cx, &JS::GetReservedSlot(response_obj, static_cast(Response::Slots::CacheBodyTransform)) .toObject()); MOZ_ASSERT(response_transform); JS::RootedObject array_buffer(cx, &args.get(0).toObject()); JS::RootedObject transform_fn_obj( cx, &JS::GetReservedSlot(response_obj, static_cast(Response::Slots::CacheBodyTransform)) .toObject()); JS::RootedValueArray<1> transform_args(cx); transform_args[0].setObject(*array_buffer); JS::RootedValue transform_ret(cx); if (!JS::Call(cx, JS::NullHandleValue, transform_fn_obj, transform_args, &transform_ret)) { return false; } JS::RootedObject transform_ret_promise(cx, JS::CallOriginalPromiseResolve(cx, transform_ret)); if (!transform_ret_promise) { return false; } JS::RootedObject transform_then( cx, create_internal_method(cx, fastly_body, response)); if (!transform_then) { return false; } JS::RootedObject ret_promise( cx, JS::CallOriginalPromiseThen(cx, transform_ret_promise, transform_then, nullptr)); args.rval().setObject(*ret_promise); return true; } bool apply_body_transform_catch_handler(JSContext *cx, JS::HandleObject fastly_body, JS::HandleValue response, JS::CallArgs args) { JS::RootedValue rval(cx); if (!JS::Call(cx, fastly_body, "abandon", JS::HandleValueArray::empty(), &rval)) { return false; } // "rethrow" the error JS_SetPendingException(cx, args.get(0), JS::ExceptionStackBehavior::DoNotCapture); return false; } bool apply_body_transform(JSContext *cx, JS::HandleValue response, host_api::HttpBody into_body, JS::MutableHandleObject ret_promise) { JS::RootedObject response_obj(cx, &response.toObject()); // Get the entire body from the response (asynchronously) JS::Value array_buffer_ret; JS::CallArgs args = JS::CallArgsFromVp(0, &array_buffer_ret); if (!RequestOrResponse::bodyAll( cx, args, response_obj)) { return false; } JS::RootedValue array_buffer(cx, array_buffer_ret); JS::RootedObject array_buffer_promise(cx, JS::CallOriginalPromiseResolve(cx, array_buffer)); if (!array_buffer_promise) { return false; } JS::RootedObject fastly_body( cx, FastlyBody::create(cx, reinterpret_cast(into_body.handle))); if (!fastly_body) { return false; } JS::RootedObject response_array_buffer_then_obj( cx, create_internal_method(cx, fastly_body, response)); if (!response_array_buffer_then_obj) { return false; } JS::RootedObject catch_handler_obj( cx, create_internal_method(cx, fastly_body, response)); if (!catch_handler_obj) { return false; } JS::RootedObject body_transform_promise( cx, JS::CallOriginalPromiseThen(cx, array_buffer_promise, response_array_buffer_then_obj, nullptr)); if (!body_transform_promise) { return false; } JS::RootedObject body_transform_promise_with_exception_handling( cx, JS::CallOriginalPromiseThen(cx, body_transform_promise, nullptr, catch_handler_obj)); if (!body_transform_promise_with_exception_handling) { return false; } ret_promise.set(body_transform_promise_with_exception_handling); return true; // Ideally we would support transform streams here in future... // // Create the stream source from the response body // JS::RootedObject body_stream_in(cx, RequestOrResponse::create_body_stream(cx, response)); // if (!body_stream_in) { // return false; // } // // Create the transform stream, and extract its readable and writable end objects // JS::RootedValue transform_stream( // cx, // JS::GetReservedSlot(response, // static_cast(Response::Slots::CacheBodyTransform))); // JS::RootedObject transform_stream_obj(cx, &transform_stream.toObject()); // JS::RootedValue transform_readable(cx); // if (!JS_GetProperty(cx, transform_stream_obj, "readable", &transform_readable)) { // return false; // } // JS::RootedValue transform_writable(cx); // if (!JS_GetProperty(cx, transform_stream_obj, "writable", &transform_writable)) { // return false; // } // // Pipe the incoming body stream into the writable end of the transform stream // JS::RootedValueArray<1> args(cx); // args[0].set(transform_writable); // JS::RootedValue pipe_ret(cx); // if (!JS::Call(cx, body_stream_in, "pipeTo", args, &pipe_ret)) { // return false; // } // // Pipe the readable end of the transform stream into the into_body, with the completion // handler // // on error or success // JS::RootedObject fastly_body( // cx, FastlyBody::create(cx, reinterpret_cast(into_body.handle))); // if (!fastly_body) { // return false; // } // JS::RootedObject into_response( // cx, JS_NewObjectWithGivenProto(cx, &Response::class_, Response::proto_obj)); // if (!into_response) { // return false; // } // if (!Response::create( // cx, into_response, Response::response_handle(response), into_body, true, nullptr, // JS::GetReservedSlot(response, static_cast(Slots::Backend)).toString())) { // return false; // } // JS::RootedObject body_stream(cx, RequestOrResponse::body_stream(self)); // if (!body_stream) { // body_stream = RequestOrResponse::create_body_stream(cx, self); // if (!body_stream) // return false; // } // // JS::RootedObject sink(cx, NativeStreamSink::create(cx, fastly_body, // JS::UndefinedHandleValue, // // body_sink_write_algorithm, // // body_sink_close_algorithm, // // body_sink_abort_algorithm)); // // if (!sink) { // // return false; // // } // JS::RootedObject transform_readable_obj(cx, &transform_readable.toObject()); // JS::RootedValueArray<1> pipeToArgs(cx); // // pipeToArgs[0].setObject(*sink); // pipeToArgs[0].setObject(*insert_response); // JS::RootedValue pipe_promise(cx); // if (!JS::Call(cx, transform_readable_obj, "pipeTo", pipeToArgs, &pipe_promise)) { // return false; // } // JS::RootedObject pipe_promise_obj(cx, &pipe_promise.toObject()); // if (then_or_catch_handler != nullptr) { // JS::RootedObject then_or_catch_handler_obj( // cx, create_internal_method(cx, response)); // if (!then_or_catch_handler_obj) { // return false; // } // if (!JS::AddPromiseReactions(cx, pipe_promise_obj, then_or_catch_handler_obj, // then_or_catch_handler_obj)) { // return false; // } // } // return true; } bool background_cleanup_handler(JSContext *cx, JS::HandleObject request, JS::HandleValue promise_val, JS::CallArgs args) { // we follow the Rust implementation calling "close" instead of "transaction_abandon" here // this could be reconsidered in future if alternative semantics are required RequestOrResponse::close_if_cache_entry(cx, request); ENGINE->decr_event_loop_interest(); return true; } bool background_revalidation_then_handler(JSContext *cx, JS::HandleObject request, JS::HandleValue extra, JS::CallArgs args) { auto response = args.get(0); RootedObject response_obj(cx, &response.toObject()); auto cache_entry = RequestOrResponse::take_cache_entry(response_obj, std::nullopt).value(); auto storage_action = Response::storage_action(response_obj).value(); auto cache_write_options = Response::override_cache_options(response_obj); MOZ_ASSERT(cache_write_options); // Mark interest as complete for this phase. We will create new event interest for the body // streaming promise shortly if needed to simplify return and error paths in this function. ENGINE->decr_event_loop_interest(); switch (storage_action) { case host_api::HttpStorageAction::Insert: { auto body_res = cache_entry.transaction_insert(Response::response_handle(response_obj), cache_write_options); if (auto *err = body_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body = body_res.unwrap(); if (!Response::has_body_transform(response_obj)) { auto append_res = body.append(RequestOrResponse::body_handle(response_obj)); if (auto *err = append_res.to_err()) { HANDLE_ERROR(cx, *err); JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } auto close_res = body.close(); if (auto *err = close_res.to_err()) { HANDLE_ERROR(cx, *err); JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } return true; } JS::RootedObject ret_promise(cx); if (!apply_body_transform(cx, response, body, &ret_promise)) { return false; } JS::RootedObject then_or_catch_handler_obj( cx, create_internal_method(cx, response_obj)); if (!then_or_catch_handler_obj) { return false; } if (!JS::AddPromiseReactions(cx, ret_promise, then_or_catch_handler_obj, then_or_catch_handler_obj)) { return false; } break; } case host_api::HttpStorageAction::Update: { auto res = cache_entry.transaction_update(Response::response_handle(response_obj), cache_write_options); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } break; } case host_api::HttpStorageAction::DoNotStore: { auto res = cache_entry.transaction_abandon(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } break; } case host_api::HttpStorageAction::RecordUncacheable: { auto res = cache_entry.transaction_record_not_cacheable(cache_write_options->max_age_ns.value(), cache_write_options->vary_rule); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } break; } default: MOZ_ASSERT_UNREACHABLE(); } return true; } std::optional get_found_response(JSContext *cx, host_api::HttpCacheEntry &cache_entry, JS::HandleObject request, JS::HandleValue maybe_candidate_response, bool transform_for_client) { auto found_res = cache_entry.get_found_response(transform_for_client); if (auto *err = found_res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } if (!found_res.unwrap().has_value()) { return std::nullopt; } auto found = found_res.unwrap().value(); RootedObject response(cx, Response::create(cx, request, found)); if (!response) { return nullptr; } // copy cache options from candidate response to response host_api::HttpCacheWriteOptions *override_cache_options; if (maybe_candidate_response.isObject()) { override_cache_options = Response::take_override_cache_options(&maybe_candidate_response.toObject()); } else { // Perhaps we can consider making these hostcalls lazy, requires a Response state enum to know // we are in a state we can do this and then keeping the cache handle around, where it is not // yet clear if holding handles for longer periods on responses is okay. override_cache_options = new host_api::HttpCacheWriteOptions(); auto age_res = cache_entry.get_age_ns(); if (auto *err = age_res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } override_cache_options->initial_age_ns = age_res.unwrap(); auto max_age_ns = cache_entry.get_max_age_ns(); if (auto *err = max_age_ns.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } override_cache_options->max_age_ns = max_age_ns.unwrap(); auto swr_res = cache_entry.get_stale_while_revalidate_ns(); if (auto *err = swr_res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } override_cache_options->stale_while_revalidate_ns = swr_res.unwrap(); auto length_res = cache_entry.get_length(); if (auto *err = length_res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } override_cache_options->length = length_res.unwrap(); auto sensitive_res = cache_entry.get_sensitive_data(); if (auto *err = sensitive_res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } override_cache_options->sensitive_data = sensitive_res.unwrap(); auto vary_res = cache_entry.get_vary_rule(); if (auto *err = vary_res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } override_cache_options->vary_rule = std::move(vary_res.unwrap()); auto surrogate_keys_res = cache_entry.get_surrogate_keys(); if (auto *err = surrogate_keys_res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } override_cache_options->surrogate_keys = std::move(surrogate_keys_res.unwrap()); } JS::SetReservedSlot(response, static_cast(Response::Slots::OverrideCacheWriteOptions), JS::PrivateValue(reinterpret_cast(override_cache_options))); return response; } bool stream_back_transform_fulfill(JSContext *cx, JS::HandleObject found_response, JS::HandleValue extra, JS::CallArgs args) { args.rval().setObject(*found_response); return true; } bool stream_back_then_handler(JSContext *cx, JS::HandleObject request, JS::HandleValue extra, JS::CallArgs args) { JS::RootedValue response(cx, args.get(0)); RootedObject response_obj(cx, &response.toObject()); auto cache_entry = RequestOrResponse::take_cache_entry(response_obj, false).value(); auto storage_action = Response::storage_action(response_obj).value(); // Override cache write options is set to the final cache write options at the end of the // response process. auto cache_write_options = Response::override_cache_options(response_obj); MOZ_ASSERT(cache_write_options); switch (storage_action) { case host_api::HttpStorageAction::Insert: { auto insert_res = cache_entry.transaction_insert_and_stream_back( Response::response_handle(response_obj), cache_write_options); if (auto *err = insert_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto [body, cache_entry] = insert_res.unwrap(); if (!Response::has_body_transform(response_obj)) { auto append_res = body.append(RequestOrResponse::body_handle(response_obj)); if (auto *err = append_res.to_err()) { HANDLE_ERROR(cx, *err); JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } auto close_res = body.close(); if (auto *err = close_res.to_err()) { HANDLE_ERROR(cx, *err); JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } auto found_response = get_found_response(cx, cache_entry, request, response, false); MOZ_ASSERT(found_response.has_value()); if (!found_response.value()) { JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } // update response to be the new response, effectively disposing the candidate response response_obj.set(found_response.value()); // Return cached response regardless of revalidation status RootedObject response_promise(cx, JS::NewPromiseObject(cx, nullptr)); JS::RootedValue response_val(cx, JS::ObjectValue(*response_obj)); args.rval().setObject(*response_promise); if (!JS::ResolvePromise(cx, response_promise, response_val)) { return false; } break; } // Body transfom // in order to stream from the response object we must unlock it if (!Response::has_bodyless_status(response_obj)) { JS::SetReservedSlot(response_obj, static_cast(Response::Slots::HasBody), JS::TrueValue()); } JS::RootedObject ret_promise(cx); if (!apply_body_transform(cx, response, body, &ret_promise)) { return false; } auto found_response = get_found_response(cx, cache_entry, request, response, false); MOZ_ASSERT(found_response.has_value()); if (!found_response.value()) { JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } JS::RootedObject found_response_obj(cx, found_response.value()); JS::RootedObject then_handler_obj( cx, create_internal_method(cx, found_response_obj)); if (!then_handler_obj) { return false; } JS::RootedObject final_promise( cx, JS::CallOriginalPromiseThen(cx, ret_promise, then_handler_obj, nullptr)); if (!final_promise) { return false; } args.rval().setObject(*final_promise); break; } case host_api::HttpStorageAction::Update: { auto update_res = cache_entry.transaction_update_and_return_fresh( Response::response_handle(response_obj), cache_write_options); if (auto *err = update_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto cache_entry = update_res.unwrap(); auto found_response = get_found_response(cx, cache_entry, request, response, true); MOZ_ASSERT(found_response.has_value()); if (!found_response.value()) { JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } // response becomes a new response response_obj.set(found_response.value()); // Return cached response regardless of revalidation status RootedObject response_promise(cx, JS::NewPromiseObject(cx, nullptr)); JS::RootedValue response_val(cx, JS::ObjectValue(*response_obj)); args.rval().setObject(*response_promise); if (!JS::ResolvePromise(cx, response_promise, response_val)) { return false; } break; } case host_api::HttpStorageAction::DoNotStore: { // promote the CandidateResponse -> body is now readable if (!Response::has_bodyless_status(response_obj)) { JS::SetReservedSlot(response_obj, static_cast(Response::Slots::HasBody), JS::TrueValue()); } auto res = cache_entry.transaction_abandon(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setObject(*response_obj); break; } case host_api::HttpStorageAction::RecordUncacheable: { // promote the CandidateResponse -> body is now readable if (!Response::has_bodyless_status(response_obj)) { JS::SetReservedSlot(response_obj, static_cast(Response::Slots::HasBody), JS::TrueValue()); } auto res = cache_entry.transaction_record_not_cacheable(cache_write_options->max_age_ns.value(), cache_write_options->vary_rule); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setObject(*response_obj); break; } default: MOZ_ASSERT_UNREACHABLE(); } // note the storage action on the final response, since the response went through the cache, // distinct from responses that did not go through this cache lifecycle. // TODO: work out why / if this is needed? // JS::SetReservedSlot(response_obj, static_cast(Response::Slots::StorageAction), // JS::Int32Value(static_cast(storage_action))); // in all cases, we must add the fastly cache headers if (!Response::add_fastly_cache_headers(cx, response_obj, request, cache_entry, "cached response")) { return false; } return true; } bool stream_back_catch_handler(JSContext *cx, JS::HandleObject request, JS::HandleValue promise_val, JS::CallArgs args) { // we follow the Rust implementation calling "close" instead of "transaction_abandon" here // this could be reconsidered in future if alternative semantics are required if (!RequestOrResponse::close_if_cache_entry(cx, request)) { return false; } // "rethrow" the streaming error JS_SetPendingException(cx, args.get(0), JS::ExceptionStackBehavior::DoNotCapture); return false; } } // namespace namespace fastly::fetch { api::Engine *ENGINE; /** * The `fetch` global function * https://fetch.spec.whatwg.org/#fetch-method */ bool fetch(JSContext *cx, unsigned argc, Value *vp) { CallArgs args = CallArgsFromVp(argc, vp); REQUEST_HANDLER_ONLY("fetch") if (!args.requireAtLeast(cx, "fetch", 1)) { return ReturnPromiseRejectedWithPendingError(cx, args); } RootedObject requestInstance( cx, JS_NewObjectWithGivenProto(cx, &Request::class_, Request::proto_obj)); if (!requestInstance) { return false; } RootedObject request(cx, Request::create(cx, requestInstance, args[0], args.get(1))); if (!request) { return ReturnPromiseRejectedWithPendingError(cx, args); } // Determine if we should use guest-side caching CachingMode caching_mode; if (!get_caching_mode(cx, request, &caching_mode)) { return false; } if (caching_mode == CachingMode::Host) { DEBUG_LOG("HTTP Cache: Using traditional fetch without cache API") return fetch_send_body(cx, request, args.rval()); } else if (caching_mode == CachingMode::ImageOptimizer) { return fetch_send_body(cx, request, args.rval()); } // Check if request is actually cacheable bool is_cacheable = false; { auto request_handle = Request::request_handle(request); auto res = request_handle.is_cacheable(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } is_cacheable = res.unwrap(); } // If not cacheable, fallback to non-caching path if (!is_cacheable) { DEBUG_LOG("HTTP Cache: Request not cacheable, using non-caching fetch") return fetch_send_body(cx, request, args.rval()); } // Lookup in cache auto request_handle = Request::request_handle(request); // Convert override cache key to span if present std::vector override_key_hash; JS::RootedValue override_cache_key( cx, JS::GetReservedSlot(request, static_cast(Request::Slots::OverrideCacheKey))); if (override_cache_key.isString()) { auto override_key_str = core::encode(cx, override_cache_key); override_key_hash.resize(32); // SHA256 produces 32 bytes picosha2::hash256(override_key_str.ptr.get(), override_key_str.ptr.get() + override_key_str.size(), override_key_hash.begin(), override_key_hash.end()); } auto transaction_res = host_api::HttpCacheEntry::transaction_lookup(request_handle, override_key_hash); if (auto *err = transaction_res.to_err()) { DEBUG_LOG("HTTP Cache: Transaction lookup error") if (host_api::error_is_limit_exceeded(*err)) { JS_ReportErrorASCII(cx, "HTTP caching limit exceeded"); } else { HANDLE_ERROR(cx, *err); } JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } host_api::HttpCacheEntry cache_entry = transaction_res.unwrap(); // This forces synchronous lookups, but we should be able to abstract a new CacheLookupTask, which // could be fully async based on its handle as an async select task handle, and then we could // support multiple cache lookups in parallel together. auto state_res = cache_entry.get_state(); if (auto *err = state_res.to_err()) { HANDLE_ERROR(cx, *err); JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } auto cache_state = state_res.unwrap(); std::string state_str = std::to_string(cache_state.state); // Check for usable cached response JS::RootedValue no_candidate(cx); auto maybe_response = get_found_response(cx, cache_entry, request, no_candidate, true); if (maybe_response.has_value() && !maybe_response.value()) { JSObject *promise = PromiseRejectedWithPendingError(cx); if (!promise) { return false; } args.rval().setObject(*promise); return true; } if (maybe_response.has_value()) { JS::RootedObject cached_response(cx, maybe_response.value()); if (cache_state.must_insert_or_update()) { // Need to start background revalidation // Queue async task to handle background cache revalidation, ensuring it blocks process // completion RootedValue background_revalidation_promise(cx); if (!fetch_send_body_with_cache_hooks(cx, request, cache_entry, &background_revalidation_promise)) { RequestOrResponse::close_if_cache_entry(cx, request); return false; } JS::RootedObject background_revalidation_promise_obj( cx, &background_revalidation_promise.toObject()); JS::RootedObject ret_promise( cx, internal_method_then( cx, background_revalidation_promise_obj, request)); if (!ret_promise) { RequestOrResponse::close_if_cache_entry(cx, request); return false; } args.rval().setObject(*ret_promise); JS::SetReservedSlot(request, static_cast(Request::Slots::ResponsePromise), JS::ObjectValue(*ret_promise)); // keep the event loop alive until background revalidation completes or errors ENGINE->incr_event_loop_interest(); } else { if (!RequestOrResponse::close_if_cache_entry(cx, request)) { return false; } } // mark the response cache entry as cached for the cached getter RequestOrResponse::take_cache_entry(cached_response, true); // Return cached response regardless of revalidation status if (!Response::add_fastly_cache_headers(cx, cached_response, request, cache_entry, "cached response")) { return false; } RootedObject response_promise(cx, JS::NewPromiseObject(cx, nullptr)); JS::RootedValue response_val(cx, JS::ObjectValue(*cached_response)); args.rval().setObject(*response_promise); return JS::ResolvePromise(cx, response_promise, response_val); } // No valid cached response, need to make backend request if (!cache_state.must_insert_or_update()) { // transaction entry is done if (!RequestOrResponse::close_if_cache_entry(cx, request)) { return false; } // request collapsing has been disabled: pass the original request to the origin without // updating the cache and without caching return fetch_send_body(cx, request, args.rval()); } else { JS::RootedValue stream_back_promise(cx, JS::ObjectValue(*JS::NewPromiseObject(cx, nullptr))); if (!fetch_send_body_with_cache_hooks(cx, request, cache_entry, &stream_back_promise)) { RequestOrResponse::close_if_cache_entry(cx, request); return false; } JS::RootedObject stream_back_promise_obj(cx, &stream_back_promise.toObject()); JS::RootedObject ret_promise( cx, internal_method_then( cx, stream_back_promise_obj, request)); if (!ret_promise) { RequestOrResponse::close_if_cache_entry(cx, request); return false; } JS::SetReservedSlot(request, static_cast(Request::Slots::ResponsePromise), JS::ObjectValue(*ret_promise)); args.rval().setObject(*ret_promise); } return true; } const JSFunctionSpec methods[] = {JS_FN("fetch", fetch, 2, JSPROP_ENUMERATE), JS_FS_END}; bool install(api::Engine *engine) { ENGINE = engine; if (!JS_DefineFunctions(engine->cx(), engine->global(), methods)) { return false; } if (!Request::init_class(ENGINE->cx(), ENGINE->global())) { return false; } if (!Response::init_class(ENGINE->cx(), ENGINE->global())) { return false; } if (!builtins::web::fetch::Headers::init_class(ENGINE->cx(), ENGINE->global())) { return false; } return true; } } // namespace fastly::fetch ================================================ FILE: runtime/fastly/builtins/fetch/fetch.h ================================================ #include "../../../StarlingMonkey/builtins/web/fetch/headers.h" #include "request-response.h" namespace fastly::fetch { extern api::Engine *ENGINE; extern bool http_caching_unsupported; } // namespace fastly::fetch ================================================ FILE: runtime/fastly/builtins/fetch/request-response.cpp ================================================ #include "request-response.h" #include "../../../StarlingMonkey/builtins/web/base64.h" #include "../../../StarlingMonkey/builtins/web/blob.h" #include "../../../StarlingMonkey/builtins/web/form-data/form-data-encoder.h" #include "../../../StarlingMonkey/builtins/web/form-data/form-data-parser.h" #include "../../../StarlingMonkey/builtins/web/form-data/form-data.h" #include "../../../StarlingMonkey/builtins/web/dom-exception.h" #include "../../../StarlingMonkey/builtins/web/fetch/fetch-errors.h" #include "../../../StarlingMonkey/builtins/web/fetch/fetch-utils.h" #include "../../../StarlingMonkey/builtins/web/streams/native-stream-source.h" #include "../../../StarlingMonkey/builtins/web/streams/transform-stream.h" #include "../../../StarlingMonkey/builtins/web/url.h" #include "../../../StarlingMonkey/builtins/web/worker-location.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../../common/ip_octets_to_js_string.h" #include "../../common/normalize_http_method.h" #include "../backend.h" #include "../cache-core.h" #include "../cache-override.h" #include "../cache-simple.h" #include "../fastly.h" #include "../fetch-event.h" #include "../image-optimizer.h" #include "../kv-store.h" #include "extension-api.h" #include "fetch.h" #include "mozilla/ResultVariant.h" #include "js/Array.h" #include "js/ArrayBuffer.h" #include "js/Conversions.h" #include "js/JSON.h" #include "js/Stream.h" #include "picosha2.h" #include #include #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #include "js/experimental/TypedData.h" #include #pragma clang diagnostic pop using builtins::web::blob::Blob; using builtins::web::form_data::FormData; using builtins::web::form_data::MultipartFormData; using namespace std::literals; using builtins::web::base64::valueToJSByteString; using builtins::web::dom_exception::DOMException; using builtins::web::form_data::FormData; using builtins::web::form_data::FormDataParser; using builtins::web::form_data::MultipartFormData; // We use the StarlingMonkey Headers implementation, despite it supporting features that we do // not - specifically the ability to construct headers unassociated with requests and responses. // // StarlingMonkey only relies on this property for one state transition - the one from ContentOnly // to CachedInContent. And this state transition is only called from the `handle_clone()` function. // // We therefore never use handle_clone() and support the same functionality by implementing a new // Request::commit_headers and Response::commit_headers for committing ContentOnly headers into // a given Request or Response headers handle. // // Further, to verify we never call the ContentOnly to CachedInContent state transition, we // implement its host API call of host_api::HttpHeaders::FromEntries as a release unreachable // assert. using builtins::web::fetch::Headers; using builtins::web::streams::NativeStreamSource; using builtins::web::streams::TransformStream; using builtins::web::url::URL; using builtins::web::url::URLSearchParams; using builtins::web::worker_location::WorkerLocation; using fastly::FastlyGetErrorMessage; using fastly::backend::Backend; using fastly::cache_core::CacheEntry; using fastly::cache_override::CacheOverride; using fastly::cache_simple::SimpleCacheEntry; using fastly::fetch_event::FetchEvent; using fastly::kv_store::KVStoreEntry; namespace builtins::web::streams { bool NativeStreamSource::stream_is_body(JSContext *cx, JS::HandleObject stream) { JSObject *stream_source = get_stream_source(cx, stream); return NativeStreamSource::is_instance(stream_source) && fastly::fetch::RequestOrResponse::is_instance(owner(stream_source)); } } // namespace builtins::web::streams namespace fastly::fetch { namespace { bool error_stream_controller_with_pending_exception(JSContext *cx, JS::HandleObject stream) { JS::RootedValue exn(cx); if (!JS_GetPendingException(cx, &exn)) return false; JS_ClearPendingException(cx); RootedValue args(cx); args.set(exn); return JS::ReadableStreamError(cx, stream, args); } constexpr size_t HANDLE_READ_CHUNK_SIZE = 8192; void set_up_shortcutting(JSContext *cx, JS::HandleObject stream, JS::HandleObject to) { // This function is part of a web of code that allows requests and responses // to "shortcut" pipelines down to simple host-side operations, without having // to actually pipe data through to javascript. This covers one of the various // scenarios. Another place to look is `maybe_shortcut_transform_stream_read`. // Part of the reason for having this complexity on our end is so we don't // have to patch StarlingMonkey to get all this working, since it's a Fastly // optimization. JS::RootedObject stream_source(cx, NativeStreamSource::get_stream_source(cx, stream)); JS::RootedObject source_owner(cx, NativeStreamSource::owner(stream_source)); auto body = RequestOrResponse::body_handle(source_owner); JS::SetReservedSlot(to, static_cast(RequestOrResponse::Slots::Body), JS::Int32Value(body.handle)); JS::SetReservedSlot(to, static_cast(RequestOrResponse::Slots::SourceRequest), JS::ObjectValue(*source_owner)); // Ensure that we take the right steps for shortcutting operations on // TransformStreams later on. if (TransformStream::is_ts_readable(cx, stream)) { // But only if the TransformStream isn't used as a mixin by other // builtins. if (!TransformStream::used_as_mixin(TransformStream::ts_from_readable(cx, stream))) { TransformStream::set_readable_used_as_body(cx, stream, to); } } } bool maybe_shortcut_transform_stream_read(JSContext *cx, JS::HandleObject streamSource, JS::HandleObject body_owner, bool *shortcutted) { // If the stream has been piped to a TransformStream whose readable end was // then passed to a Request or Response as the body, we can just append the // entire source body to the destination using a single native hostcall, and // then close the source stream, instead of reading and writing it in // individual chunks. Note that even in situations where multiple streams are // piped to the same destination this is guaranteed to happen in the right // order: ReadableStream#pipeTo locks the destination WritableStream until the // source ReadableStream is closed/canceled, so only one stream can ever be // piped in at the same time. There may be a chain of TransformStreams in // between the source and destination, so we walk the piping chain to find the // final destination. JS::RootedObject pipe_dest(cx, NativeStreamSource::piped_to_transform_stream(streamSource)); if (pipe_dest) { *shortcutted = true; // Walk the chain of TransformStreams to find the final destination JS::RootedObject current_dest(cx, pipe_dest); JS::RootedObject next_dest(cx); while (current_dest) { // Try to find the next TransformStream in the chain JS::RootedObject readable(cx, TransformStream::readable(current_dest)); JS::RootedObject next_source(cx, NativeStreamSource::get_stream_source(cx, readable)); if (next_source) { next_dest.set(NativeStreamSource::piped_to_transform_stream(next_source)); } else { next_dest.set(nullptr); } // If there's no next destination, we've found the last one in the chain if (!next_dest) { // If this is used as a body, we can append directly and close if (TransformStream::readable_used_as_body(current_dest)) { JS::RootedObject dest_owner(cx, TransformStream::owner(current_dest)); if (!RequestOrResponse::append_body(cx, dest_owner, body_owner)) { return false; } JS::RootedObject stream(cx, NativeStreamSource::stream(streamSource)); bool success = JS::ReadableStreamClose(cx, stream); MOZ_RELEASE_ASSERT(success); return true; } // If the last one isn't used as a body it must be doing something else with // the data, so we fall back to reading and writing chunks as normal *shortcutted = false; break; } current_dest.set(next_dest); } } // Fallback: check stored source reference when pipe chain is broken by async operations if (!*shortcutted && RequestOrResponse::is_instance(body_owner)) { JS::Value source_request_val = JS::GetReservedSlot( body_owner, static_cast(RequestOrResponse::Slots::SourceRequest)); if (source_request_val.isObject()) { JS::RootedObject source_request(cx, &source_request_val.toObject()); while (source_request) { JS::RootedObject source_stream(cx, RequestOrResponse::body_stream(source_request)); if (source_stream && NativeStreamSource::stream_is_body(cx, source_stream)) { if (!RequestOrResponse::append_body(cx, body_owner, source_request)) { return false; } bool success = JS::ReadableStreamClose(cx, source_stream); MOZ_RELEASE_ASSERT(success); *shortcutted = true; return true; } // Follow chained Request sources JS::Value next_source_val = JS::GetReservedSlot( source_request, static_cast(RequestOrResponse::Slots::SourceRequest)); if (next_source_val.isObject()) { source_request = &next_source_val.toObject(); } else { break; } } } } return true; } bool process_body_read(JSContext *cx, host_api::HttpBody::Handle handle, JS::HandleObject context, JS::HandleValue body_owner) { MOZ_ASSERT(context); JS::RootedObject streamSource(cx, context); MOZ_ASSERT(NativeStreamSource::is_instance(streamSource)); host_api::HttpBody body(handle); JS::RootedObject owner(cx, NativeStreamSource::owner(streamSource)); JS::RootedObject stream(cx, NativeStreamSource::stream(streamSource)); bool shortcutted = false; JS::RootedObject body_owner_obj(cx, &body_owner.toObject()); if (!maybe_shortcut_transform_stream_read(cx, streamSource, body_owner_obj, &shortcutted)) { return false; } if (shortcutted) { return true; } auto read_res = body.read(HANDLE_READ_CHUNK_SIZE); if (auto *err = read_res.to_err()) { HANDLE_ERROR(cx, *err); return error_stream_controller_with_pending_exception(cx, stream); } auto &chunk = read_res.unwrap(); if (chunk.len == 0) { JS::RootedValue r(cx); return JS::ReadableStreamClose(cx, stream); } // We don't release control of chunk's data until after we've checked that the array buffer // allocation has been successful, as that ensures that the return path frees chunk automatically // when necessary. JS::RootedObject buffer( cx, JS::NewArrayBufferWithContents(cx, chunk.len, chunk.ptr.get(), JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory)); if (!buffer) { return error_stream_controller_with_pending_exception(cx, stream); } // At this point `buffer` has taken full ownership of the chunk's data. std::ignore = chunk.ptr.release(); JS::RootedObject byte_array(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 0, chunk.len)); if (!byte_array) { return false; } RootedValue enqueue_val(cx); enqueue_val.setObject(*byte_array); if (!JS::ReadableStreamEnqueue(cx, stream, enqueue_val)) { return error_stream_controller_with_pending_exception(cx, stream); } return true; } enum StreamState { Complete, Wait, Error }; struct ReadResult { JS::UniqueChars buffer; size_t length; StreamState state; }; // Returns a UniqueChars and the length of that string. The UniqueChars value is not // null-terminated. template ReadResult read_from_handle_all(JSContext *cx, host_api::HttpBody body) { std::vector chunks; size_t bytes_read = 0; bool end_of_stream = true; while (true) { if (async) { auto ready_res = body.is_ready(); if (auto *err = ready_res.to_err()) { HANDLE_ERROR(cx, *err); return {nullptr, 0, StreamState::Error}; } if (!ready_res.unwrap()) { end_of_stream = false; break; } } auto res = body.read(HANDLE_READ_CHUNK_SIZE); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return {nullptr, 0, StreamState::Error}; } auto &chunk = res.unwrap(); if (chunk.len == 0) { break; } bytes_read += chunk.len; chunks.emplace_back(std::move(chunk)); } JS::UniqueChars buf; if (chunks.size() == 0) { return {nullptr, 0, end_of_stream ? StreamState::Complete : StreamState::Wait}; } else if (chunks.size() == 1) { // If there was only one chunk read, reuse that allocation. auto &chunk = chunks.back(); buf = std::move(chunk.ptr); } else { // If there wasn't exactly one chunk read, we'll need to allocate a buffer to store the results. buf.reset(static_cast(JS_string_malloc(cx, bytes_read))); if (!buf) { JS_ReportOutOfMemory(cx); return {nullptr, 0, StreamState::Error}; } char *end = buf.get(); for (auto &chunk : chunks) { end = std::copy(chunk.ptr.get(), chunk.ptr.get() + chunk.len, end); } } return {std::move(buf), bytes_read, end_of_stream ? StreamState::Complete : StreamState::Wait}; } } // namespace bool Response::has_body_transform(JSObject *self) { return !JS::GetReservedSlot(self, static_cast(Slots::CacheBodyTransform)).isUndefined(); } bool Response::add_fastly_cache_headers(JSContext *cx, JS::HandleObject self, JS::HandleObject request, std::optional cache_entry, const char *fun_name) { MOZ_ASSERT(Response::is_instance(self)); // Get response headers object RootedObject headers(cx, Response::headers(cx, self)); if (!headers) { return false; } JS::RootedObject headers_val(cx, headers); // Get cache handle and hits RootedValue res(cx); bool found = false; bool stale = false; if (cache_entry.has_value()) { auto state_res = cache_entry->get_state(); if (auto *err = state_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (state_res.unwrap().is_found()) { found = true; stale = state_res.unwrap().is_stale(); auto hits_res = cache_entry->get_hits(); if (auto *err = hits_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } uint64_t hits = hits_res.unwrap(); JS::RootedString hit_str(cx, JS_NewStringCopyZ(cx, "HIT")); JS::RootedValue hit_str_val(cx, JS::StringValue(hit_str)); JS::RootedValueArray<2> args(cx); args[0].setString(JS_NewStringCopyZ(cx, "x-cache")); args[1].set(hit_str_val); if (!JS::Call(cx, headers_val, "set", args, &res)) { return false; } std::string hits_str = std::to_string(hits); args[0].setString(JS_NewStringCopyZ(cx, "x-cache-hits")); args[1].setString(JS_NewStringCopyN(cx, hits_str.c_str(), hits_str.length())); if (!JS::Call(cx, headers_val, "set", args, &res)) { return false; } } } // Mark cached: found on the response, via the CacheEntry = boolean Response-phase convention slot // reuse (the cache handle was released from the response, promoting it from a CandidateResponse // to a response by the time we get here, which is why it's passed as an optional argument) JS::SetReservedSlot(self, static_cast(Slots::CacheEntry), found && stale ? JS::NullValue() : JS::BooleanValue(found)); if (!found) { JS::RootedValueArray<2> args(cx); args[0].setString(JS_NewStringCopyZ(cx, "x-cache")); args[1].setString(JS_NewStringCopyZ(cx, "MISS")); if (!JS::Call(cx, headers_val, "set", args, &res)) { return false; } args[0].setString(JS_NewStringCopyZ(cx, "x-cache-hits")); args[1].setString(JS_NewStringCopyZ(cx, "0")); if (!JS::Call(cx, headers_val, "set", args, &res)) { return false; } } // Rest of the function handling surrogate headers remains the same JSObject *request_headers = Request::headers(cx, request); if (!request_headers) { return false; } JS::RootedObject request_headers_val(cx, request_headers); JS::RootedValueArray<1> args(cx); args[0].setString(JS_NewStringCopyZ(cx, "Fastly-FF")); if (!JS::Call(cx, request_headers_val, "get", args, &res)) { return false; } bool ff_exists = !res.isUndefined(); args[0].setString(JS_NewStringCopyZ(cx, "Fastly-Debug")); if (!JS::Call(cx, request_headers_val, "get", args, &res)) { return false; } bool debug_exists = !res.isUndefined(); if (!ff_exists && !debug_exists) { JS::RootedValue delete_func(cx); if (!JS_GetProperty(cx, headers_val, "delete", &delete_func)) { return false; } { JS::RootedString key_str(cx, JS_NewStringCopyZ(cx, "Surrogate-Key")); JS::RootedValue key_val(cx, JS::StringValue(key_str)); JS::RootedValue rval(cx); if (!JS::Call(cx, headers_val, delete_func, JS::HandleValueArray(key_val), &rval)) { return false; } } { JS::RootedString key_str(cx, JS_NewStringCopyZ(cx, "Surrogate-Control")); JS::RootedValue key_val(cx, JS::StringValue(key_str)); JS::RootedValue rval(cx); if (!JS::Call(cx, headers_val, delete_func, JS::HandleValueArray(key_val), &rval)) { return false; } } } return true; } bool after_send_then(JSContext *cx, JS::HandleObject response, JS::HandleValue promise, JS::CallArgs args) { JS::RootedObject promise_obj(cx, &promise.toObject()); JS::RootedValue after_send_ret(cx, args.get(0)); if (!after_send_ret.isNullOrUndefined()) { if (!after_send_ret.isObject()) { api::throw_error(cx, api::Errors::TypeError, "Request cache hook", "afterSend()", "return either undefined or an object"); return RejectPromiseWithPendingError(cx, promise_obj); } JS::RootedObject after_send_obj(cx, &after_send_ret.toObject()); JS::RootedValue cache_val(cx); if (!JS_GetProperty(cx, after_send_obj, "cache", &cache_val)) { return RejectPromiseWithPendingError(cx, promise_obj); } // set_cacheable / set_uncacheable if (cache_val.isBoolean()) { if (cache_val.toBoolean()) { if (static_cast( JS::GetReservedSlot(response, static_cast(Response::Slots::StorageAction)) .toInt32()) != host_api::HttpStorageAction::Update) { JS::SetReservedSlot( response, static_cast(Response::Slots::StorageAction), JS::Int32Value(static_cast(host_api::HttpStorageAction::Insert))); } } else { JS::SetReservedSlot( response, static_cast(Response::Slots::StorageAction), JS::Int32Value(static_cast(host_api::HttpStorageAction::DoNotStore))); } } else if (cache_val.isString()) { bool is_uncacheable = false; if (!JS_StringEqualsLiteral(cx, cache_val.toString(), "uncacheable", &is_uncacheable)) { return false; } if (!is_uncacheable) { api::throw_error(cx, api::Errors::TypeError, "Request cache hook", "afterSend()", "return a \'cache\' property value 'uncacheable' when set to a string"); return RejectPromiseWithPendingError(cx, promise_obj); } JS::SetReservedSlot( response, static_cast(Response::Slots::StorageAction), JS::Int32Value(static_cast(host_api::HttpStorageAction::RecordUncacheable))); } else if (!cache_val.isUndefined()) { api::throw_error(cx, api::Errors::TypeError, "Request cache hook", "afterSend()", "return a 'cache' property as either a string or boolean"); return RejectPromiseWithPendingError(cx, promise_obj); } // set_body_transform JS::RootedValue body_transform_val(cx); if (!JS_GetProperty(cx, after_send_obj, "bodyTransformFn", &body_transform_val)) { return RejectPromiseWithPendingError(cx, promise_obj); } if (!body_transform_val.isUndefined()) { bool valid_function = false; if (body_transform_val.isObject()) { JS::RootedObject body_transform_obj(cx, &body_transform_val.toObject()); if (JS_ObjectIsFunction(body_transform_obj)) { valid_function = true; JS::SetReservedSlot(response, static_cast(Response::Slots::CacheBodyTransform), body_transform_val); } } if (!valid_function) { api::throw_error(cx, api::Errors::TypeError, "Request cache hook", "afterSend()", "return a 'bodyTransformFn' property that is a function"); return RejectPromiseWithPendingError(cx, promise_obj); } } } // we set the override cache write options to the final computation, which will then immediately // be used for the transaction insertion, after which it will be cleared. auto cache_write_options = Response::override_cache_options(response); auto suggested_cache_write_options = Response::suggested_cache_options(cx, response); if (!suggested_cache_write_options) { return RejectPromiseWithPendingError(cx, promise_obj); } if (!suggested_cache_write_options->initial_age_ns.has_value()) { return RejectPromiseWithPendingError(cx, promise_obj); } cache_write_options->initial_age_ns = suggested_cache_write_options->initial_age_ns.value(); if (!cache_write_options->max_age_ns.has_value()) { cache_write_options->max_age_ns = suggested_cache_write_options->max_age_ns; } if (!cache_write_options->stale_while_revalidate_ns.has_value()) { cache_write_options->stale_while_revalidate_ns = suggested_cache_write_options->stale_while_revalidate_ns; } if (!cache_write_options->surrogate_keys.has_value()) { cache_write_options->surrogate_keys = std::move(suggested_cache_write_options->surrogate_keys); } if (!cache_write_options->vary_rule.has_value()) { cache_write_options->vary_rule = std::move(suggested_cache_write_options->vary_rule); } if (!cache_write_options->sensitive_data.has_value()) { cache_write_options->sensitive_data = suggested_cache_write_options->sensitive_data; } // we can set the length if there is no body transform if (!Response::has_body_transform(response)) { auto length_res = RequestOrResponse::body_handle(response).known_length(); if (auto *err = length_res.to_err()) { HANDLE_ERROR(cx, *err); return RejectPromiseWithPendingError(cx, promise_obj); } cache_write_options->length = length_res.unwrap(); } delete suggested_cache_write_options; JS::SetReservedSlot(response, static_cast(Response::Slots::SuggestedCacheWriteOptions), JS::UndefinedValue()); JS::RootedValue response_val(cx, JS::ObjectValue(*response)); JS::ResolvePromise(cx, promise_obj, response_val); return true; } bool after_send_catch(JSContext *cx, JS::HandleObject response, JS::HandleValue promise, JS::CallArgs args) { JS::RootedObject promise_obj(cx, &promise.toObject()); if (!RequestOrResponse::close_if_cache_entry(cx, response)) { return false; } JS::RejectPromise(cx, promise_obj, args.get(0)); return true; } bool RequestOrResponse::process_pending_request(JSContext *cx, host_api::HttpPendingReq::Handle handle, JS::HandleObject request, JS::HandleValue promise) { MOZ_ASSERT(Request::is_instance(request)); host_api::HttpPendingReq pending(handle); JS::RootedObject promise_obj(cx, &promise.toObject()); auto res_res = pending.wait(); if (auto *err = res_res.to_err()) { std::string message = std::move(err->message()).value_or("when attempting to fetch resource."); DOMException::raise(cx, message, "NetworkError"); return RejectPromiseWithPendingError(cx, promise_obj); } auto res = res_res.unwrap(); std::optional maybe_cache_entry = RequestOrResponse::cache_entry(request); if (!maybe_cache_entry) { JS::RootedObject response(cx, Response::create(cx, request, res)); // For a request made without caching (via the Request cache handle false convention), we must // add fastly headers to the Response auto maybe_not_cached = JS::GetReservedSlot(request, static_cast(Slots::CacheEntry)); if (maybe_not_cached.isBoolean() && maybe_not_cached.toBoolean() == false) { if (!Response::add_fastly_cache_headers(cx, response, request, std::nullopt, "cached response")) { return false; } } JS::RootedValue response_val(cx, JS::ObjectValue(*response)); return JS::ResolvePromise(cx, promise_obj, response_val); } // after_send lifecycle implementation for a response generated from a request with a cache entry auto cache_entry = maybe_cache_entry.value(); auto suggested_res = cache_entry.prepare_response_for_storage(res.resp); if (auto *err = suggested_res.to_err()) { HANDLE_ERROR(cx, *err); return RejectPromiseWithPendingError(cx, promise_obj); } auto suggested = suggested_res.unwrap(); auto &[suggested_storage_action, suggested_resp] = suggested; // The suggested storage response overrides the original response handle, while retaining the // body handle (i.e. it just gives new headers). res.resp = suggested_resp; // create the candidate response JS::RootedObject response(cx, Response::create(cx, request, res)); // Fastly-specific heuristic: by default, we do not cache responses that set cookies RootedValue result(cx); JS::RootedObject headers(cx, Response::headers(cx, response)); MOZ_ASSERT(headers); JS::RootedValueArray<1> args(cx); JS::RootedString set_cookie_str(cx, JS_NewStringCopyZ(cx, "set-cookie")); args[0].setString(set_cookie_str); if (!JS::Call(cx, headers, "has", args, &result)) { return false; } if (result.isBoolean() && result.toBoolean() == true && suggested_storage_action != host_api::HttpStorageAction::DoNotStore) { suggested_storage_action = host_api::HttpStorageAction::RecordUncacheable; } host_api::HttpCacheWriteOptions *override_cache_options = new host_api::HttpCacheWriteOptions(); JS::SetReservedSlot(response, static_cast(Response::Slots::StorageAction), JS::Int32Value(static_cast(suggested_storage_action))); JS::SetReservedSlot(response, static_cast(RequestOrResponse::Slots::CacheEntry), JS::Int32Value(cache_entry.handle)); // CandidateResponse does not have a body! JS::SetReservedSlot(response, static_cast(RequestOrResponse::Slots::HasBody), JS::FalseValue()); RootedObject cache_override( cx, JS::GetReservedSlot(request, static_cast(Request::Slots::CacheOverride)) .toObjectOrNull()); RootedObject after_send(cx); if (cache_override) { after_send.set(CacheOverride::afterSend(cache_override)); // convert the CacheOverride provided to the request into HttpCacheWriteOptions overrides // that can still be overridden by the candidate reseponse phase host_api::HttpCacheWriteOptions *suggested = nullptr; RootedValue override_ttl(cx, CacheOverride::ttl(cache_override)); // overriding TTL is computed in terms of the original age, so we need the suggested calculation if (!override_ttl.isUndefined()) { if (!suggested) { suggested = Response::suggested_cache_options(cx, response); if (!suggested) { return false; } } uint64_t ttl_ns = static_cast(override_ttl.toInt32() * 1e9); uint64_t initial_age_ns = suggested->initial_age_ns.value(); override_cache_options->max_age_ns = ttl_ns + initial_age_ns; } RootedValue override_swr(cx, CacheOverride::swr(cache_override)); if (!override_swr.isUndefined()) { override_cache_options->stale_while_revalidate_ns = static_cast(override_swr.toInt32() * 1e9); } // overriding surrogate keys composes suggested surrogate keys with the original cache override // space-split keys, so again, use the suggested computation to do this. RootedValue override_surrogate_keys(cx, CacheOverride::surrogate_key(cache_override)); if (!override_surrogate_keys.isUndefined()) { if (!suggested) { suggested = Response::suggested_cache_options(cx, response); if (!suggested) { return false; } } auto str_val = core::encode(cx, override_surrogate_keys); if (!str_val) { return false; } // Get the string data as string_view std::string_view str(str_val.ptr.get(), str_val.len); // Initialize the optional vector override_cache_options->surrogate_keys.emplace(); size_t pos = 0; while (pos < str.length()) { // Skip any leading spaces while (pos < str.length() && str[pos] == ' ') { pos++; } // Find next space size_t space = str.find(' ', pos); // Handle either substring to next space or to end if (space == std::string_view::npos) { if (pos < str.length()) { auto substr = str.substr(pos); override_cache_options->surrogate_keys->push_back(host_api::HostString(substr)); } break; } else { if (space > pos) { auto substr = str.substr(pos, space - pos); override_cache_options->surrogate_keys->push_back(host_api::HostString(substr)); } pos = space + 1; } } } RootedValue override_pci(cx, CacheOverride::pci(cache_override)); if (!override_pci.isUndefined()) { override_cache_options->sensitive_data = override_pci.toBoolean(); } } JS::SetReservedSlot(response, static_cast(Response::Slots::OverrideCacheWriteOptions), JS::PrivateValue(override_cache_options)); JS::RootedObject after_send_promise(cx); if (after_send) { JS::RootedValue ret_val(cx); JS::RootedValueArray<1> args(cx); args[0].set(JS::ObjectValue(*response)); // now call after_send with the candidate_request, allowing any async work if (!JS::Call(cx, JS::NullHandleValue, after_send, args, &ret_val)) { return RejectPromiseWithPendingError(cx, promise_obj); } after_send_promise = JS::RootedObject(cx, JS::CallOriginalPromiseResolve(cx, ret_val)); if (!after_send_promise) { return false; } } else { after_send_promise = JS::NewPromiseObject(cx, nullptr); JS::ResolvePromise(cx, after_send_promise, JS::UndefinedHandleValue); } // when we resume, we pick up the transaction insert JS::RootedObject then_handler_obj(cx, create_internal_method(cx, response, promise)); if (!then_handler_obj) { return false; } JS::RootedObject catch_handler_obj( cx, create_internal_method(cx, response, promise)); if (!catch_handler_obj) { return false; } return JS::AddPromiseReactions(cx, after_send_promise, then_handler_obj, catch_handler_obj); } bool RequestOrResponse::is_instance(JSObject *obj) { return Request::is_instance(obj) || Response::is_instance(obj) || KVStoreEntry::is_instance(obj); } uint32_t RequestOrResponse::handle(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); return static_cast( JS::GetReservedSlot(obj, static_cast(Slots::RequestOrResponse)).toInt32()); } bool RequestOrResponse::has_body(JSObject *obj) { return JS::GetReservedSlot(obj, static_cast(Slots::HasBody)).toBoolean(); } host_api::HttpBody RequestOrResponse::body_handle(JSObject *obj) { return host_api::HttpBody(JS::GetReservedSlot(obj, static_cast(Slots::Body)).toInt32()); } JSObject *RequestOrResponse::body_stream(JSObject *obj) { return JS::GetReservedSlot(obj, static_cast(Slots::BodyStream)).toObjectOrNull(); } JSObject *RequestOrResponse::body_source(JSContext *cx, JS::HandleObject obj) { MOZ_ASSERT(has_body(obj)); JS::RootedObject stream(cx, body_stream(obj)); return NativeStreamSource::get_stream_source(cx, stream); } bool RequestOrResponse::body_used(JSObject *obj) { return JS::GetReservedSlot(obj, static_cast(Slots::BodyUsed)).toBoolean(); } bool RequestOrResponse::mark_body_used(JSContext *cx, JS::HandleObject obj) { MOZ_ASSERT(!body_used(obj)); JS::SetReservedSlot(obj, static_cast(Slots::BodyUsed), JS::BooleanValue(true)); JS::RootedObject stream(cx, body_stream(obj)); if (stream && NativeStreamSource::stream_is_body(cx, stream)) { if (!NativeStreamSource::lock_stream(cx, stream)) { // The only reason why marking the body as used could fail here is that // it's a disturbed ReadableStream. To improve error reporting, we clear // the current exception and throw a better one. JS_ClearPendingException(cx); JS_ReportErrorNumberLatin1(cx, FastlyGetErrorMessage, nullptr, JSMSG_READABLE_STREAM_LOCKED_OR_DISTRUBED); return false; } } return true; } /** * Moves an underlying body handle from one Request/Response object to another. * * Also marks the source object's body as consumed. */ bool RequestOrResponse::move_body_handle(JSContext *cx, JS::HandleObject from, JS::HandleObject to) { MOZ_ASSERT(is_instance(from)); MOZ_ASSERT(is_instance(to)); MOZ_ASSERT(!body_used(from)); // Replace the receiving object's body handle with the body stream source's // underlying handle. // TODO: Let the host know we'll not use the old handle anymore, once Fastly Compute has // a hostcall for that. auto body = body_handle(from); JS::SetReservedSlot(to, static_cast(Slots::Body), JS::Int32Value(body.handle)); // Mark the source's body as used, and the stream as locked to prevent any // future attempts to use the underlying handle we just removed. return mark_body_used(cx, from); } JS::Value RequestOrResponse::url(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); JS::Value val = JS::GetReservedSlot(obj, static_cast(RequestOrResponse::Slots::URL)); MOZ_ASSERT(val.isString()); return val; } void RequestOrResponse::set_url(JSObject *obj, JS::Value url) { MOZ_ASSERT(is_instance(obj)); MOZ_ASSERT(url.isString()); JS::SetReservedSlot(obj, static_cast(RequestOrResponse::Slots::URL), url); } /** * Implementation of the `body is unusable` concept at * https://fetch.spec.whatwg.org/#body-unusable */ bool RequestOrResponse::body_unusable(JSContext *cx, JS::HandleObject body) { MOZ_ASSERT(JS::IsReadableStream(body)); bool disturbed; bool locked; MOZ_RELEASE_ASSERT(JS::ReadableStreamIsDisturbed(cx, body, &disturbed) && JS::ReadableStreamIsLocked(cx, body, &locked)); return disturbed || locked; } /** * Implementation of the `extract a body` algorithm at * https://fetch.spec.whatwg.org/#concept-bodyinit-extract * * Note: our implementation is somewhat different from what the spec describes * in that we immediately write all non-streaming body types to the host instead * of creating a stream for them. We don't have threads, so there's nothing "in * parallel" to be had anyway. * * Note: also includes the steps applying the `Content-Type` header from the * Request and Response constructors in step 36 and 8 of those, respectively. */ bool RequestOrResponse::extract_body(JSContext *cx, JS::HandleObject self, JS::HandleValue body_val) { MOZ_ASSERT(is_instance(self)); MOZ_ASSERT(!has_body(self)); MOZ_ASSERT(!body_val.isNullOrUndefined()); const char *content_type = nullptr; // We currently support five types of body inputs: // - Blob // - byte sequence // - buffer source // - USV strings // - URLSearchParams // - ReadableStream // After the other other options are checked explicitly, all other inputs are // encoded to a UTF8 string to be treated as a USV string. // TODO: Support the other possible inputs to Body. JS::RootedObject body_obj(cx, body_val.isObject() ? &body_val.toObject() : nullptr); host_api::HostString host_type_str; if (Blob::is_instance(body_obj)) { RootedValue stream(cx); if (!Blob::stream(cx, body_obj, &stream)) { return false; } MOZ_ASSERT(stream.isObject()); JS_SetReservedSlot(self, static_cast(RequestOrResponse::Slots::BodyStream), stream); // TODO: Set content-length header from known body extracted size // size_t content_length = Blob::blob_size(body_obj); JS::RootedString type_str(cx, Blob::type(body_obj)); if (JS::GetStringLength(type_str) > 0) { host_type_str = core::encode(cx, type_str); MOZ_ASSERT(host_type_str); content_type = host_type_str.begin(); } } else if (FormData::is_instance(body_obj)) { RootedObject encoder(cx, MultipartFormData::create(cx, body_obj)); if (!encoder) { return false; } RootedObject stream(cx, MultipartFormData::encode_stream(cx, encoder)); if (!stream) { return false; } auto boundary = MultipartFormData::boundary(encoder); std::string content_type_str = "multipart/form-data; boundary=" + boundary; host_type_str = host_api::HostString(content_type_str.c_str()); auto length = MultipartFormData::query_length(cx, encoder); if (length.isErr()) { return false; } // content_length = mozilla::Some(length.unwrap()); content_type = host_type_str.begin(); RootedValue stream_val(cx, JS::ObjectValue(*stream)); JS_SetReservedSlot(self, static_cast(RequestOrResponse::Slots::BodyStream), stream_val); } else if (body_obj && JS::IsReadableStream(body_obj)) { if (RequestOrResponse::body_unusable(cx, body_obj)) { JS_ReportErrorNumberLatin1(cx, FastlyGetErrorMessage, nullptr, JSMSG_READABLE_STREAM_LOCKED_OR_DISTRUBED); return false; } // Move native body handle to new Request and store source for async-safe shortcutting if (NativeStreamSource::stream_is_body(cx, body_obj)) { set_up_shortcutting(cx, body_obj, self); } JS_SetReservedSlot(self, static_cast(RequestOrResponse::Slots::BodyStream), body_val); } else { mozilla::Maybe maybeNoGC; JS::UniqueChars text; char *buf; size_t length; host_api::Result write_res; host_api::HttpBody body{RequestOrResponse::body_handle(self)}; if (body_obj && JS_IsArrayBufferViewObject(body_obj)) { // Short typed arrays have inline data which can move on GC, so assert // that no GC happens. (Which it doesn't, because we're not allocating // before `buf` goes out of scope.) JS::AutoCheckCannotGC noGC(cx); bool is_shared; length = JS_GetArrayBufferViewByteLength(body_obj); buf = (char *)JS_GetArrayBufferViewData(body_obj, &is_shared, noGC); write_res = body.write_all_back(reinterpret_cast(buf), length); } else if (body_obj && JS::IsArrayBufferObject(body_obj)) { bool is_shared; JS::GetArrayBufferLengthAndData(body_obj, &length, &is_shared, (uint8_t **)&buf); write_res = body.write_all_back(reinterpret_cast(buf), length); } else if (body_obj && URLSearchParams::is_instance(body_obj)) { auto slice = URLSearchParams::serialize(cx, body_obj); buf = (char *)slice.data; length = slice.len; content_type = "application/x-www-form-urlencoded;charset=UTF-8"; write_res = body.write_all_back(reinterpret_cast(buf), length); } else { { auto str = core::encode(cx, body_val); text = std::move(str.ptr); length = str.len; } if (!text) { return false; } buf = text.get(); content_type = "text/plain;charset=UTF-8"; write_res = body.write_all_back(reinterpret_cast(buf), length); } if (auto *err = write_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } } // Step 36.3 of Request constructor / 8.4 of Response constructor. if (content_type) { JS::RootedObject headers( cx, &JS::GetReservedSlot(self, static_cast(Slots::Headers)).toObject()); if (!Headers::set_valid_if_undefined(cx, headers, "content-type", content_type)) { return false; } } JS::SetReservedSlot(self, static_cast(Slots::HasBody), JS::BooleanValue(true)); return true; } JSObject *RequestOrResponse::maybe_headers(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); return JS::GetReservedSlot(obj, static_cast(Slots::Headers)).toObjectOrNull(); } bool RequestOrResponse::append_body(JSContext *cx, JS::HandleObject self, JS::HandleObject source) { MOZ_ASSERT(!body_used(source)); host_api::HttpBody source_body{body_handle(source)}; host_api::HttpBody dest_body{body_handle(self)}; auto res = dest_body.append(source_body); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } return true; } JSObject *Request::headers(JSContext *cx, JS::HandleObject obj) { JS::RootedObject headers(cx, RequestOrResponse::maybe_headers(obj)); if (!headers) { MOZ_ASSERT(is_instance(obj)); if (is_downstream(obj)) { headers.set( Headers::create(cx, request_handle(obj).headers(), Headers::HeadersGuard::Request)); } else { headers.set(Headers::create(cx, Headers::HeadersGuard::Request)); } if (!headers) { return nullptr; } JS_SetReservedSlot(obj, static_cast(Slots::Headers), JS::ObjectValue(*headers)); } return headers; } JSObject *Response::headers(JSContext *cx, JS::HandleObject obj) { JS::RootedObject headers(cx, RequestOrResponse::maybe_headers(obj)); if (!headers) { MOZ_ASSERT(is_instance(obj)); if (is_upstream(obj)) { headers.set( Headers::create(cx, response_handle(obj).headers(), Headers::HeadersGuard::Response)); } else { headers.set(Headers::create(cx, Headers::HeadersGuard::Response)); } if (!headers) { return nullptr; } JS_SetReservedSlot(obj, static_cast(Slots::Headers), JS::ObjectValue(*headers)); } return headers; } bool Request::isCacheable_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) // before we can check isCacheable, we must flush the headers to the host handle // this operation is cache tracked through the HeadersGen slot if (!RequestOrResponse::commit_headers(cx, self)) { return false; } auto handle = request_handle(self); auto res = handle.is_cacheable(); if (auto *err = res.to_err()) { if (host_api::error_is_unsupported(*err)) { args.rval().setUndefined(); return true; } HANDLE_ERROR(cx, *err); return false; } args.rval().setBoolean(res.unwrap()); return true; } // Headers are committed when making the request or response. // We ensure the headers are in the ContentOnly or CachedInContent state for // future reads and mutations, and then copy them into a new handle created for the // request or response being sent. bool RequestOrResponse::commit_headers(JSContext *cx, HandleObject self) { JS::RootedObject headers(cx, RequestOrResponse::maybe_headers(self)); if (!headers) { return true; } if (Headers::mode(headers) == Headers::Mode::Uninitialized || Headers::mode(headers) == Headers::Mode::CachedInContent || Headers::mode(headers) == Headers::Mode::HostOnly) { return true; } bool headers_changed; if (!compare_bump_headers_gen(cx, self, &headers_changed)) { return false; } if (!headers_changed) { return true; } MOZ_ASSERT(Headers::mode(headers) == Headers::Mode::ContentOnly); Headers::HeadersList *list = Headers::get_list(cx, headers); MOZ_ASSERT(list); // Host headers handle to write into host_api::HttpHeaders *headers_handle; if (Request::is_instance(self)) { headers_handle = Request::request_handle(self).headers_writable(); } else { MOZ_ASSERT(Response::is_instance(self)); headers_handle = Response::response_handle(self).headers_writable(); } auto res = host_api::write_headers(headers_handle, *list); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } return true; } bool RequestOrResponse::compare_bump_headers_gen(JSContext *cx, HandleObject self, bool *changed_out) { RootedValue last_headers_gen( cx, JS::GetReservedSlot(self, static_cast(Response::Slots::HeadersGen))); JS::RootedObject headers(cx, RequestOrResponse::maybe_headers(self)); if (!headers) { JS::SetReservedSlot(self, static_cast(Slots::HeadersGen), JS::NullValue()); *changed_out = last_headers_gen.isUndefined(); return true; } uint32_t headers_gen = Headers::get_generation(headers); // generation overflow implies always-invalidate if (headers_gen == INT32_MAX || last_headers_gen.isUndefined() || last_headers_gen.isNull() || last_headers_gen.toInt32() != headers_gen) { JS::SetReservedSlot(self, static_cast(Response::Slots::HeadersGen), JS::Int32Value(headers_gen)); *changed_out = true; return true; } else { *changed_out = false; return true; } } template bool RequestOrResponse::parse_body(JSContext *cx, JS::HandleObject self, JS::UniqueChars buf, size_t len) { JS::RootedObject result_promise( cx, &JS::GetReservedSlot(self, static_cast(Slots::BodyAllPromise)).toObject()); JS::SetReservedSlot(self, static_cast(Slots::BodyAllPromise), JS::UndefinedValue()); JS::RootedValue result(cx); if constexpr (result_type == RequestOrResponse::BodyReadResult::ArrayBuffer) { JS::RootedObject array_buffer( cx, JS::NewArrayBufferWithContents(cx, len, buf.get(), JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory)); if (!array_buffer) { return RejectPromiseWithPendingError(cx, result_promise); } static_cast(buf.release()); result.setObject(*array_buffer); } else if constexpr (result_type == RequestOrResponse::BodyReadResult::Blob) { JS::RootedString contentType(cx, JS_GetEmptyString(cx)); JS::RootedObject blob(cx, Blob::create(cx, std::move(buf), len, contentType)); if (!blob) { return RejectPromiseWithPendingError(cx, result_promise); } result.setObject(*blob); } else if constexpr (result_type == RequestOrResponse::BodyReadResult::FormData) { auto throw_invalid_header = [&]() { api::throw_error(cx, FetchErrors::InvalidFormDataHeader); return RejectPromiseWithPendingError(cx, result_promise); }; RootedObject headers(cx, RequestOrResponse::maybe_headers(self)); if (!headers) { return throw_invalid_header(); } auto content_type_str = host_api::HostString("Content-Type"); auto idx = Headers::lookup(cx, headers, content_type_str); if (!idx) { return throw_invalid_header(); } auto values = Headers::get_index(cx, headers, idx.value()); auto maybe_mime = builtins::web::fetch::extract_mime_type(std::get<1>(*values)); if (maybe_mime.isErr()) { return throw_invalid_header(); } auto parser = FormDataParser::create(maybe_mime.unwrap().to_string()); if (!parser) { return throw_invalid_header(); } std::string_view body(buf.get(), len); RootedObject form_data(cx, parser->parse(cx, body)); if (!form_data) { api::throw_error(cx, FetchErrors::InvalidFormData); return RejectPromiseWithPendingError(cx, result_promise); } result.setObject(*form_data); } else { JS::RootedString text(cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(buf.get(), len))); if (!text) { return RejectPromiseWithPendingError(cx, result_promise); } if constexpr (result_type == RequestOrResponse::BodyReadResult::Text) { result.setString(text); } else { MOZ_ASSERT(result_type == RequestOrResponse::BodyReadResult::JSON); if (!JS_ParseJSON(cx, text, &result)) { return RejectPromiseWithPendingError(cx, result_promise); } } } return JS::ResolvePromise(cx, result_promise, result); } bool RequestOrResponse::content_stream_read_then_handler(JSContext *cx, JS::HandleObject self, JS::HandleValue extra, JS::CallArgs args) { JS::RootedObject then_handler(cx, &args.callee()); // The reader is stored in the catch handler, which we need here as well. // So we get that first, then the reader. MOZ_ASSERT(extra.isObject()); JS::RootedObject catch_handler(cx, &extra.toObject()); #ifdef DEBUG bool foundContents; if (!JS_HasElement(cx, catch_handler, 1, &foundContents)) { return false; } MOZ_ASSERT(foundContents); #endif JS::RootedValue contents_val(cx); if (!JS_GetElement(cx, catch_handler, 1, &contents_val)) { return false; } MOZ_ASSERT(contents_val.isObject()); JS::RootedObject contents(cx, &contents_val.toObject()); if (!contents) { return false; } #ifdef DEBUG bool contentsIsArray; if (!JS::IsArrayObject(cx, contents, &contentsIsArray)) { return false; } MOZ_ASSERT(contentsIsArray); #endif auto reader_val = js::GetFunctionNativeReserved(catch_handler, 1); MOZ_ASSERT(reader_val.isObject()); JS::RootedObject reader(cx, &reader_val.toObject()); // We're guaranteed to work with a native ReadableStreamDefaultReader here as we used // `JS::ReadableStreamDefaultReaderRead(cx, reader)`, which in turn is guaranteed to return {done: // bool, value: any} objects to read promise then callbacks. MOZ_ASSERT(args[0].isObject()); JS::RootedObject chunk_obj(cx, &args[0].toObject()); JS::RootedValue done_val(cx); JS::RootedValue value(cx); #ifdef DEBUG bool hasValue; if (!JS_HasProperty(cx, chunk_obj, "value", &hasValue)) { return false; } MOZ_ASSERT(hasValue); #endif if (!JS_GetProperty(cx, chunk_obj, "value", &value)) { return false; } #ifdef DEBUG bool hasDone; if (!JS_HasProperty(cx, chunk_obj, "done", &hasDone)) { return false; } MOZ_ASSERT(hasDone); #endif if (!JS_GetProperty(cx, chunk_obj, "done", &done_val)) { return false; } MOZ_ASSERT(done_val.isBoolean()); if (done_val.toBoolean()) { // We finished reading the stream // Now we need to iterate/reduce `contents` JS Array into UniqueChars uint32_t contentsLength; if (!JS::GetArrayLength(cx, contents, &contentsLength)) { return false; } // TODO(performance): investigate whether we can infer the size directly from `contents` size_t buf_size = HANDLE_READ_CHUNK_SIZE; // TODO(performance): make use of malloc slack. // https://github.com/fastly/js-compute-runtime/issues/217 size_t offset = 0; // In this loop we are finding the length of each entry in `contents` and resizing the `buf` // until it is large enough to fit all the entries in `contents` for (uint32_t index = 0; index < contentsLength; index++) { JS::RootedValue val(cx); if (!JS_GetElement(cx, contents, index, &val)) { return false; } { JS::AutoCheckCannotGC nogc; MOZ_ASSERT(val.isObject()); JSObject *array = &val.toObject(); MOZ_ASSERT(JS_IsUint8Array(array)); size_t length = JS_GetTypedArrayByteLength(array); if (length) { offset += length; // if buf is not big enough to fit the next uint8array's bytes then resize if (offset > buf_size) { buf_size = buf_size + (HANDLE_READ_CHUNK_SIZE * ((length / HANDLE_READ_CHUNK_SIZE) + 1)); } } } } JS::UniqueChars buf{static_cast(JS_malloc(cx, buf_size + 1))}; if (!buf) { JS_ReportOutOfMemory(cx); return false; } // reset the offset for the next loop offset = 0; // In this loop we are inserting each entry in `contents` into `buf` for (uint32_t index = 0; index < contentsLength; index++) { JS::RootedValue val(cx); if (!JS_GetElement(cx, contents, index, &val)) { return false; } { JS::AutoCheckCannotGC nogc; MOZ_ASSERT(val.isObject()); JSObject *array = &val.toObject(); MOZ_ASSERT(JS_IsUint8Array(array)); bool is_shared; size_t length = JS_GetTypedArrayByteLength(array); if (length) { static_assert(CHAR_BIT == 8, "Strange char"); auto bytes = reinterpret_cast(JS_GetUint8ArrayData(array, &is_shared, nogc)); memcpy(buf.get() + offset, bytes, length); offset += length; } } } buf[offset] = '\0'; #ifdef DEBUG bool foundBodyParser; if (!JS_HasElement(cx, catch_handler, 2, &foundBodyParser)) { return false; } MOZ_ASSERT(foundBodyParser); #endif // Now we can call parse_body on the result JS::RootedValue body_parser(cx); if (!JS_GetElement(cx, catch_handler, 2, &body_parser)) { return false; } auto parse_body = (ParseBodyCB *)body_parser.toPrivate(); return parse_body(cx, self, std::move(buf), offset); } JS::RootedValue val(cx); if (!JS_GetProperty(cx, chunk_obj, "value", &val)) { return false; } // The read operation can return anything since this stream comes from the guest // If it is not a UInt8Array -- reject with a TypeError if (!val.isObject() || !JS_IsUint8Array(&val.toObject())) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_VALUE_NOT_UINT8ARRAY); JS::RootedObject result_promise(cx); result_promise = &JS::GetReservedSlot(self, static_cast(Slots::BodyAllPromise)).toObject(); JS::SetReservedSlot(self, static_cast(Slots::BodyAllPromise), JS::UndefinedValue()); return RejectPromiseWithPendingError(cx, result_promise); } { uint32_t contentsLength; if (!JS::GetArrayLength(cx, contents, &contentsLength)) { return false; } if (!JS_SetElement(cx, contents, contentsLength, val)) { return false; } } // Read the next chunk. JS::RootedObject promise(cx, JS::ReadableStreamDefaultReaderRead(cx, reader)); if (!promise) return false; return JS::AddPromiseReactions(cx, promise, then_handler, catch_handler); } bool RequestOrResponse::content_stream_read_catch_handler(JSContext *cx, JS::HandleObject self, JS::HandleValue extra, JS::CallArgs args) { // The stream errored when being consumed // we need to propagate the stream error MOZ_ASSERT(extra.isObject()); JS::RootedObject reader(cx, &extra.toObject()); JS::RootedValue stream_val(cx); if (!JS_GetElement(cx, reader, 1, &stream_val)) { return false; } MOZ_ASSERT(stream_val.isObject()); JS::RootedObject stream(cx, &stream_val.toObject()); if (!stream) { return false; } MOZ_ASSERT(JS::IsReadableStream(stream)); #ifdef DEBUG bool isError; if (!JS::ReadableStreamIsErrored(cx, stream, &isError)) { return false; } MOZ_ASSERT(isError); #endif JS::RootedValue error(cx, JS::ReadableStreamGetStoredError(cx, stream)); JS_ClearPendingException(cx); JS_SetPendingException(cx, error, JS::ExceptionStackBehavior::DoNotCapture); JS::RootedObject result_promise(cx); result_promise = &JS::GetReservedSlot(self, static_cast(Slots::BodyAllPromise)).toObject(); JS::SetReservedSlot(self, static_cast(Slots::BodyAllPromise), JS::UndefinedValue()); return RejectPromiseWithPendingError(cx, result_promise); } bool RequestOrResponse::consume_content_stream_for_bodyAll(JSContext *cx, JS::HandleObject self, JS::HandleValue stream_val, JS::CallArgs args) { // The body_parser is stored in the stream object, which we need here as well. JS::RootedObject stream(cx, &stream_val.toObject()); JS::RootedValue body_parser(cx); if (!JS_GetElement(cx, stream, 1, &body_parser)) { return false; } MOZ_ASSERT(JS::IsReadableStream(stream)); if (RequestOrResponse::body_unusable(cx, stream)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_BODY_DISTURBED_OR_LOCKED); JS::RootedObject result_promise(cx); result_promise = &JS::GetReservedSlot(self, static_cast(Slots::BodyAllPromise)).toObject(); JS::SetReservedSlot(self, static_cast(Slots::BodyAllPromise), JS::UndefinedValue()); return RejectPromiseWithPendingError(cx, result_promise); } JS::Rooted unwrappedReader( cx, JS::ReadableStreamGetReader(cx, stream, JS::ReadableStreamReaderMode::Default)); if (!unwrappedReader) { return false; } // contents is the JS Array we store the stream chunks within, to later convert to // arrayBuffer/json/text JS::Rooted contents(cx, JS::NewArrayObject(cx, 0)); if (!contents) { return false; } JS::RootedValue extra(cx, JS::ObjectValue(*unwrappedReader)); // TODO: confirm whether this is observable to the JS application if (!JS_SetElement(cx, unwrappedReader, 1, stream)) { return false; } // Create handlers for both `then` and `catch`. // These are functions with two reserved slots, in which we store all // information required to perform the reactions. We store the actually // required information on the catch handler, and a reference to that on the // then handler. This allows us to reuse these functions for the next read // operation in the then handler. The catch handler won't ever have a need to // perform another operation in this way. JS::RootedObject catch_handler( cx, create_internal_method(cx, self, extra)); if (!catch_handler) { return false; } extra.setObject(*catch_handler); if (!JS_SetElement(cx, catch_handler, 1, contents)) { return false; } if (!JS_SetElement(cx, catch_handler, 2, body_parser)) { return false; } JS::RootedObject then_handler( cx, create_internal_method(cx, self, extra)); if (!then_handler) { return false; } // Read the next chunk. JS::RootedObject promise(cx, JS::ReadableStreamDefaultReaderRead(cx, unwrappedReader)); if (!promise) { return false; } return JS::AddPromiseReactions(cx, promise, then_handler, catch_handler); } // bool async_process_body_handle_for_bodyAll(JSContext *cx, uint32_t handle, JS::HandleObject self, // JS::HandleValue body_parser) { // auto body = RequestOrResponse::body_handle(self); // auto *parse_body = reinterpret_cast(body_parser.toPrivate()); // auto [buf, bytes_read, state] = read_from_handle_all(cx, body); // if (state == StreamState::Error) { // JS::RootedObject result_promise(cx); // result_promise = // &JS::GetReservedSlot(self, // static_cast(RequestOrResponse::Slots::BodyAllPromise)) // .toObject(); // JS::SetReservedSlot(self, static_cast(RequestOrResponse::Slots::BodyAllPromise), // JS::UndefinedValue()); // return RejectPromiseWithPendingError(cx, result_promise); // } // if (state == StreamState::Complete) { // return parse_body(cx, self, std::move(buf), bytes_read); // } // // still have to wait for the stream to complete, queue an async task // ENGINE->queue_async_task(new FastlyAsyncTask(body.async_handle(), self, // JS::UndefinedHandleValue, // async_process_body_handle_for_bodyAll)); // return true; // } template bool RequestOrResponse::consume_body_handle_for_bodyAll(JSContext *cx, JS::HandleObject self, JS::HandleValue body_parser, JS::CallArgs args) { auto body = body_handle(self); auto *parse_body = reinterpret_cast(body_parser.toPrivate()); auto [buf, bytes_read, state] = read_from_handle_all(cx, body); MOZ_ASSERT(async || state != StreamState::Wait); if (state == StreamState::Error) { JS::RootedObject result_promise(cx); result_promise = &JS::GetReservedSlot(self, static_cast(Slots::BodyAllPromise)).toObject(); JS::SetReservedSlot(self, static_cast(Slots::BodyAllPromise), JS::UndefinedValue()); return RejectPromiseWithPendingError(cx, result_promise); } if (state == StreamState::Complete) { return parse_body(cx, self, std::move(buf), bytes_read); } // TODO: the async path isn't working because we don't yet store a chunk buffer along with // the body parser / on the Response slot. This would be a nice addition in future. // still have to wait for the stream to complete, queue an async task // ENGINE->queue_async_task(new FastlyAsyncTask(body.async_handle(), self, // JS::UndefinedHandleValue, // async_process_body_handle_for_bodyAll)); return true; } template bool RequestOrResponse::bodyAll(JSContext *cx, JS::CallArgs args, JS::HandleObject self) { // TODO: mark body as consumed when operating on stream, too. if (body_used(self)) { JS_ReportErrorASCII(cx, "Body has already been consumed"); return ReturnPromiseRejectedWithPendingError(cx, args); } JS::RootedObject bodyAll_promise(cx, JS::NewPromiseObject(cx, nullptr)); if (!bodyAll_promise) { return ReturnPromiseRejectedWithPendingError(cx, args); } JS::SetReservedSlot(self, static_cast(Slots::BodyAllPromise), JS::ObjectValue(*bodyAll_promise)); // If the Request/Response doesn't have a body, empty default results need to // be returned. if (!has_body(self)) { JS::UniqueChars chars; if (!parse_body(cx, self, std::move(chars), 0)) { return ReturnPromiseRejectedWithPendingError(cx, args); } args.rval().setObject(*bodyAll_promise); return true; } if (!mark_body_used(cx, self)) { return ReturnPromiseRejectedWithPendingError(cx, args); } JS::RootedValue body_parser(cx, JS::PrivateValue((void *)parse_body)); // If the body is a ReadableStream that's not backed by a body handle, we need to // manually read all chunks from the stream. // TODO(performance): ensure that we're properly shortcutting reads from TransformStream // readables. // https://github.com/fastly/js-compute-runtime/issues/218 JS::RootedObject stream(cx, body_stream(self)); // Note: Shortcutting is now handled by maybe_shortcut_transform_stream_read() // which is called from body_source_pull_algorithm() when the stream is first read. if (stream && !NativeStreamSource::stream_is_body(cx, stream)) { if (!JS_SetElement(cx, stream, 1, body_parser)) { return false; } JS::RootedValue extra(cx, JS::ObjectValue(*stream)); if (!enqueue_internal_method(cx, self, extra)) { return ReturnPromiseRejectedWithPendingError(cx, args); } } else { if (!enqueue_internal_method>(cx, self, body_parser)) { return ReturnPromiseRejectedWithPendingError(cx, args); } } args.rval().setObject(*bodyAll_promise); return true; } bool RequestOrResponse::body_source_pull_algorithm(JSContext *cx, JS::CallArgs args, JS::HandleObject source, JS::HandleObject body_owner, JS::HandleObject controller) { if (JS::GetReservedSlot(source, static_cast(Slots::Body)).isInt32()) { auto handle = std::to_string(RequestOrResponse::body_handle(source).handle); } // The actual read from the body needs to be delayed, because it'd otherwise // be a blocking operation in case the backend didn't yet send any data. // That would lead to situations where we block on I/O before processing // all pending Promises, which in turn can result in operations happening in // observably different behavior, up to and including causing deadlocks // because a body read response is blocked on content making another request. // // (This deadlock happens in automated tests, but admittedly might not happen // in real usage.) JS::RootedObject self(cx, &args.thisv().toObject()); JS::RootedObject owner(cx, NativeStreamSource::owner(self)); JS::RootedValue body_owner_value(cx, JS::ObjectValue(*body_owner)); ENGINE->queue_async_task(new FastlyAsyncTask(RequestOrResponse::body_handle(owner).async_handle(), source, body_owner_value, process_body_read)); args.rval().setUndefined(); return true; } bool RequestOrResponse::body_source_cancel_algorithm(JSContext *cx, JS::CallArgs args, JS::HandleObject stream, JS::HandleObject owner, JS::HandleValue reason) { args.rval().setUndefined(); return true; } bool RequestOrResponse::body_reader_then_handler(JSContext *cx, JS::HandleObject body_owner, JS::HandleValue extra, JS::CallArgs args) { JS::RootedObject then_handler(cx, &args.callee()); // The reader is stored in the catch handler, which we need here as well. // So we get that first, then the reader. JS::RootedObject catch_handler(cx, &extra.toObject()); JS::RootedObject reader(cx, &js::GetFunctionNativeReserved(catch_handler, 1).toObject()); auto body = RequestOrResponse::body_handle(body_owner); // We're guaranteed to work with a native ReadableStreamDefaultReader here, // which in turn is guaranteed to vend {done: bool, value: any} objects to // read promise then callbacks. JS::RootedObject chunk_obj(cx, &args[0].toObject()); JS::RootedValue done_val(cx); if (!JS_GetProperty(cx, chunk_obj, "done", &done_val)) return false; if (done_val.toBoolean()) { // The only response with a body we ever send is the one passed to // `FetchEvent#respondWith` to send to the client. As such, we can be // certain that if we have a response here, we can advance the FetchState to // `responseDone`. if (Response::is_instance(body_owner)) { ENGINE->decr_event_loop_interest(); JS::RootedValue fetch_event_val( cx, JS::GetReservedSlot(body_owner, static_cast(Response::Slots::FetchEvent))); if (!fetch_event_val.isObject()) { JS_ReportErrorASCII(cx, "Response does not have an associated FetchEvent"); return false; } JS::RootedObject fetch_event(cx, &fetch_event_val.toObject()); FetchEvent::set_state(fetch_event, FetchEvent::State::responseDone); } auto res = body.close(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (Request::is_instance(body_owner)) { JS::RootedValue promise(cx, JS::ObjectValue(*Request::response_promise(body_owner))); ENGINE->queue_async_task( new FastlyAsyncTask(Request::pending_handle(body_owner).async_handle(), body_owner, promise, process_pending_request)); } return true; } JS::RootedValue val(cx); if (!JS_GetProperty(cx, chunk_obj, "value", &val)) return false; // The read operation returned something that's not a Uint8Array if (!val.isObject() || !JS_IsUint8Array(&val.toObject())) { // reject the request promise if (Request::is_instance(body_owner)) { JS::RootedObject response_promise(cx, Request::response_promise(body_owner)); JS::RootedValue exn(cx); // TODO: this should be a TypeError, but I'm not sure how to make that work JS_ReportErrorUTF8(cx, "TypeError"); if (!JS_GetPendingException(cx, &exn)) { return false; } JS_ClearPendingException(cx); return JS::RejectPromise(cx, response_promise, exn); } // TODO: should we also create a rejected promise if a response reads something that's not a // Uint8Array? fprintf(stderr, "Error: read operation on body ReadableStream didn't respond with a " "Uint8Array. Received value: "); ENGINE->dump_value(val, stderr); return false; } host_api::Result res; { JS::AutoCheckCannotGC nogc; JSObject *array = &val.toObject(); bool is_shared; uint8_t *bytes = JS_GetUint8ArrayData(array, &is_shared, nogc); size_t length = JS_GetTypedArrayByteLength(array); res = body.write_all_back(bytes, length); } // Needs to be outside the nogc block in case we need to create an exception. if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } // Read the next chunk. JS::RootedObject promise(cx, JS::ReadableStreamDefaultReaderRead(cx, reader)); if (!promise) { return false; } return JS::AddPromiseReactions(cx, promise, then_handler, catch_handler); } bool RequestOrResponse::body_reader_catch_handler(JSContext *cx, JS::HandleObject body_owner, JS::HandleValue extra, JS::CallArgs args) { // TODO: check if this should create a rejected promise instead, so an // in-content handler for unhandled rejections could deal with it. The body // stream errored during the streaming send. Not much we can do, but at least // close the stream, and warn. fprintf(stderr, "Warning: body ReadableStream closed during body streaming. Exception: "); ENGINE->dump_value(args.get(0), stderr); // The only response with a body we ever send is the one passed to // `FetchEvent#respondWith` to send to the client. As such, we can be certain // that if we have a response here, we can advance the FetchState to // `responseDone`. (Note that even though we encountered an error, // `responseDone` is the right state: `responsedWithError` is for when sending // a response at all failed.) if (Response::is_instance(body_owner)) { ENGINE->decr_event_loop_interest(); JS::RootedValue fetch_event_val( cx, JS::GetReservedSlot(body_owner, static_cast(Response::Slots::FetchEvent))); if (!fetch_event_val.isObject()) { JS_ReportErrorASCII(cx, "Response does not have an associated FetchEvent"); return false; } JS::RootedObject fetch_event(cx, &fetch_event_val.toObject()); FetchEvent::set_state(fetch_event, FetchEvent::State::responseDone); } return true; } bool RequestOrResponse::maybe_stream_body(JSContext *cx, JS::HandleObject body_owner, bool *requires_streaming) { JS::RootedObject stream(cx, RequestOrResponse::body_stream(body_owner)); if (!stream) { return true; } if (RequestOrResponse::body_unusable(cx, stream)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_BODY_DISTURBED_OR_LOCKED); return false; } // If the body stream is backed by a Fastly Compute body handle, we can directly pipe // that handle into the body we're about to send. if (NativeStreamSource::stream_is_body(cx, stream)) { // First, move the source's body handle to the target and lock the stream. JS::RootedObject stream_source(cx, NativeStreamSource::get_stream_source(cx, stream)); JS::RootedObject source_owner(cx, NativeStreamSource::owner(stream_source)); if (!RequestOrResponse::move_body_handle(cx, source_owner, body_owner)) { return false; } // Then, send the request/response without streaming. We know that content // won't append to this body handle, because we don't expose any means to do // so, so it's ok for it to be closed immediately. return true; } // Try shortcutting TransformStream by piping native body handle directly bool shortcutted = false; JS::RootedObject stream_source(cx, NativeStreamSource::get_stream_source(cx, stream)); if (stream_source && NativeStreamSource::is_instance(stream_source)) { if (!maybe_shortcut_transform_stream_read(cx, stream_source, body_owner, &shortcutted)) { return false; } if (shortcutted) { return true; } } JS::RootedObject reader( cx, JS::ReadableStreamGetReader(cx, stream, JS::ReadableStreamReaderMode::Default)); if (!reader) return false; bool is_closed; if (!JS::ReadableStreamReaderIsClosed(cx, reader, &is_closed)) return false; // It's ok for the stream to be closed, as its contents might // already have fully been written to the body handle. // In that case, we can do a blocking send instead. if (is_closed) { return true; } // Create handlers for both `then` and `catch`. // These are functions with two reserved slots, in which we store all // information required to perform the reactions. We store the actually // required information on the catch handler, and a reference to that on the // then handler. This allows us to reuse these functions for the next read // operation in the then handler. The catch handler won't ever have a need to // perform another operation in this way. JS::RootedObject catch_handler(cx); JS::RootedValue extra(cx, JS::ObjectValue(*reader)); catch_handler = create_internal_method(cx, body_owner, extra); if (!catch_handler) return false; JS::RootedObject then_handler(cx); extra.setObject(*catch_handler); then_handler = create_internal_method(cx, body_owner, extra); if (!then_handler) return false; JS::RootedObject promise(cx, JS::ReadableStreamDefaultReaderRead(cx, reader)); if (!promise) return false; if (!JS::AddPromiseReactions(cx, promise, then_handler, catch_handler)) return false; *requires_streaming = true; return true; } JSObject *RequestOrResponse::create_body_stream(JSContext *cx, JS::HandleObject owner) { MOZ_ASSERT(!body_stream(owner)); JS::RootedObject source(cx, NativeStreamSource::create(cx, owner, JS::UndefinedHandleValue, body_source_pull_algorithm, body_source_cancel_algorithm)); if (!source) return nullptr; JS::RootedObject body_stream(cx, NativeStreamSource::stream(source)); if (!body_stream) { return nullptr; } // TODO: immediately lock the stream if the owner's body is already used. JS_SetReservedSlot(owner, static_cast(Slots::BodyStream), JS::ObjectValue(*body_stream)); return body_stream; } bool RequestOrResponse::backend_get(JSContext *cx, JS::CallArgs args, JS::HandleObject self) { JS::RootedValue backend(cx, JS::GetReservedSlot(self, static_cast(Slots::Backend))); if (!backend.isString()) { args.rval().setUndefined(); return true; } host_api::HostString name = core::encode(cx, backend); Backend::get_from_valid_name(cx, std::move(name), args.rval()); return true; } bool RequestOrResponse::body_get(JSContext *cx, JS::CallArgs args, JS::HandleObject self, bool create_if_undefined) { if (!has_body(self)) { args.rval().setNull(); return true; } JS::RootedObject body_stream(cx, RequestOrResponse::body_stream(self)); if (!body_stream && create_if_undefined) { body_stream = create_body_stream(cx, self); if (!body_stream) return false; } args.rval().setObjectOrNull(body_stream); return true; } host_api::HttpReq Request::request_handle(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); return host_api::HttpReq( JS::GetReservedSlot(obj, static_cast(Request::Slots::Request)).toInt32()); } host_api::HttpPendingReq Request::pending_handle(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); host_api::HttpPendingReq res; JS::Value handle_val = JS::GetReservedSlot(obj, static_cast(Request::Slots::PendingRequest)); if (handle_val.isInt32()) { res = host_api::HttpPendingReq(handle_val.toInt32()); } return res; } std::optional RequestOrResponse::cache_entry(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); JS::Value handle_val = JS::GetReservedSlot(obj, static_cast(RequestOrResponse::Slots::CacheEntry)); if (handle_val.isInt32()) { return host_api::HttpCacheEntry(handle_val.toInt32()); } return std::nullopt; } std::optional RequestOrResponse::take_cache_entry(JSObject *obj, std::optional mark_cached) { MOZ_ASSERT(is_instance(obj)); JS::Value handle_val = JS::GetReservedSlot(obj, static_cast(RequestOrResponse::Slots::CacheEntry)); JS::SetReservedSlot(obj, static_cast(RequestOrResponse::Slots::CacheEntry), mark_cached.has_value() ? JS::BooleanValue(mark_cached.value()) : JS::UndefinedValue()); if (handle_val.isInt32()) { return host_api::HttpCacheEntry(handle_val.toInt32()); } return std::nullopt; } bool RequestOrResponse::close_if_cache_entry(JSContext *cx, HandleObject self) { MOZ_ASSERT(is_instance(self)); auto maybe_cache_entry = RequestOrResponse::take_cache_entry(self, std::nullopt); if (!maybe_cache_entry.has_value()) { return true; } auto res = maybe_cache_entry.value().close(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } return true; } bool Request::is_downstream(JSObject *obj) { return JS::GetReservedSlot(obj, static_cast(Slots::IsDownstream)).toBoolean(); } JSString *RequestOrResponse::backend(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); auto val = JS::GetReservedSlot(obj, static_cast(Slots::Backend)); return val.isString() ? val.toString() : nullptr; } JSObject *Request::response_promise(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); return &JS::GetReservedSlot(obj, static_cast(Request::Slots::ResponsePromise)) .toObject(); } JSString *Request::method(JSContext *cx, JS::HandleObject obj) { MOZ_ASSERT(is_instance(obj)); return JS::GetReservedSlot(obj, static_cast(Slots::Method)).toString(); } bool Request::set_cache_key(JSContext *cx, JS::HandleObject self, JS::HandleValue cache_key_val) { MOZ_ASSERT(is_instance(self)); JS::RootedString cache_key_str(cx, JS::ToString(cx, cache_key_val)); if (!cache_key_str) { return false; } JS::RootedValue cache_key_str_val(cx, JS::StringValue(cache_key_str)); // Convert the key argument into a String following https://tc39.es/ecma262/#sec-tostring auto keyString = core::encode(cx, cache_key_str_val); if (!keyString) { return false; } std::string hex_str; picosha2::hash256_hex_string(keyString, hex_str); std::transform(hex_str.begin(), hex_str.end(), hex_str.begin(), [](unsigned char c) { return std::toupper(c); }); JS::RootedObject headers(cx, Request::headers(cx, self)); if (!headers) { return false; } JS::SetReservedSlot(self, static_cast(Slots::OverrideCacheKey), cache_key_str_val); JS::RootedString hex_str_js(cx, JS_NewStringCopyN(cx, hex_str.c_str(), hex_str.length())); JS::RootedValue value_val(cx, JS::StringValue(hex_str_js)); if (!Headers::append_valid_header(cx, headers, "fastly-xqd-cache-key", value_val, "Request.prototype.setCacheKey")) { return false; } return true; } bool Request::set_image_optimizer_options(JSContext *cx, JS::HandleObject self, JS::HandleValue opts_val) { MOZ_ASSERT(is_instance(self)); auto opts = image_optimizer::ImageOptimizerOptions::create(cx, opts_val); if (!opts) { return false; } JS::SetReservedSlot(self, static_cast(Request::Slots::ImageOptimizerOptions), JS::PrivateValue(opts.release())); return true; } bool Request::set_cache_override(JSContext *cx, JS::HandleObject self, JS::HandleValue cache_override) { MOZ_ASSERT(is_instance(self)); JS::RootedObject override(cx); if (CacheOverride::is_instance(cache_override)) { JS::RootedObject input(cx, &cache_override.toObject()); override = CacheOverride::clone(cx, input); if (!override) { return false; } } else if (cache_override.isObject() || cache_override.isString()) { // support constructing the cache override dynamically override = CacheOverride::create(cx, cache_override); if (!override) { return false; } } else { JS_ReportErrorUTF8(cx, "Value passed in as cacheOverride must be an " "instance of CacheOverride or an object with the same interface"); return false; } JS::SetReservedSlot(self, static_cast(Slots::CacheOverride), JS::ObjectValue(*override)); return true; } bool Request::apply_auto_decompress_gzip(JSContext *cx, JS::HandleObject self) { MOZ_ASSERT(cx); MOZ_ASSERT(is_instance(self)); JS::RootedValue decompressGzipSlot( cx, JS::GetReservedSlot(self, static_cast(Request::Slots::AutoDecompressGzip))); auto decompress = JS::ToBoolean(decompressGzipSlot); if (!decompress) { return true; } auto res = Request::request_handle(self).auto_decompress_gzip(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } return true; } /** * Apply the CacheOverride to a host-side request handle (for non HTTP cache API). */ bool Request::apply_cache_override(JSContext *cx, JS::HandleObject self) { MOZ_ASSERT(is_instance(self)); JS::RootedObject override( cx, JS::GetReservedSlot(self, static_cast(Request::Slots::CacheOverride)) .toObjectOrNull()); if (!override) { return true; } std::optional ttl; JS::RootedValue val(cx, CacheOverride::ttl(override)); if (!val.isUndefined()) { ttl = val.toInt32(); } std::optional stale_while_revalidate; val = CacheOverride::swr(override); if (!val.isUndefined()) { stale_while_revalidate = val.toInt32(); } host_api::HostString sk_chars; std::optional surrogate_key; val = CacheOverride::surrogate_key(override); if (!val.isUndefined()) { sk_chars = core::encode(cx, val); if (!sk_chars) { return false; } surrogate_key.emplace(sk_chars); } auto tag = CacheOverride::abi_tag(override); auto res = Request::request_handle(self).cache_override(tag, ttl, stale_while_revalidate, surrogate_key); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } return true; } bool Request::method_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JSString *method = Request::method(cx, self); if (!method) return false; args.rval().setString(method); return true; } bool Request::url_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().set(RequestOrResponse::url(self)); return true; } bool Request::version_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto res = request_handle(self).get_version(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setInt32(res.unwrap()); return true; } bool Request::headers_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JSObject *headers = Request::headers(cx, self); if (!headers) return false; args.rval().setObject(*headers); return true; } template bool Request::bodyAll(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) return RequestOrResponse::bodyAll(cx, args, self); } bool Request::backend_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) return RequestOrResponse::backend_get(cx, args, self); } bool Request::body_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) return RequestOrResponse::body_get(cx, args, self, is_downstream(self)); } bool Request::bodyUsed_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().setBoolean(RequestOrResponse::body_used(self)); return true; } bool Request::setCacheOverride(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) if (!set_cache_override(cx, self, args[0])) return false; args.rval().setUndefined(); return true; } bool Request::setCacheKey(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) if (!set_cache_key(cx, self, args[0])) { return false; } args.rval().setUndefined(); return true; } bool Request::setManualFramingHeaders(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) bool manualFramingHeaders = JS::ToBoolean(args.get(0)); JS::SetReservedSlot(self, static_cast(Slots::ManualFramingHeaders), JS::BooleanValue(manualFramingHeaders)); auto handle = request_handle(self); host_api::Result res; if (manualFramingHeaders) { res = handle.set_framing_headers_mode(host_api::FramingHeadersMode::ManuallyFromHeaders); } else { res = handle.set_framing_headers_mode(host_api::FramingHeadersMode::Automatic); } if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } JSString *GET_atom; bool Request::clone(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); auto request_handle_res = host_api::HttpReq::make(); if (auto *err = request_handle_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto request_handle = request_handle_res.unwrap(); JS::RootedObject requestInstance(cx, Request::create_instance(cx)); JS::SetReservedSlot(requestInstance, static_cast(Slots::Request), JS::Int32Value(request_handle.handle)); JS::SetReservedSlot(requestInstance, static_cast(Slots::BodyUsed), JS::FalseValue()); JS::SetReservedSlot(requestInstance, static_cast(Slots::URL), JS::GetReservedSlot(self, static_cast(Slots::URL))); JS::SetReservedSlot(requestInstance, static_cast(Slots::IsDownstream), JS::GetReservedSlot(self, static_cast(Slots::IsDownstream))); JS::RootedValue manualFramingHeaders( cx, JS::GetReservedSlot(self, static_cast(Slots::ManualFramingHeaders))); JS::SetReservedSlot(requestInstance, static_cast(Slots::ManualFramingHeaders), manualFramingHeaders); if (JS::ToBoolean(manualFramingHeaders)) { auto res = request_handle.set_framing_headers_mode(host_api::FramingHeadersMode::ManuallyFromHeaders); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } } JS::RootedValue backend(cx, JS::GetReservedSlot(self, static_cast(Slots::Backend))); if (!backend.isNullOrUndefined()) { JS::SetReservedSlot(requestInstance, static_cast(Slots::Backend), backend); } auto hasBody = RequestOrResponse::has_body(self); JS::SetReservedSlot(requestInstance, static_cast(Slots::HasBody), JS::BooleanValue(hasBody)); if (hasBody) { if (RequestOrResponse::body_used(self)) { JS_ReportErrorLatin1(cx, "Request.prototype.clone: the request's body isn't usable."); return false; } // Here we get the current requests body stream and call ReadableStream.prototype.tee to return // two versions of the stream. Once we get the two streams, we create a new request handle and // attach one of the streams to the new handle and the other stream is attached to the request // handle that `clone()` was called upon. JS::RootedObject body_stream(cx, RequestOrResponse::body_stream(self)); if (!body_stream) { body_stream = RequestOrResponse::create_body_stream(cx, self); if (!body_stream) { return false; } } JS::RootedValue tee_val(cx); if (!JS_GetProperty(cx, body_stream, "tee", &tee_val)) { return false; } JS::Rooted tee(cx, JS_GetObjectFunction(&tee_val.toObject())); if (!tee) { return false; } JS::RootedVector argv(cx); JS::RootedValue rval(cx); if (!JS::Call(cx, body_stream, tee, argv, &rval)) { return false; } JS::RootedObject rval_array(cx, &rval.toObject()); JS::RootedValue body1_val(cx); if (!JS_GetProperty(cx, rval_array, "0", &body1_val)) { return false; } JS::RootedValue body2_val(cx); if (!JS_GetProperty(cx, rval_array, "1", &body2_val)) { return false; } auto res = host_api::HttpBody::make(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body_handle = res.unwrap(); if (!JS::IsReadableStream(&body1_val.toObject())) { return false; } body_stream.set(&body1_val.toObject()); if (RequestOrResponse::body_unusable(cx, body_stream)) { JS_ReportErrorNumberLatin1(cx, FastlyGetErrorMessage, nullptr, JSMSG_READABLE_STREAM_LOCKED_OR_DISTRUBED); return false; } JS::SetReservedSlot(requestInstance, static_cast(Slots::Body), JS::Int32Value(body_handle.handle)); JS::SetReservedSlot(requestInstance, static_cast(Slots::BodyStream), body1_val); JS::SetReservedSlot(self, static_cast(Slots::BodyStream), body2_val); JS::SetReservedSlot(self, static_cast(Slots::BodyUsed), JS::FalseValue()); JS::SetReservedSlot(self, static_cast(Slots::HasBody), JS::BooleanValue(true)); } JS::RootedObject headers(cx, Request::headers(cx, self)); if (!headers) { return false; } JS::SetReservedSlot(requestInstance, static_cast(Slots::Headers), JS::ObjectValue(*headers)); JS::RootedString method(cx, Request::method(cx, self)); if (!method) { return false; } JS::SetReservedSlot(requestInstance, static_cast(Slots::Method), JS::StringValue(method)); JS::RootedValue cache_override( cx, JS::GetReservedSlot(self, static_cast(Slots::CacheOverride))); if (!cache_override.isNullOrUndefined()) { if (!set_cache_override(cx, requestInstance, cache_override)) { return false; } } else { JS::SetReservedSlot(requestInstance, static_cast(Slots::CacheOverride), cache_override); } JS::RootedValue override_cache_key( cx, JS::GetReservedSlot(self, static_cast(Slots::OverrideCacheKey))); JS::SetReservedSlot(requestInstance, static_cast(Slots::OverrideCacheKey), override_cache_key); JS::RootedValue image_optimizer_options( cx, JS::GetReservedSlot(self, static_cast(Slots::ImageOptimizerOptions))); if (!image_optimizer_options.isNullOrUndefined()) { if (!set_image_optimizer_options(cx, requestInstance, image_optimizer_options)) { return false; } } else { JS::SetReservedSlot(requestInstance, static_cast(Slots::ImageOptimizerOptions), image_optimizer_options); } args.rval().setObject(*requestInstance); return true; } const JSFunctionSpec Request::static_methods[] = { JS_FS_END, }; const JSPropertySpec Request::static_properties[] = { JS_PS_END, }; const JSFunctionSpec Request::methods[] = { JS_FN("arrayBuffer", Request::bodyAll, 0, JSPROP_ENUMERATE), JS_FN("blob", Request::bodyAll, 0, JSPROP_ENUMERATE), JS_FN("formData", Request::bodyAll, 0, JSPROP_ENUMERATE), JS_FN("json", Request::bodyAll, 0, JSPROP_ENUMERATE), JS_FN("text", Request::bodyAll, 0, JSPROP_ENUMERATE), JS_FN("setCacheOverride", Request::setCacheOverride, 3, JSPROP_ENUMERATE), JS_FN("setCacheKey", Request::setCacheKey, 0, JSPROP_ENUMERATE), JS_FN("setManualFramingHeaders", Request::setManualFramingHeaders, 1, JSPROP_ENUMERATE), JS_FN("clone", Request::clone, 0, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec Request::properties[] = { JS_PSG("method", method_get, JSPROP_ENUMERATE), JS_PSG("url", url_get, JSPROP_ENUMERATE), JS_PSG("version", version_get, JSPROP_ENUMERATE), JS_PSG("headers", headers_get, JSPROP_ENUMERATE), JS_PSG("backend", backend_get, JSPROP_ENUMERATE), JS_PSG("body", body_get, JSPROP_ENUMERATE), JS_PSG("bodyUsed", bodyUsed_get, JSPROP_ENUMERATE), JS_PSG("isCacheable", isCacheable_get, JSPROP_ENUMERATE), JS_STRING_SYM_PS(toStringTag, "Request", JSPROP_READONLY), JS_PS_END, }; bool Request::init_class(JSContext *cx, JS::HandleObject global) { if (!init_class_impl(cx, global)) { return false; } // Initialize a pinned (i.e., never-moved, living forever) atom for the // default HTTP method. GET_atom = JS_AtomizeAndPinString(cx, "GET"); return !!GET_atom; } JSObject *Request::create(JSContext *cx, JS::HandleObject requestInstance, host_api::HttpReq request_handle, host_api::HttpBody body_handle, bool is_downstream) { JS::SetReservedSlot(requestInstance, static_cast(Slots::Request), JS::Int32Value(request_handle.handle)); JS::SetReservedSlot(requestInstance, static_cast(Slots::Headers), JS::NullValue()); JS::SetReservedSlot(requestInstance, static_cast(Slots::Body), JS::Int32Value(body_handle.handle)); JS::SetReservedSlot(requestInstance, static_cast(Slots::BodyStream), JS::NullValue()); JS::SetReservedSlot(requestInstance, static_cast(Slots::HasBody), JS::FalseValue()); JS::SetReservedSlot(requestInstance, static_cast(Slots::BodyUsed), JS::FalseValue()); JS::SetReservedSlot(requestInstance, static_cast(Slots::Method), JS::StringValue(GET_atom)); JS::SetReservedSlot(requestInstance, static_cast(Slots::OverrideCacheKey), JS::NullValue()); JS::SetReservedSlot(requestInstance, static_cast(Slots::CacheOverride), JS::NullValue()); JS::SetReservedSlot(requestInstance, static_cast(Slots::ImageOptimizerOptions), JS::NullValue()); JS::SetReservedSlot(requestInstance, static_cast(Slots::IsDownstream), JS::BooleanValue(is_downstream)); return requestInstance; } /** * Create a new Request object, roughly according to * https://fetch.spec.whatwg.org/#dom-request * * "Roughly" because not all aspects of Request handling make sense in Fastly Compute. * The places where we deviate from the spec are called out inline. */ JSObject *Request::create(JSContext *cx, JS::HandleObject requestInstance, JS::HandleValue input, JS::HandleValue init_val) { auto request_handle_res = host_api::HttpReq::make(); if (auto *err = request_handle_res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } auto body = host_api::HttpBody::make(); if (auto *err = body.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } auto request_handle = request_handle_res.unwrap(); JS::RootedObject request(cx, create(cx, requestInstance, request_handle, body.unwrap(), false)); if (!request) { return nullptr; } JS::RootedString url_str(cx); JS::RootedString method_str(cx); bool method_needs_normalization = false; JS::RootedObject input_request(cx); JS::RootedValue input_headers(cx); bool input_has_body = false; // 1. Let `request` be null. // 4. Let `signal` be null. // (implicit) // 2. Let `fallbackMode` be null. // (N/A) // 3. Let `baseURL` be this’s relevant settings object’s API base URL. // (implicit) // 6. Otherwise: // (reordered because it's easier to check is_instance and otherwise // stringify.) if (is_instance(input)) { input_request = &input.toObject(); input_has_body = RequestOrResponse::has_body(input_request); // 1. Assert: `input` is a `Request` object. // 2. Set `request` to `input`’s request. // (implicit) // 3. Set `signal` to `input`’s signal. // (signals not yet supported) // 12. Set `request` to a new request with the following properties: // (moved into step 6 because we can leave everything at the default values // if step 5 runs.) URL: `request`’s URL. Will actually be applied below. url_str = RequestOrResponse::url(input_request).toString(); // method: `request`’s method. method_str = Request::method(cx, input_request); if (!method_str) { return nullptr; } // referrer: `request`’s referrer. // TODO: evaluate whether we want to implement support for setting the // `referer` [sic] header based on this or not. // cache mode: `request`’s cache mode. // TODO: implement support for cache mode-based headers setting. // header list: A copy of `request`’s header list. // Note: copying the headers is postponed, see step 32 below. JS::RootedObject headers_obj(cx, Request::headers(cx, input_request)); if (!headers_obj) { return nullptr; } input_headers = JS::ObjectValue(*headers_obj); // The following properties aren't applicable: // unsafe-request flag: Set. // client: This’s relevant settings object. // window: `window`. // priority: `request`’s priority // origin: `request`’s origin. // referrer policy: `request`’s referrer policy. // mode: `request`’s mode. // credentials mode: `request`’s credentials mode. // redirect mode: `request`’s redirect mode. // integrity metadata: `request`’s integrity metadata. // keepalive: `request`’s keepalive. // reload-navigation flag: `request`’s reload-navigation flag. // history-navigation flag: `request`’s history-navigation flag. // URL list: A clone of `request`’s URL list. } // 5. If `input` is a string, then: else { // 1. Let `parsedURL` be the result of parsing `input` with `baseURL`. JS::RootedObject url_instance(cx, JS_NewObjectWithGivenProto(cx, &URL::class_, URL::proto_obj)); if (!url_instance) return nullptr; JS::RootedObject parsedURL(cx, URL::create(cx, url_instance, input, fastly::Fastly::baseURL)); // 2. If `parsedURL` is failure, then throw a `TypeError`. if (!parsedURL) { return nullptr; } // 3. If `parsedURL` includes credentials, then throw a `TypeError`. // (N/A) // 4. Set `request` to a new request whose URL is `parsedURL`. // Instead, we store `url_str` to apply below. JS::RootedValue url_val(cx, JS::ObjectValue(*parsedURL)); url_str = JS::ToString(cx, url_val); if (!url_str) { return nullptr; } // 5. Set `fallbackMode` to "`cors`". // (N/A) } // Actually set the URL derived in steps 5 or 6 above. RequestOrResponse::set_url(request, StringValue(url_str)); auto url = core::encode(cx, url_str); if (!url) { return nullptr; } else { auto res = request_handle.set_uri(url); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } } // 7. Let `origin` be this’s relevant settings object’s origin. // 8. Let `window` be "`client`". // 9. If `request`’s window is an environment settings object and its origin // is same origin with `origin`, then set `window` to `request`’s window. // 10. If `init`["window"] exists and is non-null, then throw a `TypeError. // 11. If `init`["window"] exists, then set `window` to "`no-window`". // (N/A) // Extract all relevant properties from the init object. // TODO: evaluate how much we care about precisely matching evaluation order. // If "a lot", we need to make sure that all side effects that value // conversions might trigger occur in the right order—presumably by running // them all right here as WebIDL bindings would. JS::RootedValue method_val(cx); JS::RootedValue headers_val(cx); JS::RootedValue body_val(cx); JS::RootedValue backend_val(cx); JS::RootedValue cache_override(cx); JS::RootedValue cache_key(cx); JS::RootedValue fastly_val(cx); JS::RootedValue image_optimizer_options(cx); bool hasManualFramingHeaders = false; bool setManualFramingHeaders = false; if (init_val.isObject()) { JS::RootedValue manualFramingHeaders(cx); JS::RootedObject init(cx, init_val.toObjectOrNull()); if (!JS_GetProperty(cx, init, "method", &method_val) || !JS_GetProperty(cx, init, "headers", &headers_val) || !JS_GetProperty(cx, init, "body", &body_val) || !JS_GetProperty(cx, init, "backend", &backend_val) || !JS_GetProperty(cx, init, "cacheOverride", &cache_override) || !JS_GetProperty(cx, init, "cacheKey", &cache_key) || !JS_GetProperty(cx, init, "fastly", &fastly_val) || !JS_HasOwnProperty(cx, init, "manualFramingHeaders", &hasManualFramingHeaders) || !JS_GetProperty(cx, init, "manualFramingHeaders", &manualFramingHeaders) || !JS_GetProperty(cx, init, "imageOptimizerOptions", &image_optimizer_options)) { return nullptr; } setManualFramingHeaders = manualFramingHeaders.isBoolean() && manualFramingHeaders.toBoolean(); } else if (!init_val.isNullOrUndefined()) { JS_ReportErrorLatin1(cx, "Request constructor: |init| parameter can't be converted to " "a dictionary"); return nullptr; } // 13. If `init` is not empty, then: // 1. If `request`’s mode is "`navigate`", then set it to "`same-origin`". // 2. Unset `request`’s reload-navigation flag. // 3. Unset `request`’s history-navigation flag. // 4. Set `request`’s origin to "`client`". // 5. Set `request`’s referrer to "`client`". // 6. Set `request`’s referrer policy to the empty string. // 7. Set `request`’s URL to `request`’s current URL. // 8. Set `request`’s URL list to « `request`’s URL ». // (N/A) // 14. If `init["referrer"]` exists, then: // TODO: implement support for referrer application. // 1. Let `referrer` be `init["referrer"]`. // 2. If `referrer` is the empty string, then set `request`’s referrer to // "`no-referrer`". // 3. Otherwise: // 1. Let `parsedReferrer` be the result of parsing `referrer` with // `baseURL`. // 2. If `parsedReferrer` is failure, then throw a `TypeError`. // 3. If one of the following is true // * `parsedReferrer`’s scheme is "`about`" and path is the string // "`client`" // * `parsedReferrer`’s origin is not same origin with `origin` // then set `request`’s referrer to "`client`". // (N/A) // 4. Otherwise, set `request`’s referrer to `parsedReferrer`. // 15. If `init["referrerPolicy"]` exists, then set `request`’s referrer // policy to it. // 16. Let `mode` be `init["mode"]` if it exists, and `fallbackMode` // otherwise. // 17. If `mode` is "`navigate`", then throw a `TypeError`. // 18. If `mode` is non-null, set `request`’s mode to `mode`. // 19. If `init["credentials"]` exists, then set `request`’s credentials mode // to it. (N/A) // 20. If `init["cache"]` exists, then set `request`’s cache mode to it. // TODO: implement support for cache mode application. // 21. If `request`’s cache mode is "`only-if-cached`" and `request`’s mode // is _not_ // "`same-origin`", then throw a TypeError. // 22. If `init["redirect"]` exists, then set `request`’s redirect mode to // it. // 23. If `init["integrity"]` exists, then set `request`’s integrity metadata // to it. // 24. If `init["keepalive"]` exists, then set `request`’s keepalive to it. // (N/A) // 25. If `init["method"]` exists, then: if (!method_val.isUndefined()) { // 1. Let `method` be `init["method"]`. method_str = JS::ToString(cx, method_val); if (!method_str) { return nullptr; } // 2. If `method` is not a method or `method` is a forbidden method, then // throw a // `TypeError`. // TODO: evaluate whether we should barr use of methods forbidden by the // WHATWG spec. // 3. Normalize `method`. // Delayed to below to reduce some code duplication. method_needs_normalization = true; // 4. Set `request`’s method to `method`. // Done below, unified with the non-init case. } // Apply the method derived in step 6 or 25. // This only needs to happen if the method was set explicitly and isn't the // default `GET`. bool is_get = true; if (method_str && !JS_StringEqualsLiteral(cx, method_str, "GET", &is_get)) { return nullptr; } bool is_get_or_head = is_get; if (!is_get) { auto method = core::encode(cx, method_str); if (!method) { return nullptr; } if (method_needs_normalization) { if (common::normalize_http_method(method.begin(), method.len)) { // Replace the JS string with the normalized name. method_str = JS_NewStringCopyN(cx, method.begin(), method.len); if (!method_str) { return nullptr; } } } is_get_or_head = strcmp(method.begin(), "GET") == 0 || strcmp(method.begin(), "HEAD") == 0; JS::SetReservedSlot(request, static_cast(Slots::Method), JS::StringValue(method_str)); auto res = request_handle.set_method(method); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } } // 26. If `init["signal"]` exists, then set `signal` to it. // (signals NYI) // 27. Set this’s request to `request`. // (implicit) // 28. Set this’s signal to a new `AbortSignal` object with this’s relevant // Realm. // 29. If `signal` is not null, then make this’s signal follow `signal`. // (signals NYI) // 30. Set this’s headers to a new `Headers` object with this’s relevant // Realm, whose header list is `request`’s header list and guard is // "`request`". (implicit) // 31. If this’s requests mode is "`no-cors`", then: // 1. If this’s requests method is not a CORS-safelisted method, then throw a // `TypeError`. // 2. Set this’s headers’s guard to "`request-no-cors`". // (N/A) // 32. If `init` is not empty, then: // 1. Let `headers` be a copy of this’s headers and its associated header // list. // 2. If `init["headers"]` exists, then set `headers` to `init["headers"]`. // 3. Empty this’s headers’s header list. // 4. If `headers` is a `Headers` object, then for each `header` in its // header list, append (`header`’s name, `header`’s value) to this’s headers. // 5. Otherwise, fill this’s headers with `headers`. // Note: the substeps of 32 are somewhat convoluted because they don't just // serve to ensure that the contents of `init["headers"]` are added to the // request's headers, but also that all headers, including those from the // `input` object are sanitized in accordance with the request's `mode`. Since // we don't implement this sanitization, we do a much simpler thing: if // `init["headers"]` exists, create the request's `headers` from that, // otherwise create it from the `init` object's `headers`, or create a new, // empty one. JS::RootedObject headers(cx); if (!headers_val.isUndefined()) { headers = Headers::create(cx, headers_val, Headers::HeadersGuard::Request); } else { headers = Headers::create(cx, input_headers, Headers::HeadersGuard::Request); } if (!headers) { return nullptr; } JS::SetReservedSlot(request, static_cast(Slots::Headers), JS::ObjectValue(*headers)); // 33. Let `inputBody` be `input`’s requests body if `input` is a `Request` // object; // otherwise null. // (skipped) // 34. If either `init["body"]` exists and is non-null or `inputBody` is // non-null, and `request`’s method is ``GET`` or ``HEAD``, then throw a // TypeError. if ((input_has_body || !body_val.isNullOrUndefined()) && is_get_or_head) { api::throw_error(cx, FetchErrors::InvalidInitArg, "Request constructor"); return nullptr; } // 35. Let `initBody` be null. // (skipped) // Note: steps 36-41 boil down to "if there's an init body, use that. // Otherwise, if there's an input body, use that, but proxied through a // TransformStream to make sure it's not consumed by something else in the // meantime." Given that, we're restructuring things quite a bit below. // 36. If `init["body"]` exists and is non-null, then: if (!body_val.isNullOrUndefined()) { // 1. Let `Content-Type` be null. // 2. Set `initBody` and `Content-Type` to the result of extracting // `init["body"]`, with // `keepalive` set to `request`’s keepalive. // 3. If `Content-Type` is non-null and this’s headers’s header list does // not contain // ``Content-Type``, then append (``Content-Type``, `Content-Type`) to // this’s headers. // Note: these steps are all inlined into RequestOrResponse::extract_body. if (!RequestOrResponse::extract_body(cx, request, body_val)) { return nullptr; } } else if (input_has_body) { // 37. Let `inputOrInitBody` be `initBody` if it is non-null; otherwise // `inputBody`. (implicit) // 38. If `inputOrInitBody` is non-null and `inputOrInitBody`’s source is // null, then: // 1. If this’s requests mode is neither "`same-origin`" nor "`cors`", then // throw a `TypeError. // 2. Set this’s requests use-CORS-preflight flag. // (N/A) // 39. Let `finalBody` be `inputOrInitBody`. // 40. If `initBody` is null and `inputBody` is non-null, then: // (implicit) // 1. If `input` is unusable, then throw a TypeError. // 2. Set `finalBody` to the result of creating a proxy for `inputBody`. // All the above steps boil down to "if the input request has an unusable // body, throw. Otherwise, use the body." Our implementation is a bit more // involved, because we might not have a body reified as a ReadableStream at // all, in which case we can directly append the input body to the new // request's body with a single hostcall. JS::RootedObject inputBody(cx, RequestOrResponse::body_stream(input_request)); // Throw an error if the input request's body isn't usable. if (RequestOrResponse::body_used(input_request) || (inputBody && RequestOrResponse::body_unusable(cx, inputBody))) { JS_ReportErrorLatin1(cx, "Request constructor: the input request's body isn't usable."); return nullptr; } if (!inputBody) { // If `inputBody` is null, that means that it was never created, and hence // content can't have access to it. Instead of reifying it here to pass it // into a TransformStream, we just append the body on the host side and // mark it as used on the input Request. RequestOrResponse::append_body(cx, request, input_request); RequestOrResponse::mark_body_used(cx, input_request); } else { // Track source Request with native body before creating proxy bool has_native_body = NativeStreamSource::stream_is_body(cx, inputBody); if (has_native_body) { // Technically speaking, the spec says we must create a proxy, // but this has caused us so many problems that we're going to cheat and just // re-use the existing stream. set_up_shortcutting(cx, inputBody, request); } else { inputBody = TransformStream::create_rs_proxy(cx, inputBody); if (!inputBody) { return nullptr; } TransformStream::set_readable_used_as_body(cx, inputBody, request); } JS::SetReservedSlot(request, static_cast(Slots::BodyStream), JS::ObjectValue(*inputBody)); } JS::SetReservedSlot(request, static_cast(Slots::HasBody), JS::BooleanValue(true)); } // 41. Set this’s requests body to `finalBody`. // (implicit) // Apply the Fastly Compute-proprietary `backend` property. if (!backend_val.isUndefined()) { JS::RootedString backend(cx, JS::ToString(cx, backend_val)); if (!backend) { return nullptr; } JS::SetReservedSlot(request, static_cast(Slots::Backend), JS::StringValue(backend)); } else if (input_request) { JS::SetReservedSlot(request, static_cast(Slots::Backend), JS::GetReservedSlot(input_request, static_cast(Slots::Backend))); } // Apply the Fastly Compute-proprietary `cacheOverride` property. if (!cache_override.isUndefined()) { if (!set_cache_override(cx, request, cache_override)) { return nullptr; } } else if (input_request) { JS::SetReservedSlot( request, static_cast(Slots::CacheOverride), JS::GetReservedSlot(input_request, static_cast(Slots::CacheOverride))); } // Apply the Fastly Compute-proprietary `cacheKey` property. if (!cache_key.isUndefined()) { if (!set_cache_key(cx, request, cache_key)) { return nullptr; } } else if (input_request) { // The fastly-xqd-cache-key header will be copied as part of the header copying logic, // but we need to copy the slot as well to preserve the invariant that the slot and header are // in sync. JS::SetReservedSlot( request, static_cast(Slots::OverrideCacheKey), JS::GetReservedSlot(input_request, static_cast(Slots::OverrideCacheKey))); } // Apply the Fastly Compute-proprietary `imageOptimizerOptions` property. if (!image_optimizer_options.isUndefined()) { if (!set_image_optimizer_options(cx, request, image_optimizer_options)) { return nullptr; } } if (fastly_val.isObject()) { JS::RootedValue decompress_response_val(cx); JS::RootedObject fastly(cx, fastly_val.toObjectOrNull()); if (!JS_GetProperty(cx, fastly, "decompressGzip", &decompress_response_val)) { return nullptr; } auto value = JS::ToBoolean(decompress_response_val); JS::SetReservedSlot(request, static_cast(Slots::AutoDecompressGzip), JS::BooleanValue(value)); } else if (input_request) { JS::SetReservedSlot( request, static_cast(Slots::AutoDecompressGzip), JS::GetReservedSlot(input_request, static_cast(Slots::AutoDecompressGzip))); } else { JS::SetReservedSlot(request, static_cast(Slots::AutoDecompressGzip), JS::BooleanValue(false)); } if (!hasManualFramingHeaders) { if (input_request) { auto val = JS::GetReservedSlot(input_request, static_cast(Slots::ManualFramingHeaders)); setManualFramingHeaders = val.isBoolean() && val.toBoolean(); } } JS::SetReservedSlot(request, static_cast(Slots::ManualFramingHeaders), JS::BooleanValue(setManualFramingHeaders)); if (setManualFramingHeaders) { auto res = request_handle.set_framing_headers_mode(host_api::FramingHeadersMode::ManuallyFromHeaders); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } } return request; } JSObject *Request::create_instance(JSContext *cx) { JS::RootedObject requestInstance( cx, JS_NewObjectWithGivenProto(cx, &Request::class_, Request::proto_obj)); return requestInstance; } bool Request::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The Request builtin"); CTOR_HEADER("Request", 1); JS::RootedObject requestInstance(cx, JS_NewObjectForConstructor(cx, &class_, args)); JS::RootedObject request(cx, create(cx, requestInstance, args[0], args.get(1))); if (!request) return false; args.rval().setObject(*request); return true; } // Needed for uniform access to Request and Response slots. static_assert((int)Response::Slots::Body == (int)Request::Slots::Body); static_assert((int)Response::Slots::BodyStream == (int)Request::Slots::BodyStream); static_assert((int)Response::Slots::HasBody == (int)Request::Slots::HasBody); static_assert((int)Response::Slots::BodyUsed == (int)Request::Slots::BodyUsed); static_assert((int)Response::Slots::Headers == (int)Request::Slots::Headers); static_assert((int)Response::Slots::Response == (int)Request::Slots::Request); host_api::HttpResp Response::response_handle(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); return host_api::HttpResp( JS::GetReservedSlot(obj, static_cast(Slots::Response)).toInt32()); } bool Response::is_upstream(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); return JS::GetReservedSlot(obj, static_cast(Slots::IsUpstream)).toBoolean(); } std::optional Response::grip_upgrade_request(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); auto grip_upgrade_request = JS::GetReservedSlot(obj, static_cast(Slots::GripUpgradeRequest)); if (grip_upgrade_request.isUndefined()) { return std::nullopt; } return host_api::HttpReq(grip_upgrade_request.toInt32()); } std::optional Response::websocket_upgrade_request(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); auto websocket_upgrade_request = JS::GetReservedSlot(obj, static_cast(Slots::WebsocketUpgradeRequest)); if (websocket_upgrade_request.isUndefined()) { return std::nullopt; } return host_api::HttpReq(websocket_upgrade_request.toInt32()); } host_api::HostString Response::backend_str(JSContext *cx, JSObject *obj) { MOZ_ASSERT(is_instance(obj)); RootedValue backend(cx, JS::GetReservedSlot(obj, static_cast(Slots::Backend))); MOZ_ASSERT(backend.isString()); return core::encode(cx, backend); } uint16_t Response::status(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); return (uint16_t)JS::GetReservedSlot(obj, static_cast(Slots::Status)).toInt32(); } JSString *Response::status_message(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); return JS::GetReservedSlot(obj, static_cast(Slots::StatusMessage)).toString(); } // TODO(jake): Remove this when the reason phrase host-call is implemented void Response::set_status_message_from_code(JSContext *cx, JSObject *obj, uint16_t code) { auto phrase = ""; switch (code) { case 100: // 100 Continue - https://tools.ietf.org/html/rfc7231#section-6.2.1 phrase = "Continue"; break; case 101: // 101 Switching Protocols - https://tools.ietf.org/html/rfc7231#section-6.2.2 phrase = "Switching Protocols"; break; case 102: // 102 Processing - https://tools.ietf.org/html/rfc2518 phrase = "Processing"; break; case 200: // 200 OK - https://tools.ietf.org/html/rfc7231#section-6.3.1 phrase = "OK"; break; case 201: // 201 Created - https://tools.ietf.org/html/rfc7231#section-6.3.2 phrase = "Created"; break; case 202: // 202 Accepted - https://tools.ietf.org/html/rfc7231#section-6.3.3 phrase = "Accepted"; break; case 203: // 203 Non-Authoritative Information - https://tools.ietf.org/html/rfc7231#section-6.3.4 phrase = "Non Authoritative Information"; break; case 204: // 204 No Content - https://tools.ietf.org/html/rfc7231#section-6.3.5 phrase = "No Content"; break; case 205: // 205 Reset Content - https://tools.ietf.org/html/rfc7231#section-6.3.6 phrase = "Reset Content"; break; case 206: // 206 Partial Content - https://tools.ietf.org/html/rfc7233#section-4.1 phrase = "Partial Content"; break; case 207: // 207 Multi-Status - https://tools.ietf.org/html/rfc4918 phrase = "Multi-Status"; break; case 208: // 208 Already Reported - https://tools.ietf.org/html/rfc5842 phrase = "Already Reported"; break; case 226: // 226 IM Used - https://tools.ietf.org/html/rfc3229 phrase = "IM Used"; break; case 300: // 300 Multiple Choices - https://tools.ietf.org/html/rfc7231#section-6.4.1 phrase = "Multiple Choices"; break; case 301: // 301 Moved Permanently - https://tools.ietf.org/html/rfc7231#section-6.4.2 phrase = "Moved Permanently"; break; case 302: // 302 Found - https://tools.ietf.org/html/rfc7231#section-6.4.3 phrase = "Found"; break; case 303: // 303 See Other - https://tools.ietf.org/html/rfc7231#section-6.4.4 phrase = "See Other"; break; case 304: // 304 Not Modified - https://tools.ietf.org/html/rfc7232#section-4.1 phrase = "Not Modified"; break; case 305: // 305 Use Proxy - https://tools.ietf.org/html/rfc7231#section-6.4.5 phrase = "Use Proxy"; break; case 307: // 307 Temporary Redirect - https://tools.ietf.org/html/rfc7231#section-6.4.7 phrase = "Temporary Redirect"; break; case 308: // 308 Permanent Redirect - https://tools.ietf.org/html/rfc7238 phrase = "Permanent Redirect"; break; case 400: // 400 Bad Request - https://tools.ietf.org/html/rfc7231#section-6.5.1 phrase = "Bad Request"; break; case 401: // 401 Unauthorized - https://tools.ietf.org/html/rfc7235#section-3.1 phrase = "Unauthorized"; break; case 402: // 402 Payment Required - https://tools.ietf.org/html/rfc7231#section-6.5.2 phrase = "Payment Required"; break; case 403: // 403 Forbidden - https://tools.ietf.org/html/rfc7231#section-6.5.3 phrase = "Forbidden"; break; case 404: // 404 Not Found - https://tools.ietf.org/html/rfc7231#section-6.5.4 phrase = "Not Found"; break; case 405: // 405 Method Not Allowed - https://tools.ietf.org/html/rfc7231#section-6.5.5 phrase = "Method Not Allowed"; break; case 406: // 406 Not Acceptable - https://tools.ietf.org/html/rfc7231#section-6.5.6 phrase = "Not Acceptable"; break; case 407: // 407 Proxy Authentication Required - https://tools.ietf.org/html/rfc7235#section-3.2 phrase = "Proxy Authentication Required"; break; case 408: // 408 Request Timeout - https://tools.ietf.org/html/rfc7231#section-6.5.7 phrase = "Request Timeout"; break; case 409: // 409 Conflict - https://tools.ietf.org/html/rfc7231#section-6.5.8 phrase = "Conflict"; break; case 410: // 410 Gone - https://tools.ietf.org/html/rfc7231#section-6.5.9 phrase = "Gone"; break; case 411: // 411 Length Required - https://tools.ietf.org/html/rfc7231#section-6.5.10 phrase = "Length Required"; break; case 412: // 412 Precondition Failed - https://tools.ietf.org/html/rfc7232#section-4.2 phrase = "Precondition Failed"; break; case 413: // 413 Payload Too Large - https://tools.ietf.org/html/rfc7231#section-6.5.11 phrase = "Payload Too Large"; break; case 414: // 414 URI Too Long - https://tools.ietf.org/html/rfc7231#section-6.5.12 phrase = "URI Too Long"; break; case 415: // 415 Unsupported Media Type - https://tools.ietf.org/html/rfc7231#section-6.5.13 phrase = "Unsupported Media Type"; break; case 416: // 416 Range Not Satisfiable - https://tools.ietf.org/html/rfc7233#section-4.4 phrase = "Range Not Satisfiable"; break; case 417: // 417 Expectation Failed - https://tools.ietf.org/html/rfc7231#section-6.5.14 phrase = "Expectation Failed"; break; case 418: // 418 I'm a teapot - https://tools.ietf.org/html/rfc2324 phrase = "I'm a teapot"; break; case 421: // 421 Misdirected Request - http://tools.ietf.org/html/rfc7540#section-9.1.2 phrase = "Misdirected Request"; break; case 422: // 422 Unprocessable Entity - https://tools.ietf.org/html/rfc4918 phrase = "Unprocessable Entity"; break; case 423: // 423 Locked - https://tools.ietf.org/html/rfc4918 phrase = "Locked"; break; case 424: // 424 Failed Dependency - https://tools.ietf.org/html/rfc4918 phrase = "Failed Dependency"; break; case 426: // 426 Upgrade Required - https://tools.ietf.org/html/rfc7231#section-6.5.15 phrase = "Upgrade Required"; break; case 428: // 428 Precondition Required - https://tools.ietf.org/html/rfc6585 phrase = "Precondition Required"; break; case 429: // 429 Too Many Requests - https://tools.ietf.org/html/rfc6585 phrase = "Too Many Requests"; break; case 431: // 431 Request Header Fields Too Large - https://tools.ietf.org/html/rfc6585 phrase = "Request Header Fields Too Large"; break; case 451: // 451 Unavailable For Legal Reasons - http://tools.ietf.org/html/rfc7725 phrase = "Unavailable For Legal Reasons"; break; case 500: // 500 Internal Server Error - https://tools.ietf.org/html/rfc7231#section-6.6.1 phrase = "Internal Server Error"; break; case 501: // 501 Not Implemented - https://tools.ietf.org/html/rfc7231#section-6.6.2 phrase = "Not Implemented"; break; case 502: // 502 Bad Gateway - https://tools.ietf.org/html/rfc7231#section-6.6.3 phrase = "Bad Gateway"; break; case 503: // 503 Service Unavailable - https://tools.ietf.org/html/rfc7231#section-6.6.4 phrase = "Service Unavailable"; break; case 504: // 504 Gateway Timeout - https://tools.ietf.org/html/rfc7231#section-6.6.5 phrase = "Gateway Timeout"; break; case 505: // 505 HTTP Version Not Supported - https://tools.ietf.org/html/rfc7231#section-6.6.6 phrase = "HTTP Version Not Supported"; break; case 506: // 506 Variant Also Negotiates - https://tools.ietf.org/html/rfc2295 phrase = "Variant Also Negotiates"; break; case 507: // 507 Insufficient Storage - https://tools.ietf.org/html/rfc4918 phrase = "Insufficient Storage"; break; case 508: // 508 Loop Detected - https://tools.ietf.org/html/rfc5842 phrase = "Loop Detected"; break; case 510: // 510 Not Extended - https://tools.ietf.org/html/rfc2774 phrase = "Not Extended"; break; case 511: // 511 Network Authentication Required - https://tools.ietf.org/html/rfc6585 phrase = "Network Authentication Required"; break; default: phrase = ""; break; } JS::RootedString phrase_js(cx, JS_NewStringCopyZ(cx, phrase)); JS::SetReservedSlot(obj, static_cast(Slots::StatusMessage), JS::StringValue(phrase_js)); } bool Response::ok_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) uint16_t status = Response::status(self); args.rval().setBoolean(status >= 200 && status < 300); return true; } bool Response::status_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().setInt32(status(self)); return true; } bool Response::status_set(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto maybe_cache_entry = RequestOrResponse::cache_entry(self); if (!maybe_cache_entry.has_value()) { args.rval().set(args[0]); return true; } // If it _is_ a CandidateResponse, then support the status set, with validation bool valid_status = true; uint16_t status = 0; if (!args[0].isNumber() || !JS::ToUint16(cx, args[0], &status)) { valid_status = false; } // Allow 103: Early Hints bool status_in_range = status == 103 || (status >= 200 && status < 600); if (!valid_status || !status_in_range) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_CONSTRUCTOR_INVALID_STATUS, status); return false; } auto res = response_handle(self).set_status(status); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } return true; } bool Response::statusText_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().setString(status_message(self)); return true; } bool Response::url_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().set(RequestOrResponse::url(self)); return true; } // TODO: store version client-side, support version_set for HTTP cache Candidate Response flow. bool Response::version_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto res = response_handle(self).get_version(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setInt32(res.unwrap()); return true; } namespace { JSString *type_default_atom; JSString *type_error_atom; } // namespace bool Response::type_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().setString(status(self) == 0 ? type_error_atom : type_default_atom); return true; } bool Response::redirected_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().setBoolean( JS::GetReservedSlot(self, static_cast(Slots::Redirected)).toBoolean()); return true; } bool Response::headers_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JSObject *headers = Response::headers(cx, self); if (!headers) return false; args.rval().setObject(*headers); return true; } template bool Response::bodyAll(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) return RequestOrResponse::bodyAll(cx, args, self); } bool Response::body_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) return RequestOrResponse::body_get(cx, args, self, true); } bool Response::backend_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) return RequestOrResponse::backend_get(cx, args, self); } bool Response::bodyUsed_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().setBoolean(RequestOrResponse::body_used(self)); return true; } bool Response::ip_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) // non-upstream responses always have undefined IP if (!Response::is_upstream(self)) { args.rval().setUndefined(); return true; } auto handle = response_handle(self); auto res = handle.get_ip(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto ret = std::move(res.unwrap()); if (!ret.has_value()) { args.rval().setUndefined(); return true; } JS::RootedString address(cx, common::ip_octets_to_js_string(cx, std::move(*ret))); if (!address) { return false; } args.rval().setString(address); return true; } bool Response::port_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) // non-upstream responses always have undefined port if (!Response::is_upstream(self)) { args.rval().setUndefined(); return true; } auto handle = response_handle(self); auto res = handle.get_port(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setUndefined(); } else { args.rval().setInt32(res.unwrap().value()); } return true; } // https://fetch.spec.whatwg.org/#dom-response-redirect // [NewObject] static Response redirect(USVString url, optional unsigned short status = 302); bool Response::redirect(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "redirect", 1)) { return false; } auto url = args.get(0); // 1. Let parsedURL be the result of parsing url with current settings object’s API base URL. JS::RootedObject urlInstance(cx, JS_NewObjectWithGivenProto(cx, &URL::class_, URL::proto_obj)); if (!urlInstance) { return false; } JS::RootedObject parsedURL(cx, URL::create(cx, urlInstance, url, WorkerLocation::url)); // 2. If parsedURL is failure, then throw a TypeError. if (!parsedURL) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_REDIRECT_INVALID_URI); return false; } JS::RootedValue url_val(cx, JS::ObjectValue(*parsedURL)); auto url_str = core::encode(cx, url_val); if (!url_str) { return false; } // 3. If status is not a redirect status, then throw a RangeError. // A redirect status is a status that is 301, 302, 303, 307, or 308. auto statusVal = args.get(1); uint16_t status; if (statusVal.isUndefined()) { status = 302; } else { if (!JS::ToUint16(cx, statusVal, &status)) { return false; } } if (status != 301 && status != 302 && status != 303 && status != 307 && status != 308) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_REDIRECT_INVALID_STATUS); return false; } // 4. Let responseObject be the result of creating a Response object, given a new response, // "immutable", and this’s relevant Realm. auto response_handle_res = host_api::HttpResp::make(); if (auto *err = response_handle_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto response_handle = response_handle_res.unwrap(); if (!response_handle.is_valid()) { return false; } auto make_res = host_api::HttpBody::make(); if (auto *err = make_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body = make_res.unwrap(); JS::RootedObject response_instance( cx, JS_NewObjectWithGivenProto(cx, &Response::class_, Response::proto_obj)); if (!response_instance) { return false; } JS::RootedObject response( cx, create(cx, response_instance, response_handle, body, false, nullptr, nullptr, nullptr)); if (!response) { return false; } // 5. Set responseObject’s response’s status to status. auto set_res = response_handle.set_status(status); if (auto *err = set_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } // To ensure that we really have the same status value as the host, // we always read it back here. auto get_res = response_handle.get_status(); if (auto *err = get_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } status = get_res.unwrap(); JS::SetReservedSlot(response, static_cast(Slots::Status), JS::Int32Value(status)); JS::RootedString statusText(cx, JS_GetEmptyString(cx)); JS::SetReservedSlot(response, static_cast(Slots::StatusMessage), JS::StringValue(statusText)); // 6. Let value be parsedURL, serialized and isomorphic encoded. // 7. Append (`Location`, value) to responseObject’s response’s header list. JS::RootedObject headers(cx, Headers::create(cx, Headers::HeadersGuard::Response)); if (!headers) { return false; } if (!Headers::set_valid_if_undefined(cx, headers, "location", url_str.begin())) { return false; } JS::SetReservedSlot(response, static_cast(Slots::Headers), JS::ObjectValue(*headers)); JS::SetReservedSlot(response, static_cast(Slots::Redirected), JS::FalseValue()); // 8. Return responseObject. args.rval().setObjectOrNull(response); return true; } namespace { bool callbackCalled; bool write_json_to_buf(const char16_t *str, uint32_t strlen, void *out) { callbackCalled = true; auto outstr = static_cast(out); outstr->append(str, strlen); return true; } } // namespace bool Response::json(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "json", 1)) { return false; } JS::RootedValue data(cx, args.get(0)); JS::RootedValue init_val(cx, args.get(1)); JS::RootedObject replacer(cx); JS::RootedValue space(cx); std::u16string out; // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. callbackCalled = false; if (!JS::ToJSON(cx, data, replacer, space, &write_json_to_buf, &out)) { return false; } if (!callbackCalled) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_JSON_INVALID_VALUE); return false; } // 2. Let body be the result of extracting bytes. // 3. Let responseObject be the result of creating a Response object, given a new response, // "response", and this’s relevant Realm. JS::RootedValue status_val(cx); uint16_t status = 200; JS::RootedValue statusText_val(cx); JS::RootedString statusText(cx, JS_GetEmptyString(cx)); JS::RootedValue headers_val(cx); if (init_val.isObject()) { JS::RootedObject init(cx, init_val.toObjectOrNull()); if (!JS_GetProperty(cx, init, "status", &status_val) || !JS_GetProperty(cx, init, "statusText", &statusText_val) || !JS_GetProperty(cx, init, "headers", &headers_val)) { return false; } if (!status_val.isUndefined() && !JS::ToUint16(cx, status_val, &status)) { return false; } if (status == 103 || status == 204 || status == 205 || status == 304) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_NULL_BODY_STATUS_WITH_BODY); return false; } if (!statusText_val.isUndefined() && !(statusText = JS::ToString(cx, statusText_val))) { return false; } } else if (!init_val.isNullOrUndefined()) { JS_ReportErrorLatin1(cx, "Response constructor: |init| parameter can't be converted to " "a dictionary"); return false; } auto response_handle_res = host_api::HttpResp::make(); if (auto *err = response_handle_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto response_handle = response_handle_res.unwrap(); if (!response_handle.is_valid()) { return false; } auto make_res = host_api::HttpBody::make(); if (auto *err = make_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body = make_res.unwrap(); JS::RootedString string(cx, JS_NewUCStringCopyN(cx, out.c_str(), out.length())); auto stringChars = core::encode(cx, string); auto write_res = body.write_all_back(reinterpret_cast(stringChars.begin()), stringChars.len); if (auto *err = write_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::RootedObject response_instance( cx, JS_NewObjectWithGivenProto(cx, &Response::class_, Response::proto_obj)); if (!response_instance) { return false; } JS::RootedObject response( cx, create(cx, response_instance, response_handle, body, false, nullptr, nullptr, nullptr)); if (!response) { return false; } // Set `this`’s `response`’s `status` to `init`["status"]. auto set_res = response_handle.set_status(status); if (auto *err = set_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } // To ensure that we really have the same status value as the host, // we always read it back here. auto get_res = response_handle.get_status(); if (auto *err = get_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } status = get_res.unwrap(); JS::SetReservedSlot(response, static_cast(Slots::Status), JS::Int32Value(status)); // Set `this`’s `response`’s `status message` to `init`["statusText"]. JS::SetReservedSlot(response, static_cast(Slots::StatusMessage), JS::StringValue(statusText)); // If `init`["headers"] `exists`, then `fill` `this`’s `headers` with // `init`["headers"]. JS::RootedObject headers(cx, Headers::create(cx, headers_val, Headers::HeadersGuard::Response)); if (!headers) { return false; } // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). if (!Headers::set_valid_if_undefined(cx, headers, "content-type", "application/json")) { return false; } JS::SetReservedSlot(response, static_cast(Slots::Headers), JS::ObjectValue(*headers)); JS::SetReservedSlot(response, static_cast(Slots::Redirected), JS::FalseValue()); JS::SetReservedSlot(response, static_cast(Slots::HasBody), JS::TrueValue()); RequestOrResponse::set_url(response, JS_GetEmptyStringValue(cx)); // 5. Return responseObject. args.rval().setObjectOrNull(response); return true; } bool Response::setManualFramingHeaders(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) bool manualFramingHeaders = JS::ToBoolean(args.get(0)); JS::SetReservedSlot(self, static_cast(Slots::ManualFramingHeaders), JS::BooleanValue(manualFramingHeaders)); auto handle = response_handle(self); host_api::Result res; if (manualFramingHeaders) { res = handle.set_framing_headers_mode(host_api::FramingHeadersMode::ManuallyFromHeaders); } else { res = handle.set_framing_headers_mode(host_api::FramingHeadersMode::Automatic); } if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } const JSFunctionSpec Response::static_methods[] = { JS_FN("redirect", redirect, 1, JSPROP_ENUMERATE), JS_FN("json", json, 1, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec Response::static_properties[] = { JS_PS_END, }; const JSFunctionSpec Response::methods[] = { JS_FN("arrayBuffer", bodyAll, 0, JSPROP_ENUMERATE), JS_FN("blob", bodyAll, 0, JSPROP_ENUMERATE), JS_FN("formData", bodyAll, 0, JSPROP_ENUMERATE), JS_FN("json", bodyAll, 0, JSPROP_ENUMERATE), JS_FN("text", bodyAll, 0, JSPROP_ENUMERATE), JS_FN("setManualFramingHeaders", Response::setManualFramingHeaders, 1, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec Response::properties[] = { JS_PSG("redirected", redirected_get, JSPROP_ENUMERATE), JS_PSG("type", type_get, JSPROP_ENUMERATE), JS_PSG("url", url_get, JSPROP_ENUMERATE), JS_PSGS("status", status_get, status_set, JSPROP_ENUMERATE), JS_PSG("ok", ok_get, JSPROP_ENUMERATE), JS_PSG("statusText", statusText_get, JSPROP_ENUMERATE), JS_PSG("version", version_get, JSPROP_ENUMERATE), JS_PSG("headers", headers_get, JSPROP_ENUMERATE), JS_PSG("body", body_get, JSPROP_ENUMERATE), JS_PSG("bodyUsed", bodyUsed_get, JSPROP_ENUMERATE), JS_PSG("ip", ip_get, JSPROP_ENUMERATE), JS_PSG("port", port_get, JSPROP_ENUMERATE), JS_PSG("backend", backend_get, JSPROP_ENUMERATE), JS_PSG("cached", cached_get, JSPROP_ENUMERATE), JS_PSG("stale", stale_get, JSPROP_ENUMERATE), JS_PSGS("ttl", ttl_get, ttl_set, JSPROP_ENUMERATE), JS_PSG("age", age_get, JSPROP_ENUMERATE), JS_PSGS("swr", swr_get, swr_set, JSPROP_ENUMERATE), JS_PSGS("vary", vary_get, vary_set, JSPROP_ENUMERATE), JS_PSGS("surrogateKeys", surrogateKeys_get, surrogateKeys_set, JSPROP_ENUMERATE), JS_PSGS("pci", pci_get, pci_set, JSPROP_ENUMERATE), JS_STRING_SYM_PS(toStringTag, "Response", JSPROP_READONLY), JS_PS_END, }; std::optional Response::storage_action(JSObject *obj) { MOZ_ASSERT(is_instance(obj)); auto val = JS::GetReservedSlot(obj, static_cast(Slots::StorageAction)); if (val.isUndefined()) { return std::nullopt; } MOZ_ASSERT(val.isInt32()); return static_cast(val.toInt32()); } bool Response::cached_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::Value cache_entry = JS::GetReservedSlot(self, static_cast(RequestOrResponse::Slots::CacheEntry)); // Candidate Response -> not cached, since it just came from an origin update if (cache_entry.isInt32()) { args.rval().setBoolean(false); return true; } // Actual Response -> cache_entry boolean/null slot-saving convention used to indicate if // cached/stale if (cache_entry.isBoolean()) { args.rval().setBoolean(cache_entry.toBoolean()); return true; } if (cache_entry.isNull()) { args.rval().setBoolean(true); return true; } // Otherwise no info / cache stuff disabled -> undefined args.rval().setUndefined(); return true; } bool Response::stale_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::Value cache_entry = JS::GetReservedSlot(self, static_cast(RequestOrResponse::Slots::CacheEntry)); // Actual Response -> cache_entry null slot-saving convention used to indicate if stale if (cache_entry.isNull()) { args.rval().setBoolean(true); return true; } // Candidate Response -> not cached, since it just came from an origin update if (cache_entry.isInt32() || cache_entry.isBoolean()) { args.rval().setBoolean(false); return true; } // Otherwise no info / cache stuff disabled -> undefined args.rval().setUndefined(); return true; } bool Response::ttl_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto entry = RequestOrResponse::cache_entry(self); // all caching paths should set the override options as the final options // so if they aren't set we are in the undefiend cases of no caching API use / no hostcall support auto override_opts = override_cache_options(self); if (!override_opts) { args.rval().setUndefined(); return true; } uint64_t max_age_ns, initial_age_ns; // a promoted candidate response must define all cache options if (!entry.has_value() || (override_opts->max_age_ns.has_value() && override_opts->initial_age_ns.has_value())) { max_age_ns = override_opts->max_age_ns.value(); initial_age_ns = override_opts->initial_age_ns.value(); } else { auto suggested_opts = suggested_cache_options(cx, self); if (!suggested_opts) { return false; } max_age_ns = suggested_opts->max_age_ns.value(); if (!override_opts->initial_age_ns.has_value()) { override_opts->initial_age_ns = suggested_opts->initial_age_ns; } initial_age_ns = override_opts->initial_age_ns.value(); } MOZ_ASSERT(max_age_ns > initial_age_ns); uint64_t ttl_ns = max_age_ns - initial_age_ns; args.rval().setNumber(static_cast(ttl_ns) / 1e9); return true; } bool Response::age_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto entry = RequestOrResponse::cache_entry(self); // all caching paths should set the override options as the final options // so if they aren't set we are in the undefiend cases of no caching API use / no hostcall support auto override_opts = override_cache_options(self); if (!override_opts) { args.rval().setUndefined(); return true; } uint64_t initial_age_ns; // a promoted candidate response must define all cache options if (!entry.has_value() || override_opts->initial_age_ns.has_value()) { initial_age_ns = override_opts->initial_age_ns.value(); } else { auto suggested_opts = suggested_cache_options(cx, self); if (!suggested_opts) { return false; } initial_age_ns = suggested_opts->initial_age_ns.value(); if (!override_opts->initial_age_ns.has_value()) { override_opts->initial_age_ns = suggested_opts->initial_age_ns; } initial_age_ns = override_opts->initial_age_ns.value(); } args.rval().setNumber(static_cast(initial_age_ns) / 1e9); return true; } bool Response::swr_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto entry = RequestOrResponse::cache_entry(self); // all caching paths should set the override options as the final options // so if they aren't set we are in the undefiend cases of no caching API use / no hostcall support auto override_opts = override_cache_options(self); if (!override_opts) { args.rval().setUndefined(); return true; } uint64_t swr_ns; // a promoted candidate response must define all cache options if (!entry.has_value() || override_opts->stale_while_revalidate_ns.has_value()) { swr_ns = override_opts->stale_while_revalidate_ns.value(); } else { auto suggested_opts = suggested_cache_options(cx, self); if (!suggested_opts) { return false; } swr_ns = suggested_opts->stale_while_revalidate_ns.value(); } args.rval().setNumber(static_cast(swr_ns) / 1e9); return true; } bool Response::vary_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto entry = RequestOrResponse::cache_entry(self); // all caching paths should set the override options as the final options // so if they aren't set we are in the undefiend cases of no caching API use / no hostcall support auto override_opts = override_cache_options(self); if (!override_opts) { args.rval().setUndefined(); return true; } std::optional vary_rule; // a promoted candidate response must define all cache options if (!entry.has_value() || override_opts->vary_rule.has_value()) { vary_rule = override_opts->vary_rule; } else { auto suggested_opts = suggested_cache_options(cx, self); if (!suggested_opts) { return false; } vary_rule = suggested_opts->vary_rule; } JS::RootedObject arr(cx, JS::NewArrayObject(cx, 0)); if (!arr) { return false; } if (!vary_rule.has_value()) { // Empty Array if no vary rule args.rval().setObject(*arr); return true; } // Split vary rule on commas and trim whitespace std::string_view rule_str(vary_rule.value()); std::vector headers; size_t pos = 0; while (pos < rule_str.length()) { // Skip leading whitespace while (pos < rule_str.length() && std::isspace(rule_str[pos])) { pos++; } // Find next space size_t comma = rule_str.find(' ', pos); std::string_view header; if (comma == std::string_view::npos) { header = rule_str.substr(pos); pos = rule_str.length(); } else { header = rule_str.substr(pos, comma - pos); pos = comma + 1; } // Trim trailing whitespace while (!header.empty() && std::isspace(header.back())) { header.remove_suffix(1); } // Only add non-empty headers if (!header.empty()) { headers.push_back(header); } } // Add headers to array for (size_t i = 0; i < headers.size(); i++) { const auto &header = headers[i]; JS::RootedString str(cx, JS_NewStringCopyN(cx, header.data(), header.length())); if (!str) { return false; } JS::RootedValue val(cx, JS::StringValue(str)); if (!JS_SetElement(cx, arr, i, val)) { return false; } } args.rval().setObject(*arr); return true; } bool Response::surrogateKeys_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto entry = RequestOrResponse::cache_entry(self); // all caching paths should set the override options as the final options // so if they aren't set we are in the undefiend cases of no caching API use / no hostcall support auto override_opts = override_cache_options(self); if (!override_opts) { args.rval().setUndefined(); return true; } const std::vector *surrogate_keys; // a promoted candidate response must define all cache options if (!entry.has_value() || override_opts->surrogate_keys.has_value()) { surrogate_keys = &override_opts->surrogate_keys.value(); } else { auto suggested_opts = suggested_cache_options(cx, self); if (!suggested_opts) { return false; } surrogate_keys = &suggested_opts->surrogate_keys.value(); } // Create array with known size JS::RootedObject arr(cx, JS::NewArrayObject(cx, surrogate_keys->size())); if (!arr) { return false; } // Add keys to array for (size_t i = 0; i < surrogate_keys->size(); i++) { const auto &key = surrogate_keys->at(i); JS::RootedString str(cx, JS_NewStringCopyN(cx, key.ptr.get(), key.len)); if (!str) { return false; } JS::RootedValue val(cx, JS::StringValue(str)); if (!JS_SetElement(cx, arr, i, val)) { return false; } } args.rval().setObject(*arr); return true; } bool Response::pci_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto entry = RequestOrResponse::cache_entry(self); // all caching paths should set the override options as the final options // so if they aren't set we are in the undefiend cases of no caching API use / no hostcall support auto override_opts = override_cache_options(self); if (!override_opts) { args.rval().setUndefined(); return true; } bool sensitive_data; // a promoted candidate response must define all cache options if (!entry.has_value() || override_opts->sensitive_data.has_value()) { sensitive_data = override_opts->sensitive_data.value(); } else { auto suggested_opts = suggested_cache_options(cx, self); if (!suggested_opts) { return false; } sensitive_data = suggested_opts->sensitive_data.value(); } args.rval().setBoolean(sensitive_data); return true; } // Setters for mutable properties bool Response::ttl_set(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) auto override_opts = override_cache_options(self); host_api::HttpCacheWriteOptions *suggested_opts = nullptr; if (RequestOrResponse::cache_entry(self).has_value()) { suggested_opts = suggested_cache_options(cx, self); if (!suggested_opts) { return false; } } if (!suggested_opts) { api::throw_error(cx, api::Errors::TypeError, "Response set", "ttl", "be set only on unsent cache transaction responses"); return false; } double seconds; if (!JS::ToNumber(cx, args[0], &seconds)) { return false; } if (std::isnan(seconds) || seconds <= 0) { api::throw_error(cx, api::Errors::TypeError, "Response set", "ttl", "be a number greater than zero"); return false; } uint64_t ttl_ns = static_cast(std::round(seconds * 1e9)); uint64_t initial_age_ns = suggested_opts->initial_age_ns.value(); override_opts->max_age_ns = ttl_ns + initial_age_ns; args.rval().setUndefined(); return true; } bool Response::swr_set(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) auto override_opts = override_cache_options(self); if (!RequestOrResponse::cache_entry(self).has_value()) { api::throw_error(cx, api::Errors::TypeError, "Response set", "swr", "be set only on unsent cache transaction responses"); return false; } MOZ_ASSERT(override_opts); double seconds; if (!JS::ToNumber(cx, args[0], &seconds)) { return false; } if (std::isnan(seconds) || seconds <= 0) { api::throw_error(cx, api::Errors::TypeError, "Response set", "swr", "be a number greater than zero"); return false; } override_opts->stale_while_revalidate_ns = static_cast(seconds * 1e9); args.rval().setUndefined(); return true; } bool Response::vary_set(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) auto override_opts = override_cache_options(self); if (!RequestOrResponse::cache_entry(self).has_value()) { api::throw_error(cx, api::Errors::TypeError, "Response set", "vary", "be set only on unsent cache transaction responses"); return false; } MOZ_ASSERT(override_opts); JS::RootedObject arr_obj(cx); bool is_array = false; if (args[0].isObject()) { arr_obj.set(&args[0].toObject()); if (!JS::IsArrayObject(cx, arr_obj, &is_array)) { return false; } } if (!is_array) { api::throw_error(cx, api::Errors::TypeError, "Response set", "vary", "be an Array"); return false; } uint32_t length; if (!JS::GetArrayLength(cx, arr_obj, &length)) { return false; } size_t total_len = 0; std::vector encoded_strings; encoded_strings.reserve(length); for (uint32_t i = 0; i < length; i++) { JS::RootedValue val(cx); if (!JS_GetElement(cx, arr_obj, i, &val)) { return false; } if (!val.isString()) { api::throw_error(cx, api::Errors::TypeError, "Response set", "vary", "contain only strings"); return false; } auto str_val = core::encode(cx, val); if (!str_val) { return false; } encoded_strings.push_back(std::move(str_val)); total_len += str_val.len; } // Add space for spaces between strings if (length > 1) { total_len += length - 1; } // Allocate buffer and copy strings with spaces JS::UniqueChars buffer(static_cast(malloc(total_len))); if (!buffer) { return false; } size_t pos = 0; for (size_t i = 0; i < encoded_strings.size(); i++) { const auto &str = encoded_strings[i]; if (i > 0) { buffer[pos++] = ' '; } memcpy(buffer.get() + pos, str.ptr.get(), str.len); pos += str.len; } override_opts->vary_rule = host_api::HostString(std::move(buffer), total_len); args.rval().setUndefined(); return true; } bool Response::surrogateKeys_set(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) auto override_opts = override_cache_options(self); if (!RequestOrResponse::cache_entry(self).has_value()) { api::throw_error(cx, api::Errors::TypeError, "Response set", "surrogateKeys", "be set only on unsent cache transaction responses"); return false; } MOZ_ASSERT(override_opts); if (!args[0].isObject()) { api::throw_error(cx, api::Errors::TypeError, "Response set", "surrogateKeys", "be an Array"); return false; } bool is_arr; JS::RootedObject arr_obj(cx, &args[0].toObject()); if (!JS::IsArrayObject(cx, arr_obj, &is_arr)) { return false; } if (!is_arr) { api::throw_error(cx, api::Errors::TypeError, "Response set", "surrogateKeys", "be an Array"); return false; } uint32_t length; if (!JS::GetArrayLength(cx, arr_obj, &length)) { return false; } std::vector keys; keys.reserve(length); for (uint32_t i = 0; i < length; i++) { JS::RootedValue val(cx); if (!JS_GetElement(cx, arr_obj, i, &val)) { return false; } if (!val.isString()) { api::throw_error(cx, api::Errors::TypeError, "Response set", "surrogateKeys", "contain only strings"); return false; } auto key = core::encode(cx, val); if (!key) { return false; } keys.push_back(std::move(key)); // Move the entire HostString } override_opts->surrogate_keys = std::move(keys); args.rval().setUndefined(); return true; } bool Response::pci_set(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) auto override_opts = override_cache_options(self); if (!RequestOrResponse::cache_entry(self).has_value()) { api::throw_error(cx, api::Errors::TypeError, "Response set", "pci", "be set only on unsent cache transaction responses"); return false; } MOZ_ASSERT(override_opts); if (!args[0].isBoolean()) { api::throw_error(cx, api::Errors::TypeError, "Response set", "pci", "be a boolean"); return false; } override_opts->sensitive_data = args[0].toBoolean(); args.rval().setUndefined(); return true; } /** * The `Response` constructor https://fetch.spec.whatwg.org/#dom-response */ bool Response::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The Response builtin"); CTOR_HEADER("Response", 0); JS::RootedValue body_val(cx, args.get(0)); JS::RootedValue init_val(cx, args.get(1)); JS::RootedValue status_val(cx); uint16_t status = 200; JS::RootedValue statusText_val(cx); JS::RootedString statusText(cx, JS_GetEmptyString(cx)); JS::RootedValue headers_val(cx); bool hasmanualFramingHeaders; JS::RootedValue manualFramingHeaders(cx); host_api::FramingHeadersMode mode{host_api::FramingHeadersMode::Automatic}; if (init_val.isObject()) { JS::RootedObject init(cx, init_val.toObjectOrNull()); if (!JS_GetProperty(cx, init, "status", &status_val) || !JS_GetProperty(cx, init, "statusText", &statusText_val) || !JS_GetProperty(cx, init, "headers", &headers_val)) { return false; } if (!status_val.isUndefined() && !JS::ToUint16(cx, status_val, &status)) { return false; } if (!statusText_val.isUndefined()) { auto status_text_result = valueToJSByteString(cx, statusText_val); if (status_text_result.isErr()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_CONSTRUCTOR_INVALID_STATUS_TEXT); return false; } auto status_text = status_text_result.unwrap(); auto it = std::find_if(status_text.begin(), status_text.end(), [](unsigned char c) { if (c < 9) { return true; } if (c > 9 && c < 32) { return true; } if (c == 127) { return true; } if (c > 255) { return true; } return false; }); if (it != status_text.end()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_CONSTRUCTOR_INVALID_STATUS_TEXT); return false; } statusText = JS_NewStringCopyZ(cx, status_text.c_str()); } if (!JS_HasOwnProperty(cx, init, "manualFramingHeaders", &hasmanualFramingHeaders) || !JS_GetProperty(cx, init, "manualFramingHeaders", &manualFramingHeaders)) { return false; } } else if (!init_val.isNullOrUndefined()) { JS_ReportErrorLatin1(cx, "Response constructor: |init| parameter can't be converted to " "a dictionary"); return false; } // 1. If `init`["status"] is not in the range 200 to 599, inclusive, then // `throw` a ``RangeError``. (We allow 103 Early Hints as an extension) if (status != 103 && !(status >= 200 && status < 600)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_CONSTRUCTOR_INVALID_STATUS, status); return false; } // 2. If `init`["statusText"] does not match the `reason-phrase` token // production, then `throw` a ``TypeError``. // 3. Set `this`’s `response` to a new `response`. // TODO(performance): consider not creating a host-side representation for responses // eagerly. Some applications create Response objects purely for internal use, // e.g. to represent cache entries. While that's perhaps not ideal to begin // with, it exists, so we should handle it in a good way, and not be // superfluously slow. // https://github.com/fastly/js-compute-runtime/issues/219 // TODO(performance): enable creating Response objects during the init phase, and only // creating the host-side representation when processing requests. // https://github.com/fastly/js-compute-runtime/issues/220 auto response_handle_res = host_api::HttpResp::make(); if (auto *err = response_handle_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto make_res = host_api::HttpBody::make(); if (auto *err = make_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto response_handle = response_handle_res.unwrap(); auto body = make_res.unwrap(); JS::RootedObject responseInstance(cx, JS_NewObjectForConstructor(cx, &class_, args)); JS::RootedObject response( cx, create(cx, responseInstance, response_handle, body, false, nullptr, nullptr, nullptr)); if (!response) { return false; } if (!hasmanualFramingHeaders) { if (is_instance(init_val)) { manualFramingHeaders.set(JS::GetReservedSlot( init_val.toObjectOrNull(), static_cast(Slots::ManualFramingHeaders))); } else { manualFramingHeaders.setBoolean(false); } } JS::SetReservedSlot(response, static_cast(Slots::ManualFramingHeaders), JS::BooleanValue(JS::ToBoolean(manualFramingHeaders))); // `manualFramingHeaders: true` indicates that we want to set the framing mode manually. if (JS::ToBoolean(manualFramingHeaders)) { mode = host_api::FramingHeadersMode::ManuallyFromHeaders; } if (mode != host_api::FramingHeadersMode::Automatic) { auto res = response_handle.set_framing_headers_mode(mode); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } } RequestOrResponse::set_url(response, JS_GetEmptyStringValue(cx)); // 4. Set `this`’s `headers` to a `new` ``Headers`` object with `this`’s // `relevant Realm`, // whose `header list` is `this`’s `response`’s `header list` and `guard` // is "`response`". // (implicit) // 5. Set `this`’s `response`’s `status` to `init`["status"]. auto set_res = response_handle.set_status(status); if (auto *err = set_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } // To ensure that we really have the same status value as the host, // we always read it back here. auto get_res = response_handle.get_status(); if (auto *err = get_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } status = get_res.unwrap(); JS::SetReservedSlot(response, static_cast(Slots::Status), JS::Int32Value(status)); // 6. Set `this`’s `response`’s `status message` to `init`["statusText"]. JS::SetReservedSlot(response, static_cast(Slots::StatusMessage), JS::StringValue(statusText)); // 7. If `init`["headers"] `exists`, then `fill` `this`’s `headers` with // `init`["headers"]. JS::RootedObject headers(cx, Headers::create(cx, headers_val, Headers::HeadersGuard::Response)); if (!headers) { return false; } JS::SetReservedSlot(response, static_cast(Slots::Headers), JS::ObjectValue(*headers)); // 8. If `body` is non-null, then: if ((!body_val.isNullOrUndefined())) { // 1. If `init`["status"] is a `null body status`, then `throw` a // ``TypeError``. if (status == 103 || status == 204 || status == 205 || status == 304) { JS_ReportErrorNumberLatin1(cx, FastlyGetErrorMessage, nullptr, JSMSG_RESPONSE_CONSTRUCTOR_BODY_WITH_NULL_BODY_STATUS); return false; } // 2. Let `Content-Type` be null. // 3. Set `this`’s `response`’s `body` and `Content-Type` to the result // of `extracting` // `body`. // 4. If `Content-Type` is non-null and `this`’s `response`’s `header // list` `does not // contain` ``Content-Type``, then `append` (``Content-Type``, // `Content-Type`) to `this`’s `response`’s `header list`. // Note: these steps are all inlined into RequestOrResponse::extract_body. if (!RequestOrResponse::extract_body(cx, response, body_val)) { return false; } } args.rval().setObject(*response); return true; } bool Response::init_class(JSContext *cx, JS::HandleObject global) { if (!init_class_impl(cx, global)) { return false; } // Initialize a pinned (i.e., never-moved, living forever) atom for the // response type values. return (type_default_atom = JS_AtomizeAndPinString(cx, "default")) && (type_error_atom = JS_AtomizeAndPinString(cx, "error")); } host_api::HttpCacheWriteOptions *Response::override_cache_options(JSObject *response) { MOZ_ASSERT(is_instance(response)); auto cache_options = reinterpret_cast( JS::GetReservedSlot(response, static_cast(Response::Slots::OverrideCacheWriteOptions)) .toPrivate()); return cache_options; } host_api::HttpCacheWriteOptions *Response::take_override_cache_options(JSObject *response) { MOZ_ASSERT(is_instance(response)); auto cache_options = reinterpret_cast( JS::GetReservedSlot(response, static_cast(Response::Slots::OverrideCacheWriteOptions)) .toPrivate()); JS::SetReservedSlot(response, static_cast(Response::Slots::OverrideCacheWriteOptions), JS::PrivateValue(nullptr)); MOZ_ASSERT(cache_options); return cache_options; } /** * Get suggested HTTP cache write options for this CandidateResponse, lazily computed and cached on * Slots::SuggestedCacheWriteOptions. * * Suggested cache options will have ALL values set for HttpCacheWriteOptions (no optionals). * * This function should not be used when the response is closed, as it will panic, instead */ host_api::HttpCacheWriteOptions *Response::suggested_cache_options(JSContext *cx, HandleObject response) { MOZ_ASSERT(is_instance(response)); auto existing = JS::GetReservedSlot( response, static_cast(Response::Slots::SuggestedCacheWriteOptions)); bool changed; if (!RequestOrResponse::compare_bump_headers_gen(cx, response, &changed)) { return nullptr; } if (!changed && !existing.isUndefined()) { return reinterpret_cast(existing.toPrivate()); } host_api::HttpCacheEntry cache_entry = RequestOrResponse::cache_entry(response).value(); auto suggested_cache_options_res = cache_entry.get_suggested_cache_options(response_handle(response)); if (auto *err = suggested_cache_options_res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } // TODO: read from the special surrogate keys header here as part of the suggestion. auto suggested_cache_options = suggested_cache_options_res.unwrap(); JS::SetReservedSlot(response, static_cast(Response::Slots::SuggestedCacheWriteOptions), JS::PrivateValue(suggested_cache_options)); return suggested_cache_options; } JSObject *Response::create(JSContext *cx, HandleObject request, host_api::Response res) { auto [response_handle, body] = res; JS::RootedObject response_instance( cx, JS_NewObjectWithGivenProto(cx, &Response::class_, Response::proto_obj)); if (!response_instance) { return nullptr; } bool is_upstream = true; RootedString backend(cx, RequestOrResponse::backend(request)); JS::RootedObject response(cx, Response::create(cx, response_instance, response_handle, body, is_upstream, nullptr, nullptr, backend)); if (!response) { return nullptr; } RequestOrResponse::set_url(response, RequestOrResponse::url(request)); return response; } void Response::finalize(JS::GCContext *gcx, JSObject *self) { auto suggested_cache_write_options_val = JS::GetReservedSlot(self, static_cast(Response::Slots::SuggestedCacheWriteOptions)); if (!suggested_cache_write_options_val.isUndefined()) { host_api::HttpCacheWriteOptions *cache_write_options = static_cast( suggested_cache_write_options_val.toPrivate()); delete cache_write_options; } auto override_cache_write_options_val = JS::GetReservedSlot(self, static_cast(Response::Slots::OverrideCacheWriteOptions)); if (!override_cache_write_options_val.isUndefined()) { auto override_cache_write_options = reinterpret_cast( override_cache_write_options_val.toPrivate()); if (override_cache_write_options) { delete override_cache_write_options; } } } bool Response::has_bodyless_status(JSObject *obj) { auto status(Response::status(obj)); return status == 103 || status == 204 || status == 205 || status == 304; } JSObject *Response::create(JSContext *cx, JS::HandleObject response, host_api::HttpResp response_handle, host_api::HttpBody body_handle, bool is_upstream, JSObject *grip_upgrade_request, JSObject *websocket_upgrade_request, JS::HandleString backend) { JS::SetReservedSlot(response, static_cast(Slots::Response), JS::Int32Value(response_handle.handle)); JS::SetReservedSlot(response, static_cast(Slots::Headers), JS::NullValue()); JS::SetReservedSlot(response, static_cast(Slots::Body), JS::Int32Value(body_handle.handle)); JS::SetReservedSlot(response, static_cast(Slots::BodyStream), JS::NullValue()); JS::SetReservedSlot(response, static_cast(Slots::HasBody), JS::FalseValue()); JS::SetReservedSlot(response, static_cast(Slots::BodyUsed), JS::FalseValue()); JS::SetReservedSlot(response, static_cast(Slots::Redirected), JS::FalseValue()); JS::SetReservedSlot(response, static_cast(Slots::IsUpstream), JS::BooleanValue(is_upstream)); if (grip_upgrade_request) { JS::SetReservedSlot(response, static_cast(Slots::GripUpgradeRequest), JS::Int32Value(Request::request_handle(grip_upgrade_request).handle)); } if (websocket_upgrade_request) { JS::SetReservedSlot(response, static_cast(Slots::WebsocketUpgradeRequest), JS::Int32Value(Request::request_handle(websocket_upgrade_request).handle)); } JS::SetReservedSlot(response, static_cast(Slots::StorageAction), JS::UndefinedValue()); JS::SetReservedSlot(response, static_cast(RequestOrResponse::Slots::CacheEntry), JS::UndefinedValue()); JS::SetReservedSlot(response, static_cast(Slots::SuggestedCacheWriteOptions), JS::UndefinedValue()); JS::SetReservedSlot(response, static_cast(Slots::HeadersGen), JS::UndefinedValue()); JS::SetReservedSlot(response, static_cast(Slots::OverrideCacheWriteOptions), JS::PrivateValue(nullptr)); JS::SetReservedSlot(response, static_cast(Slots::CacheBodyTransform), JS::UndefinedValue()); if (backend) { JS::SetReservedSlot(response, static_cast(Slots::Backend), JS::StringValue(backend)); } if (is_upstream) { auto res = response_handle.get_status(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } auto status = res.unwrap(); JS::SetReservedSlot(response, static_cast(Slots::Status), JS::Int32Value(status)); set_status_message_from_code(cx, response, status); if (!Response::has_bodyless_status(response)) { JS::SetReservedSlot(response, static_cast(Slots::HasBody), JS::TrueValue()); } } return response; } } // namespace fastly::fetch ================================================ FILE: runtime/fastly/builtins/fetch/request-response.h ================================================ #ifndef FASTLY_REQUEST_RESPONSE #define FASTLY_REQUEST_RESPONSE #include "../../../StarlingMonkey/builtins/web/fetch/headers.h" #include "../../host-api/host_api_fastly.h" namespace fastly::fetch { class RequestOrResponse final { public: enum class Slots { RequestOrResponse, Body, BodyStream, BodyAllPromise, HasBody, BodyUsed, Headers, HeadersGen, URL, ManualFramingHeaders, Backend, CacheEntry, SourceRequest, // Tracks the original Request when body is proxied via TransformStream FetchEvent, Count, }; static bool is_instance(JSObject *obj); static uint32_t handle(JSObject *obj); static bool has_body(JSObject *obj); static host_api::HttpBody body_handle(JSObject *obj); static JSObject *body_stream(JSObject *obj); static JSObject *body_source(JSContext *cx, JS::HandleObject obj); static bool body_used(JSObject *obj); static bool mark_body_used(JSContext *cx, JS::HandleObject obj); static bool move_body_handle(JSContext *cx, JS::HandleObject from, JS::HandleObject to); static JS::Value url(JSObject *obj); static void set_url(JSObject *obj, JS::Value url); static void set_manual_framing_headers(JSContext *cx, JSObject *obj, JS::HandleValue url); static bool body_unusable(JSContext *cx, JS::HandleObject body); static bool extract_body(JSContext *cx, JS::HandleObject self, JS::HandleValue body_val); static bool process_pending_request(JSContext *cx, host_api::HttpPendingReq::Handle handle, JS::HandleObject context, JS::HandleValue promise); /** * Returns the RequestOrResponse's Headers if it has been reified, nullptr if * not. */ static JSObject *maybe_headers(JSObject *obj); /** * For Requests and Responses in Mode::ContentOnly, creates a new HostOnly headers * object and commits the headers map values. */ static bool commit_headers(JSContext *cx, JS::HandleObject self); /** * Compare the HeadersGen slot with the current headers generation, returning true if the headers * have changed and false otherwise, storing the new generation into the slot. * If the headers are undefined, the generation is tracked as null, still supporting comparison. */ static bool compare_bump_headers_gen(JSContext *cx, JS::HandleObject self, bool *changed_out); static bool append_body(JSContext *cx, JS::HandleObject self, JS::HandleObject source); using ParseBodyCB = bool(JSContext *cx, JS::HandleObject self, JS::UniqueChars buf, size_t len); enum class BodyReadResult { ArrayBuffer, Blob, FormData, JSON, Text, }; template static bool parse_body(JSContext *cx, JS::HandleObject self, JS::UniqueChars buf, size_t len); static bool content_stream_read_then_handler(JSContext *cx, JS::HandleObject self, JS::HandleValue extra, JS::CallArgs args); static bool content_stream_read_catch_handler(JSContext *cx, JS::HandleObject self, JS::HandleValue extra, JS::CallArgs args); static bool consume_content_stream_for_bodyAll(JSContext *cx, JS::HandleObject self, JS::HandleValue stream_val, JS::CallArgs args); template static bool consume_body_handle_for_bodyAll(JSContext *cx, JS::HandleObject self, JS::HandleValue body_parser, JS::CallArgs args); template static bool bodyAll(JSContext *cx, JS::CallArgs args, JS::HandleObject self); static bool body_source_cancel_algorithm(JSContext *cx, JS::CallArgs args, JS::HandleObject stream, JS::HandleObject owner, JS::HandleValue reason); static bool body_source_pull_algorithm(JSContext *cx, JS::CallArgs args, JS::HandleObject source, JS::HandleObject body_owner, JS::HandleObject controller); static bool body_reader_then_handler(JSContext *cx, JS::HandleObject body_owner, JS::HandleValue extra, JS::CallArgs args); static bool body_reader_catch_handler(JSContext *cx, JS::HandleObject body_owner, JS::HandleValue extra, JS::CallArgs args); /** * Ensures that the given |body_owner|'s body is properly streamed, if it * requires streaming. * * If streaming is required, starts the process of reading from the * ReadableStream representing the body and sets the |requires_streaming| bool * to `true`. */ static bool maybe_stream_body(JSContext *cx, JS::HandleObject body_owner, bool *requires_streaming); static JSObject *create_body_stream(JSContext *cx, JS::HandleObject owner); static bool body_get(JSContext *cx, JS::CallArgs args, JS::HandleObject self, bool create_if_undefined); static bool backend_get(JSContext *cx, JS::CallArgs args, JS::HandleObject self); static JSString *backend(JSObject *obj); /** * Helper method to get (and possibly unset) the cache entry for a request or response (if any) * * A Response with a cache entry is a valid CandidateResponse. */ static std::optional cache_entry(JSObject *obj); /** * Helper method to get and unset the transaction cache entry for a request or response (if any) * * Unsetting the cache entry on a Response object freezes the CandidateResponse from further * modification. * * A boolean overload for the cache entry disabled case is used to mark if we were cached or not. */ static std::optional take_cache_entry(JSObject *obj, std::optional mark_cached); /** * Close the cache entry and clear it from the Response, effectively locking this * candidate response object. */ static bool close_if_cache_entry(JSContext *cx, JS::HandleObject self); }; class Request final : public builtins::BuiltinImpl { static bool method_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool headers_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool url_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool version_get(JSContext *cx, unsigned argc, JS::Value *vp); template static bool bodyAll(JSContext *cx, unsigned argc, JS::Value *vp); static bool backend_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool body_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool bodyUsed_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool setCacheOverride(JSContext *cx, unsigned argc, JS::Value *vp); static bool setCacheKey(JSContext *cx, unsigned argc, JS::Value *vp); static bool setManualFramingHeaders(JSContext *cx, unsigned argc, JS::Value *vp); static bool clone(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "Request"; enum class Slots { Request = static_cast(RequestOrResponse::Slots::RequestOrResponse), Body = static_cast(RequestOrResponse::Slots::Body), BodyStream = static_cast(RequestOrResponse::Slots::BodyStream), HasBody = static_cast(RequestOrResponse::Slots::HasBody), BodyUsed = static_cast(RequestOrResponse::Slots::BodyUsed), Headers = static_cast(RequestOrResponse::Slots::Headers), HeadersGen = static_cast(RequestOrResponse::Slots::HeadersGen), URL = static_cast(RequestOrResponse::Slots::URL), ManualFramingHeaders = static_cast(RequestOrResponse::Slots::ManualFramingHeaders), Backend = static_cast(RequestOrResponse::Slots::Backend), CacheEntry = static_cast(RequestOrResponse::Slots::CacheEntry), SourceRequest = static_cast(RequestOrResponse::Slots::SourceRequest), FetchEvent = static_cast(RequestOrResponse::Slots::FetchEvent), Method = static_cast(RequestOrResponse::Slots::Count), OverrideCacheKey, CacheOverride, PendingRequest, ResponsePromise, IsDownstream, AutoDecompressGzip, ImageOptimizerOptions, Count, }; /** * Returns the RequestOrResponse's Headers, reifying it if necessary. */ static JSObject *headers(JSContext *cx, JS::HandleObject obj); static JSObject *response_promise(JSObject *obj); static JSString *method(JSContext *cx, JS::HandleObject obj); // static JSString *override_cache_key(JSContext *cx) static bool set_cache_key(JSContext *cx, JS::HandleObject self, JS::HandleValue cache_key_val); static bool set_cache_override(JSContext *cx, JS::HandleObject self, JS::HandleValue cache_override_val); static bool apply_cache_override(JSContext *cx, JS::HandleObject self); static bool apply_auto_decompress_gzip(JSContext *cx, JS::HandleObject self); static bool set_image_optimizer_options(JSContext *cx, JS::HandleObject self, JS::HandleValue image_optimizer_options); static bool isCacheable_get(JSContext *cx, unsigned argc, JS::Value *vp); static host_api::HttpReq request_handle(JSObject *obj); static host_api::HttpPendingReq pending_handle(JSObject *obj); static bool is_downstream(JSObject *obj); static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static const unsigned ctor_length = 1; static bool init_class(JSContext *cx, JS::HandleObject global); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); static JSObject *create(JSContext *cx, JS::HandleObject requestInstance, host_api::HttpReq request_handle, host_api::HttpBody body_handle, bool is_downstream); static JSObject *create(JSContext *cx, JS::HandleObject requestInstance, JS::HandleValue input, JS::HandleValue init_val); static JSObject *create_instance(JSContext *cx); }; class Response final : public builtins::FinalizableBuiltinImpl { static bool waitUntil(JSContext *cx, unsigned argc, JS::Value *vp); static bool ok_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool status_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool status_set(JSContext *cx, unsigned argc, JS::Value *vp); static bool statusText_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool url_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool version_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool type_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool headers_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool redirected_get(JSContext *cx, unsigned argc, JS::Value *vp); template static bool bodyAll(JSContext *cx, unsigned argc, JS::Value *vp); static bool backend_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool body_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool bodyUsed_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool ip_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool port_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool redirect(JSContext *cx, unsigned argc, JS::Value *vp); static bool json(JSContext *cx, unsigned argc, JS::Value *vp); static bool setManualFramingHeaders(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "Response"; enum class Slots { Response = static_cast(RequestOrResponse::Slots::RequestOrResponse), Body = static_cast(RequestOrResponse::Slots::Body), BodyStream = static_cast(RequestOrResponse::Slots::BodyStream), HasBody = static_cast(RequestOrResponse::Slots::HasBody), BodyUsed = static_cast(RequestOrResponse::Slots::BodyUsed), Headers = static_cast(RequestOrResponse::Slots::Headers), HeadersGen = static_cast(RequestOrResponse::Slots::HeadersGen), URL = static_cast(RequestOrResponse::Slots::URL), ManualFramingHeaders = static_cast(RequestOrResponse::Slots::ManualFramingHeaders), Backend = static_cast(RequestOrResponse::Slots::Backend), CacheEntry = static_cast(RequestOrResponse::Slots::CacheEntry), SourceRequest = static_cast(RequestOrResponse::Slots::SourceRequest), FetchEvent = static_cast(RequestOrResponse::Slots::FetchEvent), IsUpstream = static_cast(RequestOrResponse::Slots::Count), Status, StatusMessage, Redirected, GripUpgradeRequest, WebsocketUpgradeRequest, StorageAction, SuggestedCacheWriteOptions, OverrideCacheWriteOptions, CacheBodyTransform, Count, }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static const unsigned ctor_length = 1; static bool init_class(JSContext *cx, JS::HandleObject global); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); /** * Create a response for a request, used for the fetch response flow. */ static JSObject *create(JSContext *cx, HandleObject request, host_api::Response res); /** * Base-level response creation handler, for both upstream and downstream requests. */ static JSObject *create(JSContext *cx, JS::HandleObject response, host_api::HttpResp response_handle, host_api::HttpBody body_handle, bool is_upstream, JSObject *grip_upgrade_request, JSObject *websocket_upgrade_request, JS::HandleString backend); static host_api::HttpResp response_handle(JSObject *obj); /** * Returns the RequestOrResponse's Headers, reifying it if necessary. */ static JSObject *headers(JSContext *cx, JS::HandleObject obj); /** * Get the storage action for the response. */ static std::optional storage_action(JSObject *obj); static bool is_upstream(JSObject *obj); static std::optional grip_upgrade_request(JSObject *obj); static std::optional websocket_upgrade_request(JSObject *obj); static host_api::HostString backend_str(JSContext *cx, JSObject *obj); static uint16_t status(JSObject *obj); static JSString *status_message(JSObject *obj); static void set_status_message_from_code(JSContext *cx, JSObject *obj, uint16_t code); static bool add_fastly_cache_headers(JSContext *cx, JS::HandleObject self, JS::HandleObject request, std::optional cache_entry, const char *fun_name); static bool has_body_transform(JSObject *self); static bool has_bodyless_status(JSObject *obj); /** * Override cache options set by the user & suggested options, or final cache options if * finalized. */ static host_api::HttpCacheWriteOptions *override_cache_options(JSObject *response); /** * Takes the override cache options field. */ static host_api::HttpCacheWriteOptions *take_override_cache_options(JSObject *response); /** * Suggested cache options as provided by the host for the request/response pair, and * computed lazily (fallible). */ static host_api::HttpCacheWriteOptions *suggested_cache_options(JSContext *cx, HandleObject response); static bool isCacheable_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool cached_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool stale_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool ttl_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool ttl_set(JSContext *cx, unsigned argc, JS::Value *vp); static bool age_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool swr_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool swr_set(JSContext *cx, unsigned argc, JS::Value *vp); static bool vary_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool vary_set(JSContext *cx, unsigned argc, JS::Value *vp); static bool surrogateKeys_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool surrogateKeys_set(JSContext *cx, unsigned argc, JS::Value *vp); static bool pci_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool pci_set(JSContext *cx, unsigned argc, JS::Value *vp); static void finalize(JS::GCContext *gcx, JSObject *self); }; } // namespace fastly::fetch #endif ================================================ FILE: runtime/fastly/builtins/fetch-event.cpp ================================================ #include "fetch-event.h" #include "../../StarlingMonkey/builtins/web/performance.h" #include "../../StarlingMonkey/builtins/web/url.h" #include "../../StarlingMonkey/builtins/web/worker-location.h" #include "../common/ip_octets_to_js_string.h" #include "../common/normalize_http_method.h" #include "../host-api/fastly.h" #include "../host-api/host_api_fastly.h" #include "./fetch/request-response.h" #include "encode.h" #include "fastly.h" #include "host_api.h" #include "js/JSON.h" #include "openssl/evp.h" #include #include using std::chrono::microseconds; using std::chrono::system_clock; using namespace std::literals::string_view_literals; using builtins::web::fetch::Headers; using builtins::web::url::URL; using builtins::web::worker_location::WorkerLocation; using fastly::fastly::Fastly; using fastly::fetch::RequestOrResponse; using fastly::fetch::Response; namespace fastly::fetch_event { namespace { JSString *client_request_id(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::ClientRequestId)); return val.isString() ? val.toString() : nullptr; } JSString *client_address(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::Address)); return val.isString() ? val.toString() : nullptr; } JSString *geo_info(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::GeoInfo)); return val.isString() ? val.toString() : nullptr; } JSString *cipher(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::Cipher)); return val.isString() ? val.toString() : nullptr; } JSString *ja3(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::JA3)); return val.isString() ? val.toString() : nullptr; } JSString *ja4(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::JA4)); return val.isString() ? val.toString() : nullptr; } JSString *h2Fingerprint(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::H2Fingerprint)); return val.isString() ? val.toString() : nullptr; } JSString *ohFingerprint(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::OHFingerprint)); return val.isString() ? val.toString() : nullptr; } JSObject *clientHello(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::ClientHello)); return val.isObject() ? val.toObjectOrNull() : nullptr; } JSObject *clientCert(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::ClientCert)); return val.isObject() ? val.toObjectOrNull() : nullptr; } JSString *protocol(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ClientInfo::Slots::Protocol)); return val.isString() ? val.toString() : nullptr; } } // namespace JSString *ClientInfo::retrieve_client_address(JSContext *cx, JS::HandleObject self) { auto res = request_handle(cx, self).downstream_client_ip_addr(); if (res.is_err()) { return nullptr; } JS::RootedString address(cx, common::ip_octets_to_js_string(cx, std::move(res.unwrap()))); if (!address) { return nullptr; } JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::Address), JS::StringValue(address)); return address; } host_api::HttpReq ClientInfo::request_handle(JSContext *cx, JS::HandleObject self) { JS::RootedValue req(cx, JS::GetReservedSlot(self, static_cast(Slots::Request))); return Request::request_handle(&req.toObject()); } bool ClientInfo::request_id_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedString result(cx, client_request_id(self)); if (!result) { auto res = request_handle(cx, self).http_req_downstream_client_request_id(); if (res.to_err() || !res.unwrap().has_value()) { args.rval().setNull(); return true; } auto h2fp_str = std::move(res.unwrap().value()); result.set(JS_NewStringCopyN(cx, h2fp_str.ptr.get(), h2fp_str.len)); JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::ClientRequestId), JS::StringValue(result)); } args.rval().setString(result); return true; } bool ClientInfo::address_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedString address_str(cx, client_address(self)); if (!address_str) { address_str = retrieve_client_address(cx, self); if (!address_str) { args.rval().setNull(); return true; } } args.rval().setString(address_str); return true; } bool ClientInfo::geo_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedString geo_info_str(cx, geo_info(self)); if (!geo_info_str) { JS::RootedString address_str(cx, client_address(self)); if (!address_str) { address_str = retrieve_client_address(cx, self); if (!address_str) { args.rval().setNull(); return true; } } // TODO: skip intermediate encoding, and rely on the fact that we already had the bytes before auto address = core::encode(cx, address_str); if (!address) { return false; } // TODO: Remove all of this and rely on the host for validation as the hostcall only takes one // user-supplied parameter int format = AF_INET; size_t octets_len = 4; if (std::find(address.begin(), address.end(), ':') != address.end()) { format = AF_INET6; octets_len = 16; } uint8_t octets[sizeof(struct in6_addr)]; if (inet_pton(format, address.begin(), octets) != 1) { // While get_geo_info can be invoked through FetchEvent#client.geo, too, // that path can't result in an invalid address here, so we can be more // specific in the error message. // TODO: Make a TypeError JS_ReportErrorLatin1(cx, "Invalid address passed to fastly.getGeolocationForIpAddress"); return false; } auto res = host_api::GeoIp::lookup(std::span{octets, octets_len}); if (res.is_err() || !res.unwrap().has_value()) { args.rval().setNull(); return true; } auto ret = std::move(res.unwrap().value()); geo_info_str = JS::RootedString(cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(ret.ptr.release(), ret.len))); if (!geo_info_str) return false; JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::GeoInfo), JS::StringValue(geo_info_str)); } return JS_ParseJSON(cx, geo_info_str, args.rval()); } bool ClientInfo::tls_cipher_openssl_name_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedString result(cx, cipher(self)); if (!result) { auto res = request_handle(cx, self).http_req_downstream_tls_cipher_openssl_name(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); return true; } auto cipher = std::move(res.unwrap().value()); result.set(JS_NewStringCopyN(cx, cipher.ptr.get(), cipher.len)); JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::Cipher), JS::StringValue(result)); } args.rval().setString(result); return true; } bool ClientInfo::tls_ja3_md5_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedString result(cx, ja3(self)); if (!result) { auto res = request_handle(cx, self).http_req_downstream_tls_ja3_md5(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); return true; } auto ja3 = std::move(res.unwrap().value()); JS::UniqueChars hex{OPENSSL_buf2hexstr(ja3.ptr.get(), ja3.len)}; std::string ja3hex{hex.get(), std::remove(hex.get(), hex.get() + strlen(hex.get()), ':')}; result.set(JS_NewStringCopyN(cx, ja3hex.c_str(), ja3hex.length())); JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::JA3), JS::StringValue(result)); } args.rval().setString(result); return true; } bool ClientInfo::tls_ja4_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedString result(cx, ja4(self)); if (!result) { auto res = request_handle(cx, self).http_req_downstream_tls_ja4(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); return true; } auto ja4_str = std::move(res.unwrap().value()); result.set(JS_NewStringCopyN(cx, ja4_str.ptr.get(), ja4_str.len)); JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::JA4), JS::StringValue(result)); } args.rval().setString(result); return true; } bool ClientInfo::h2_fingerprint_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedString result(cx, h2Fingerprint(self)); if (!result) { auto res = request_handle(cx, self).http_req_downstream_client_h2_fingerprint(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); return true; } auto h2fp_str = std::move(res.unwrap().value()); result.set(JS_NewStringCopyN(cx, h2fp_str.ptr.get(), h2fp_str.len)); JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::H2Fingerprint), JS::StringValue(result)); } args.rval().setString(result); return true; } bool ClientInfo::oh_fingerprint_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedString result(cx, ohFingerprint(self)); if (!result) { auto res = request_handle(cx, self).http_req_downstream_client_oh_fingerprint(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); return true; } auto ohfp_str = std::move(res.unwrap().value()); result.set(JS_NewStringCopyN(cx, ohfp_str.ptr.get(), ohfp_str.len)); JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::OHFingerprint), JS::StringValue(result)); } args.rval().setString(result); return true; } bool ClientInfo::tls_client_hello_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedObject buffer(cx, clientHello(self)); if (!buffer) { auto res = request_handle(cx, self).http_req_downstream_tls_client_hello(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); return true; } auto hello = std::move(res.unwrap().value()); buffer.set(JS::NewArrayBufferWithContents(cx, hello.len, hello.ptr.get(), JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory)); if (!buffer) { // We can be here if the array buffer was too large -- if that was the case then a // JSMSG_BAD_ARRAY_LENGTH will have been created. return false; } // `hello` is now owned by `buffer` static_cast(hello.ptr.release()); JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::ClientHello), JS::ObjectValue(*buffer)); } args.rval().setObject(*buffer); return true; } bool ClientInfo::tls_client_certificate_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedObject buffer(cx, clientCert(self)); if (!buffer) { auto res = request_handle(cx, self).http_req_downstream_tls_raw_client_certificate(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); return true; } auto cert = std::move(res.unwrap().value()); buffer.set(JS::NewArrayBufferWithContents(cx, cert.len, cert.ptr.get(), JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory)); if (!buffer) { // We can be here if the array buffer was too large -- if that was the case then a // JSMSG_BAD_ARRAY_LENGTH will have been created. return false; } // `cert` is now owned by `buffer` static_cast(cert.ptr.release()); JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::ClientCert), JS::ObjectValue(*buffer)); } args.rval().setObject(*buffer); return true; } bool ClientInfo::tls_protocol_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedString result(cx, protocol(self)); if (!result) { auto res = request_handle(cx, self).http_req_downstream_tls_protocol(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } if (!res.unwrap().has_value()) { args.rval().setNull(); return true; } auto protocol = std::move(res.unwrap().value()); result.set(JS_NewStringCopyN(cx, protocol.ptr.get(), protocol.len)); JS::SetReservedSlot(self, static_cast(ClientInfo::Slots::Protocol), JS::StringValue(result)); } args.rval().setString(result); return true; } const JSFunctionSpec ClientInfo::static_methods[] = { JS_FS_END, }; const JSPropertySpec ClientInfo::static_properties[] = { JS_PS_END, }; const JSFunctionSpec ClientInfo::methods[] = { JS_FS_END, }; const JSPropertySpec ClientInfo::properties[] = { JS_PSG("requestId", request_id_get, JSPROP_ENUMERATE), JS_PSG("address", address_get, JSPROP_ENUMERATE), JS_PSG("geo", geo_get, JSPROP_ENUMERATE), JS_PSG("tlsCipherOpensslName", tls_cipher_openssl_name_get, JSPROP_ENUMERATE), JS_PSG("tlsProtocol", tls_protocol_get, JSPROP_ENUMERATE), JS_PSG("tlsJA3MD5", tls_ja3_md5_get, JSPROP_ENUMERATE), JS_PSG("tlsJA4", tls_ja4_get, JSPROP_ENUMERATE), JS_PSG("h2Fingerprint", h2_fingerprint_get, JSPROP_ENUMERATE), JS_PSG("ohFingerprint", oh_fingerprint_get, JSPROP_ENUMERATE), JS_PSG("tlsClientCertificate", tls_client_certificate_get, JSPROP_ENUMERATE), JS_PSG("tlsClientHello", tls_client_hello_get, JSPROP_ENUMERATE), JS_PS_END, }; JSObject *ClientInfo::create(JSContext *cx, JS::HandleValue req) { JS::RootedObject obj(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!obj) { return nullptr; } JS::SetReservedSlot(obj, static_cast(Slots::Request), req); return obj; } namespace { JSString *server_address(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(ServerInfo::Slots::Address)); return val.isString() ? val.toString() : nullptr; } } // namespace JSString *ServerInfo::retrieve_server_address(JSContext *cx, JS::HandleObject self) { auto res = request_handle(cx, self).downstream_server_ip_addr(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return nullptr; } JS::RootedString address(cx, common::ip_octets_to_js_string(cx, std::move(res.unwrap()))); if (!address) { return nullptr; } JS::SetReservedSlot(self, static_cast(ServerInfo::Slots::Address), JS::StringValue(address)); return address; } host_api::HttpReq ServerInfo::request_handle(JSContext *cx, JS::HandleObject self) { JS::RootedValue req(cx, JS::GetReservedSlot(self, static_cast(Slots::Request))); return Request::request_handle(&req.toObject()); } bool ServerInfo::address_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); JS::RootedString address_str(cx, server_address(self)); if (!address_str) { address_str = retrieve_server_address(cx, self); if (!address_str) return false; } args.rval().setString(address_str); return true; } const JSFunctionSpec ServerInfo::static_methods[] = { JS_FS_END, }; const JSPropertySpec ServerInfo::static_properties[] = { JS_PS_END, }; const JSFunctionSpec ServerInfo::methods[] = { JS_FS_END, }; const JSPropertySpec ServerInfo::properties[] = { JS_PSG("address", address_get, JSPROP_ENUMERATE), JS_PS_END, }; JSObject *ServerInfo::create(JSContext *cx, JS::HandleValue req) { JS::RootedObject obj(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!obj) { return nullptr; } JS::SetReservedSlot(obj, static_cast(Slots::Request), req); return obj; } namespace { api::Engine *ENGINE; JS::PersistentRootedObjectVector *FETCH_HANDLERS; void inc_pending_promise_count(JSObject *self) { MOZ_ASSERT(FetchEvent::is_instance(self)); auto count = JS::GetReservedSlot(self, static_cast(FetchEvent::Slots::PendingPromiseCount)) .toInt32(); if (count == 0) { ENGINE->incr_event_loop_interest(); } count++; MOZ_ASSERT(count > 0); JS::SetReservedSlot(self, static_cast(FetchEvent::Slots::PendingPromiseCount), JS::Int32Value(count)); } void dec_pending_promise_count(JSObject *self) { MOZ_ASSERT(FetchEvent::is_instance(self)); auto count = JS::GetReservedSlot(self, static_cast(FetchEvent::Slots::PendingPromiseCount)) .toInt32(); MOZ_ASSERT(count > 0); count--; if (count == 0) { ENGINE->decr_event_loop_interest(); } JS::SetReservedSlot(self, static_cast(FetchEvent::Slots::PendingPromiseCount), JS::Int32Value(count)); } bool add_pending_promise(JSContext *cx, JS::HandleObject self, JS::HandleObject promise) { MOZ_ASSERT(FetchEvent::is_instance(self)); MOZ_ASSERT(JS::IsPromiseObject(promise)); JS::RootedObject handler(cx); handler = &JS::GetReservedSlot( self, static_cast(FetchEvent::Slots::DecPendingPromiseCountFunc)) .toObject(); if (!JS::AddPromiseReactions(cx, promise, handler, handler)) return false; inc_pending_promise_count(self); return true; } } // namespace bool FetchEvent::client_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue clientInfo(cx, JS::GetReservedSlot(self, static_cast(Slots::ClientInfo))); if (clientInfo.isUndefined()) { JS::RootedValue req(cx, JS::GetReservedSlot(self, static_cast(Slots::Request))); JS::RootedObject obj(cx, ClientInfo::create(cx, req)); if (!obj) return false; clientInfo.setObject(*obj); JS::SetReservedSlot(self, static_cast(Slots::ClientInfo), clientInfo); } args.rval().set(clientInfo); return true; } bool FetchEvent::server_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue serverInfo(cx, JS::GetReservedSlot(self, static_cast(Slots::ServerInfo))); if (serverInfo.isUndefined()) { JS::RootedValue req(cx, JS::GetReservedSlot(self, static_cast(Slots::Request))); JS::RootedObject obj(cx, ServerInfo::create(cx, req)); if (!obj) { return false; } serverInfo.setObject(*obj); JS::SetReservedSlot(self, static_cast(Slots::ServerInfo), serverInfo); } args.rval().set(serverInfo); return true; } void dispatch_fetch_event(HandleObject event) { MOZ_ASSERT(FetchEvent::is_instance(event)); RootedValue result(ENGINE->cx()); RootedValue event_val(ENGINE->cx(), JS::ObjectValue(*event)); HandleValueArray argsv = HandleValueArray(event_val); RootedValue handler(ENGINE->cx()); RootedValue rval(ENGINE->cx()); FetchEvent::start_dispatching(event); for (size_t i = 0; i < FETCH_HANDLERS->length(); i++) { handler.setObject(*(*FETCH_HANDLERS)[i]); if (!JS_CallFunctionValue(ENGINE->cx(), ENGINE->global(), handler, argsv, &rval)) { ENGINE->dump_pending_exception("dispatching FetchEvent\n"); break; } if (FetchEvent::state(event) != FetchEvent::State::unhandled) { break; } } FetchEvent::stop_dispatching(event); } void dispatch_fetch_event(HandleObject event, double *total_compute) { auto pre_handler = system_clock::now(); dispatch_fetch_event(event); double diff = duration_cast(system_clock::now() - pre_handler).count(); *total_compute += diff; if (ENGINE->debug_logging_enabled()) { printf("Request handler took %fms\n", diff / 1000); } } JSObject *FetchEvent::prepare_downstream_request(JSContext *cx) { JS::RootedObject requestInstance( cx, JS_NewObjectWithGivenProto(cx, &Request::class_, Request::proto_obj)); if (!requestInstance) return nullptr; return Request::create(cx, requestInstance, host_api::HttpReq{}, host_api::HttpBody{}, true); } bool FetchEvent::init_request(JSContext *cx, JS::HandleObject self, host_api::HttpReq req, host_api::HttpBody body) { builtins::web::performance::Performance::timeOrigin.emplace( std::chrono::high_resolution_clock::now()); JS::RootedObject request( cx, &JS::GetReservedSlot(self, static_cast(Slots::Request)).toObject()); MOZ_ASSERT(!Request::request_handle(request).is_valid()); JS::SetReservedSlot(request, static_cast(Request::Slots::Request), JS::Int32Value(req.handle)); JS::SetReservedSlot(request, static_cast(Request::Slots::Body), JS::Int32Value(body.handle)); // Set the method. auto res = req.get_method(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto method_str = std::move(res.unwrap()); bool is_get = method_str == "GET"sv; bool is_head = method_str == "HEAD"sv; if (!is_get) { std::ignore = common::normalize_http_method(method_str.begin(), method_str.size()); JS::RootedString method(cx, JS_NewStringCopyN(cx, method_str.begin(), method_str.len)); if (!method) { return false; } JS::SetReservedSlot(request, static_cast(Request::Slots::Method), JS::StringValue(method)); } // Set whether we have a body depending on the method. // TODO: verify if that's right. I.e. whether we should treat all requests // that are not GET or HEAD as having a body, which might just be 0-length. // It's not entirely clear what else we even could do here though. if (!is_get && !is_head) { JS::SetReservedSlot(request, static_cast(Request::Slots::HasBody), JS::TrueValue()); } auto uri_res = req.get_uri(); if (auto *err = uri_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto uri_str = std::move(uri_res.unwrap()); JS::RootedString url(cx, JS_NewStringCopyN(cx, uri_str.ptr.get(), uri_str.len)); if (!url) { return false; } JS::SetReservedSlot(request, static_cast(Request::Slots::URL), JS::StringValue(url)); // Set the URL for `globalThis.location` to the client request's URL. JS::RootedObject url_instance(cx, JS_NewObjectWithGivenProto(cx, &URL::class_, URL::proto_obj)); if (!url_instance) { return false; } jsurl::SpecString spec(reinterpret_cast(uri_str.ptr.get()), uri_str.len, uri_str.len); WorkerLocation::url = URL::create(cx, url_instance, spec); if (!WorkerLocation::url) { return false; } // Set `fastly.baseURL` to the origin of the client request's URL. // Note that this only happens if baseURL hasn't already been set to another // value explicitly. if (!Fastly::baseURL.get()) { JS::RootedObject url_instance(cx, JS_NewObjectWithGivenProto(cx, &URL::class_, URL::proto_obj)); if (!url_instance) return false; Fastly::baseURL = URL::create(cx, url_instance, URL::origin(cx, WorkerLocation::url)); if (!Fastly::baseURL) return false; } return true; } bool FetchEvent::request_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().set(JS::GetReservedSlot(self, static_cast(Slots::Request))); return true; } namespace { bool start_response(JSContext *cx, JS::HandleObject response_obj, bool streaming) { auto response = Response::response_handle(response_obj); auto body = RequestOrResponse::body_handle(response_obj); // write all the headers if (!RequestOrResponse::commit_headers(cx, response_obj)) return false; auto res = response.send_downstream(body, streaming); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } return true; } // Steps in this function refer to the spec at // https://w3c.github.io/ServiceWorker/#fetch-event-respondwith bool response_promise_then_handler(JSContext *cx, JS::HandleObject event, JS::HandleValue extra, JS::CallArgs args) { // Step 10.1 // Note: the `then` handler is only invoked after all Promise resolution has // happened. (Even if there were multiple Promises to unwrap first.) That // means that at this point we're guaranteed to have the final value instead // of a Promise wrapping it, so either the value is a Response, or we have to // bail. if (!Response::is_instance(args.get(0))) { JS_ReportErrorUTF8(cx, "FetchEvent#respondWith must be called with a Response " "object or a Promise resolving to a Response object as " "the first argument"); JS::RootedObject rejection(cx, PromiseRejectedWithPendingError(cx)); if (!rejection) return false; args.rval().setObject(*rejection); return FetchEvent::respondWithError(cx, event); } // Step 10.2 (very roughly: the way we handle responses and their bodies is // very different.) JS::RootedObject response_obj(cx, &args[0].toObject()); // Store the FetchEvent on the Response so it can be accessed later JS::SetReservedSlot(response_obj, static_cast(Response::Slots::FetchEvent), JS::ObjectValue(*event)); if (Response::is_upstream(response_obj)) { JS::RootedObject headers(cx, Response::headers(cx, response_obj)); // Calling get_list() transitions to Mode::ContentOnly or Mode::CachedInContent. if (!Headers::get_list(cx, headers)) return false; } if (auto grip_upgrade_request = Response::grip_upgrade_request(response_obj)) { auto backend = Response::backend_str(cx, response_obj); auto res = grip_upgrade_request->redirect_to_grip_proxy(backend); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } FetchEvent::mark_done(event, true, Response::status(response_obj)); return true; } if (auto websocket_upgrade_request = Response::websocket_upgrade_request(response_obj)) { auto backend = Response::backend_str(cx, response_obj); auto res = websocket_upgrade_request->redirect_to_websocket_proxy(backend); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } FetchEvent::mark_done(event, true, Response::status(response_obj)); return true; } bool streaming = false; if (!RequestOrResponse::maybe_stream_body(cx, response_obj, &streaming)) { return false; } if (streaming) { ENGINE->incr_event_loop_interest(); } FetchEvent::mark_done(event, streaming, Response::status(response_obj)); return start_response(cx, response_obj, streaming); } // Steps in this function refer to the spec at // https://w3c.github.io/ServiceWorker/#fetch-event-respondwith bool response_promise_catch_handler(JSContext *cx, JS::HandleObject event, JS::HandleValue promise_val, JS::CallArgs args) { JS::RootedObject promise(cx, &promise_val.toObject()); fprintf(stderr, "Error while running request handler: "); ENGINE->dump_promise_rejection(args.get(0), promise, stderr); // TODO: verify that this is the right behavior. // Steps 9.1-2 return FetchEvent::respondWithError(cx, event); } } // namespace // Steps in this function refer to the spec at // https://w3c.github.io/ServiceWorker/#fetch-event-respondwith bool FetchEvent::respondWith(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) // Coercion of argument `r` to a Promise JS::RootedObject response_promise(cx, JS::CallOriginalPromiseResolve(cx, args.get(0))); if (!response_promise) return false; // Step 2 if (!is_dispatching(self)) { JS_ReportErrorUTF8(cx, "FetchEvent#respondWith must be called synchronously from " "within a FetchEvent handler"); return false; } // Step 3 if (state(self) != State::unhandled && state(self) != State::waitToRespond) { JS_ReportErrorUTF8(cx, "FetchEvent#respondWith can't be called twice on the same event"); return false; } // Step 4 add_pending_promise(cx, self, response_promise); // Steps 5-7 (very roughly) set_state(self, State::waitToRespond); // Step 9 (continued in `response_promise_catch_handler` above) JS::RootedObject catch_handler(cx); JS::RootedValue extra(cx, JS::ObjectValue(*response_promise)); catch_handler = create_internal_method(cx, self, extra); if (!catch_handler) return false; // Step 10 (continued in `response_promise_then_handler` above) JS::RootedObject then_handler(cx); then_handler = create_internal_method(cx, self); if (!then_handler) return false; if (!JS::AddPromiseReactions(cx, response_promise, then_handler, catch_handler)) return false; args.rval().setUndefined(); return true; } bool FetchEvent::sendEarlyHints(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) MOZ_RELEASE_ASSERT(state(self) == State::unhandled || state(self) == State::waitToRespond); if (state(self) != State::unhandled && state(self) != State::waitToRespond) { JS_ReportErrorUTF8( cx, "FetchEvent#sendEarlyHints can't be called after the main response has been sent"); return false; } JS::RootedObject headers(cx, Headers::create(cx, args.get(0), Headers::HeadersGuard::None)); // Calling get_list() transitions to Mode::ContentOnly or Mode::CachedInContent. if (!Headers::get_list(cx, headers)) { return false; } auto response_handle = host_api::HttpResp::make(); if (auto *err = response_handle.to_err()) { HANDLE_ERROR(cx, *err); return false; } // 103: Early Hint auto set_res = response_handle.unwrap().set_status(103); if (auto *err = set_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto body_handle = host_api::HttpBody::make(); if (auto *err = body_handle.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::RootedObject response_instance( cx, JS_NewObjectWithGivenProto(cx, &Response::class_, Response::proto_obj)); if (!response_instance) { return false; } RootedObject response_obj(cx, Response::create(cx, response_instance, response_handle.unwrap(), body_handle.unwrap(), false, nullptr, nullptr, nullptr)); RootedValue headers_val(cx, JS::ObjectValue(*headers)); JS::SetReservedSlot(response_obj, static_cast(Response::Slots::Headers), headers_val); JS::SetReservedSlot(response_obj, static_cast(Response::Slots::Status), JS::Int32Value(103)); RequestOrResponse::set_url(response_obj, JS_GetEmptyStringValue(cx)); args.rval().setUndefined(); return start_response(cx, response_obj, false); } bool FetchEvent::respondWithError(JSContext *cx, JS::HandleObject self) { MOZ_RELEASE_ASSERT(state(self) == State::unhandled || state(self) == State::waitToRespond); set_state(self, State::responsedWithError); auto response_res = host_api::HttpResp::make(); if (auto *err = response_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto make_res = host_api::HttpBody::make(); if (auto *err = make_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto response = response_res.unwrap(); auto status_res = response.set_status(500); if (auto *err = status_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto send_res = response.send_downstream(make_res.unwrap(), false); if (auto *err = send_res.to_err()) { HANDLE_ERROR(cx, *err); return false; } return true; } namespace { // Step 5 of https://w3c.github.io/ServiceWorker/#wait-until-method bool dec_pending_promise_count(JSContext *cx, JS::HandleObject event, JS::HandleValue extra, JS::CallArgs args) { // Step 5.1 dec_pending_promise_count(event); // Note: step 5.2 not relevant to our implementation. return true; } } // namespace // Steps in this function refer to the spec at // https://w3c.github.io/ServiceWorker/#wait-until-method bool FetchEvent::waitUntil(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::RootedObject promise(cx, JS::CallOriginalPromiseResolve(cx, args.get(0))); if (!promise) return false; // Step 2 if (!is_active(self)) { JS_ReportErrorUTF8(cx, "FetchEvent#waitUntil called on inactive event"); return false; } // Steps 3-4 add_pending_promise(cx, self, promise); // Note: step 5 implemented in dec_pending_promise_count args.rval().setUndefined(); return true; } const JSFunctionSpec FetchEvent::static_methods[] = { JS_FS_END, }; const JSPropertySpec FetchEvent::static_properties[] = { JS_PS_END, }; const JSFunctionSpec FetchEvent::methods[] = { JS_FN("respondWith", respondWith, 1, JSPROP_ENUMERATE), JS_FN("waitUntil", waitUntil, 1, JSPROP_ENUMERATE), JS_FN("sendEarlyHints", sendEarlyHints, 1, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec FetchEvent::properties[] = { JS_PSG("client", client_get, JSPROP_ENUMERATE), JS_PSG("request", request_get, JSPROP_ENUMERATE), JS_PSG("server", server_get, JSPROP_ENUMERATE), JS_PS_END, }; JSObject *FetchEvent::create(JSContext *cx) { JS::RootedObject self(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!self) return nullptr; if (!reset(cx, self)) { return nullptr; } return self; } bool FetchEvent::reset(JSContext *cx, JS::HandleObject self) { JS::RootedObject request(cx, prepare_downstream_request(cx)); if (!request) return false; JS::RootedObject dec_count_handler(cx, create_internal_method(cx, self)); if (!dec_count_handler) return false; JS::SetReservedSlot(self, static_cast(Slots::Request), JS::ObjectValue(*request)); JS::SetReservedSlot(self, static_cast(Slots::Dispatch), JS::FalseValue()); JS::SetReservedSlot(self, static_cast(Slots::State), JS::Int32Value((int)State::unhandled)); JS::SetReservedSlot(self, static_cast(Slots::PendingPromiseCount), JS::Int32Value(0)); JS::SetReservedSlot(self, static_cast(Slots::DecPendingPromiseCountFunc), JS::ObjectValue(*dec_count_handler)); JS::SetReservedSlot(self, static_cast(Slots::ClientInfo), JS::UndefinedValue()); JS::SetReservedSlot(self, static_cast(Slots::ServerInfo), JS::UndefinedValue()); return true; } bool FetchEvent::is_active(JSObject *self) { MOZ_ASSERT(is_instance(self)); // Note: we also treat the FetchEvent as active if it's in `responseStreaming` // state because that requires us to extend the service's lifetime as well. In // the spec this is achieved using individual promise counts for the body read // operations. return JS::GetReservedSlot(self, static_cast(Slots::Dispatch)).toBoolean() || state(self) == State::responseStreaming || JS::GetReservedSlot(self, static_cast(Slots::PendingPromiseCount)).toInt32() > 0; } bool FetchEvent::is_dispatching(JSObject *self) { MOZ_ASSERT(is_instance(self)); return JS::GetReservedSlot(self, static_cast(Slots::Dispatch)).toBoolean(); } void FetchEvent::start_dispatching(JSObject *self) { MOZ_ASSERT(!is_dispatching(self)); JS::SetReservedSlot(self, static_cast(Slots::Dispatch), JS::TrueValue()); } void FetchEvent::stop_dispatching(JSObject *self) { MOZ_ASSERT(is_dispatching(self)); JS::SetReservedSlot(self, static_cast(Slots::Dispatch), JS::FalseValue()); } FetchEvent::State FetchEvent::state(JSObject *self) { MOZ_ASSERT(is_instance(self)); return static_cast( JS::GetReservedSlot(self, static_cast(Slots::State)).toInt32()); } void FetchEvent::mark_done(JSObject *self, bool streaming, uint16_t status_code) { MOZ_ASSERT(is_instance(self)); auto new_state = [&] { // 103: Early Hint if (status_code == 103) { return State::unhandled; } if (streaming) { return State::responseStreaming; } return State::responseDone; }(); JS::SetReservedSlot(self, static_cast(Slots::State), JS::Int32Value(static_cast(new_state))); } void FetchEvent::set_state(JSObject *self, State new_state) { MOZ_ASSERT(is_instance(self)); JS::SetReservedSlot(self, static_cast(Slots::State), JS::Int32Value(static_cast(new_state))); } bool FetchEvent::response_started(JSObject *self) { auto current_state = state(self); return current_state != State::unhandled && current_state != State::waitToRespond; } static bool addEventListener(JSContext *cx, unsigned argc, Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "addEventListener", 2)) { return false; } auto event_chars = core::encode(cx, args[0]); if (!event_chars) { return false; } if (strncmp(event_chars.begin(), "fetch", event_chars.len)) { fprintf(stderr, "Error: addEventListener only supports the event 'fetch' right now, " "but got event '%s'\n", event_chars.begin()); exit(1); } RootedValue val(cx, args[1]); if (!val.isObject() || !JS_ObjectIsFunction(&val.toObject())) { fprintf(stderr, "Error: addEventListener: Argument 2 is not a function.\n"); exit(1); } return FETCH_HANDLERS->append(&val.toObject()); } bool install(api::Engine *engine) { ENGINE = engine; FETCH_HANDLERS = new JS::PersistentRootedObjectVector(engine->cx()); if (!JS_DefineFunction(engine->cx(), engine->global(), "addEventListener", addEventListener, 2, 0)) { MOZ_RELEASE_ASSERT(false); } if (!FetchEvent::init_class(engine->cx(), engine->global())) return false; if (!FetchEvent::create(engine->cx())) { MOZ_RELEASE_ASSERT(false); } if (!ClientInfo::init_class(engine->cx(), engine->global())) { return false; } if (!ServerInfo::init_class(engine->cx(), engine->global())) { return false; } return true; } } // namespace fastly::fetch_event ================================================ FILE: runtime/fastly/builtins/fetch-event.h ================================================ #ifndef FASTLY_FETCH_EVENT_H #define FASTLY_FETCH_EVENT_H #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "extension-api.h" #include "host_api.h" #include namespace fastly::fetch_event { class ClientInfo final : public builtins::BuiltinNoConstructor { static bool request_id_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool address_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool geo_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool tls_cipher_openssl_name_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool tls_protocol_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool tls_client_hello_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool tls_ja3_md5_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool tls_ja4_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool h2_fingerprint_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool oh_fingerprint_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool tls_client_certificate_get(JSContext *cx, unsigned argc, JS::Value *vp); static host_api::HttpReq request_handle(JSContext *cx, JS::HandleObject self); static JSString *retrieve_client_address(JSContext *cx, JS::HandleObject self); public: static constexpr const char *class_name = "ClientInfo"; enum class Slots { Request, Address, GeoInfo, Cipher, Protocol, ClientHello, JA3, JA4, H2Fingerprint, OHFingerprint, ClientCert, ClientRequestId, Count, }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static JSObject *create(JSContext *cx, JS::HandleValue req); }; class ServerInfo final : public builtins::BuiltinNoConstructor { static bool address_get(JSContext *cx, unsigned argc, JS::Value *vp); static host_api::HttpReq request_handle(JSContext *cx, JS::HandleObject self); static JSString *retrieve_server_address(JSContext *cx, JS::HandleObject self); public: static constexpr const char *class_name = "ServerInfo"; enum class Slots { Request, Address, Count, }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static JSObject *create(JSContext *cx, JS::HandleValue req); }; void dispatch_fetch_event(HandleObject event); void dispatch_fetch_event(HandleObject event, double *total_compute); class FetchEvent final : public builtins::BuiltinNoConstructor { static bool respondWith(JSContext *cx, unsigned argc, JS::Value *vp); static bool client_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool request_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool server_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool waitUntil(JSContext *cx, unsigned argc, JS::Value *vp); static bool sendEarlyHints(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "FetchEvent"; enum class State { unhandled, waitToRespond, responseStreaming, responseDone, responsedWithError, }; enum class Slots { Dispatch, Request, State, PendingPromiseCount, DecPendingPromiseCountFunc, ClientInfo, ServerInfo, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static JSObject *create(JSContext *cx); static bool reset(JSContext *cx, JS::HandleObject self); /** * Create a Request object for the incoming request. * * Since this happens during initialization time, the object will not be fully * initialized. It's filled in at runtime using `init_request`. */ static JSObject *prepare_downstream_request(JSContext *cx); /** * Fully initialize the Request object based on the incoming request. */ static bool init_request(JSContext *cx, JS::HandleObject self, host_api::HttpReq req, host_api::HttpBody body); static bool respondWithError(JSContext *cx, JS::HandleObject self); static bool is_active(JSObject *self); static bool is_dispatching(JSObject *self); static void start_dispatching(JSObject *self); static void stop_dispatching(JSObject *self); static State state(JSObject *self); static void mark_done(JSObject *self, bool streaming, uint16_t status_code); static void set_state(JSObject *self, State state); static bool response_started(JSObject *self); static JS::HandleObject instance(); }; bool install(api::Engine *engine); } // namespace fastly::fetch_event #endif ================================================ FILE: runtime/fastly/builtins/html-rewriter.cpp ================================================ #include "html-rewriter.h" #include "../../../StarlingMonkey/builtins/web/streams/transform-stream-default-controller.h" #include "../../../StarlingMonkey/builtins/web/streams/transform-stream.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../host-api/host_api_fastly.h" #include using builtins::web::streams::TransformStream; using builtins::web::streams::TransformStreamDefaultController; namespace fastly::html_rewriter { const JSFunctionSpec Element::static_methods[] = {JS_FS_END}; const JSPropertySpec Element::static_properties[] = {JS_PS_END}; const JSFunctionSpec Element::methods[] = { JS_FN("before", before, 1, JSPROP_ENUMERATE), JS_FN("prepend", prepend, 1, JSPROP_ENUMERATE), JS_FN("append", append, 1, JSPROP_ENUMERATE), JS_FN("after", after, 1, JSPROP_ENUMERATE), JS_FN("getAttribute", getAttribute, 1, JSPROP_ENUMERATE), JS_FN("setAttribute", setAttribute, 2, JSPROP_ENUMERATE), JS_FN("removeAttribute", removeAttribute, 1, JSPROP_ENUMERATE), JS_FN("replaceChildren", replaceChildren, 1, JSPROP_ENUMERATE), JS_FN("replaceWith", replaceWith, 1, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec Element::properties[] = { JS_PSG("selector", Element::selector_get, JSPROP_ENUMERATE), JS_PSG("tag", Element::tag_get, JSPROP_ENUMERATE), JS_PS_END}; lol_html_element_t *raw_element(JSObject *self) { MOZ_ASSERT(Element::is_instance(self)); return static_cast( JS::GetReservedSlot(self, static_cast(Element::Slots::Raw)).toPrivate()); } bool Element::selector_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto selector = JS::GetReservedSlot(self, static_cast(Slots::Selector)).toString(); args.rval().setString(selector); return true; } bool Element::tag_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) auto element = raw_element(self); MOZ_ASSERT(element); auto str = lol_html_element_tag_name_get(element); args.rval().setString(JS_NewStringCopyN(cx, str.data, str.len)); return true; } // We should escape only if the user supplies { escapeHTML: true } in the options object static bool should_escape_html(JSContext *cx, JS::HandleValue options_arg) { if (!options_arg.isObject()) { return false; } JS::RootedObject options_obj(cx, &options_arg.toObject()); JS::RootedValue escape_html_val(cx); if (!JS_GetProperty(cx, options_obj, "escapeHTML", &escape_html_val)) { return false; } return escape_html_val.isBoolean() && escape_html_val.toBoolean(); } bool Element::before(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::HandleValue content_arg = args.get(0); auto content = core::encode(cx, content_arg); if (!content) { return false; } auto element = raw_element(self); MOZ_ASSERT(element); return lol_html_element_before(element, content.begin(), content.size(), !should_escape_html(cx, args.get(1))) == 0; } bool Element::prepend(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::HandleValue content_arg = args.get(0); auto content = core::encode(cx, content_arg); if (!content) { return false; } auto element = raw_element(self); MOZ_ASSERT(element); return lol_html_element_prepend(element, content.begin(), content.size(), !should_escape_html(cx, args.get(1))) == 0; } bool Element::append(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::HandleValue content_arg = args.get(0); auto content = core::encode(cx, content_arg); if (!content) { return false; } auto element = raw_element(self); MOZ_ASSERT(element); return lol_html_element_append(element, content.begin(), content.size(), !should_escape_html(cx, args.get(1))) == 0; } bool Element::after(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::HandleValue content_arg = args.get(0); auto content = core::encode(cx, content_arg); if (!content) { return false; } auto element = raw_element(self); MOZ_ASSERT(element); return lol_html_element_after(element, content.begin(), content.size(), !should_escape_html(cx, args.get(1))) == 0; } bool Element::getAttribute(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::HandleValue name_arg = args.get(0); auto name = core::encode(cx, name_arg); if (!name) { return false; } auto element = raw_element(self); MOZ_ASSERT(element); auto attr = lol_html_element_get_attribute(element, name.begin(), name.size()); if (!attr.data) { args.rval().setNull(); } else { args.rval().setString(JS_NewStringCopyN(cx, attr.data, attr.len)); } return true; } bool Element::setAttribute(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(2) JS::HandleValue name_arg = args.get(0); auto name = core::encode(cx, name_arg); if (!name) { return false; } JS::HandleValue value_arg = args.get(1); auto value = core::encode(cx, value_arg); if (!value) { return false; } auto element = raw_element(self); MOZ_ASSERT(element); return lol_html_element_set_attribute(element, name.begin(), name.size(), value.begin(), value.size()) == 0; } bool Element::removeAttribute(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::HandleValue name_arg = args.get(0); auto name = core::encode(cx, name_arg); if (!name) { return false; } auto element = raw_element(self); MOZ_ASSERT(element); lol_html_element_remove_attribute(element, name.begin(), name.size()); return true; } bool Element::replaceChildren(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::HandleValue content_arg = args.get(0); auto content = core::encode(cx, content_arg); if (!content) { return false; } auto element = raw_element(self); MOZ_ASSERT(element); return lol_html_element_set_inner_content(element, content.begin(), content.size(), !should_escape_html(cx, args.get(1))) == 0; } bool Element::replaceWith(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::HandleValue content_arg = args.get(0); auto content = core::encode(cx, content_arg); if (!content) { return false; } auto element = raw_element(self); MOZ_ASSERT(element); return lol_html_element_replace(element, content.begin(), content.size(), !should_escape_html(cx, args.get(1))) == 0; } static JSObject *create_element(JSContext *cx, lol_html_element_t *element, JS::HandleString selector) { JS::RootedObject obj(cx, JS_NewObjectWithGivenProto(cx, &Element::class_, Element::proto_obj)); if (!obj) { return nullptr; } JS::SetReservedSlot(obj, static_cast(Element::Slots::Raw), JS::PrivateValue(element)); JS::SetReservedSlot(obj, static_cast(Element::Slots::Selector), JS::StringValue(selector)); return obj; } const JSFunctionSpec HTMLRewritingStream::static_methods[] = {JS_FS_END}; const JSPropertySpec HTMLRewritingStream::static_properties[] = {JS_PS_END}; const JSFunctionSpec HTMLRewritingStream::methods[] = { JS_FN("onElement", onElement, 2, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec HTMLRewritingStream::properties[] = { JS_PSG("readable", HTMLRewritingStream::readable_get, JSPROP_ENUMERATE), JS_PSG("writable", HTMLRewritingStream::writable_get, JSPROP_ENUMERATE), JS_PS_END}; static lol_html_rewriter_builder_t *builder(JSObject *self) { MOZ_ASSERT(HTMLRewritingStream::is_instance(self)); return static_cast( JS::GetReservedSlot(self, static_cast(HTMLRewritingStream::Slots::RawBuilder)) .toPrivate()); } static void set_builder(JSObject *self, lol_html_rewriter_builder_t *builder) { MOZ_ASSERT(HTMLRewritingStream::is_instance(self)); JS::SetReservedSlot(self, static_cast(HTMLRewritingStream::Slots::RawBuilder), JS::PrivateValue(builder)); } static JSObject *transform(JSObject *self) { MOZ_ASSERT(HTMLRewritingStream::is_instance(self)); return &JS::GetReservedSlot(self, HTMLRewritingStream::Slots::Transform).toObject(); } static lol_html_rewriter_t *raw_rewriter(JSObject *self) { MOZ_ASSERT(HTMLRewritingStream::is_instance(self)); return static_cast( JS::GetReservedSlot(self, static_cast(HTMLRewritingStream::Slots::RawRewriter)) .toPrivate()); } static void set_raw_rewriter(JSObject *self, lol_html_rewriter_t *rewriter) { MOZ_ASSERT(HTMLRewritingStream::is_instance(self)); JS::SetReservedSlot(self, HTMLRewritingStream::Slots::RawRewriter, JS::PrivateValue(rewriter)); } // Data needed to call an element handler from lol_html // This also manages the lifetime of the lol-html selector // There should be exactly one of these per element handler registered on the rewriter // They should all be deleted when the HTMLRewritingStream is finalized class ElementHandlerData { public: ElementHandlerData(JSContext *cx, JSObject *handler, JSString *js_selector, lol_html_selector_t *raw_selector) : cx_(cx), handler_(handler), js_selector_(js_selector), raw_selector_(raw_selector) {} ~ElementHandlerData() { lol_html_selector_free(raw_selector_); } JSContext *cx() const { return cx_; } JSObject *handler() const { return handler_; } JSString *selector() const { return js_selector_; } void trace(JSTracer *trc) { TraceEdge(trc, &handler_, "ElementHandlerData handler"); TraceEdge(trc, &js_selector_, "ElementHandlerData selector"); } private: JSContext *cx_; JS::Heap handler_; JS::Heap js_selector_; lol_html_selector_t *raw_selector_; }; // Called by lol_html when an element matching a registered selector is found static lol_html_rewriter_directive_t handle_element(lol_html_element_t *element, void *user_data) { auto *data = static_cast(user_data); JS::RootedString selector(data->cx(), data->selector()); JS::RootedObject jsElement(data->cx(), create_element(data->cx(), element, selector)); if (!jsElement) { return LOL_HTML_STOP; } JS::RootedValue jsElementVal(data->cx(), JS::ObjectValue(*jsElement)); JS::RootedValue handlerVal(data->cx(), JS::ObjectValue(*data->handler())); JS::HandleValueArray arg(jsElementVal); JS::RootedValue rval(data->cx()); if (!JS_CallFunctionValue(data->cx(), nullptr, handlerVal, arg, &rval)) { return LOL_HTML_STOP; } return LOL_HTML_CONTINUE; } bool HTMLRewritingStream::onElement(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(2) if (!builder(self)) { JS_ReportErrorASCII(cx, "HTMLRewriter: cannot add handlers after the rewriter has been used"); return false; } JS::HandleValue selector_arg = args.get(0); auto selector_str = core::encode(cx, selector_arg); if (!selector_str) { return false; } JS::HandleValue handler = args.get(1); if (!handler.isObject() || !JS_ObjectIsFunction(&handler.toObject())) { JS_ReportErrorASCII(cx, "HTMLRewriter: element handler must be a function"); return false; } auto raw_selector = lol_html_selector_parse(selector_str.begin(), selector_str.size()); if (!raw_selector) { auto error = lol_html_take_last_error(); if (error.data) { // Error may not be null-terminated std::string msg(error.data, error.len); JS_ReportErrorASCII(cx, "HTMLRewriter: invalid selector - %s", msg.c_str()); } else { JS_ReportErrorASCII(cx, "HTMLRewriter: invalid selector"); } return false; } // Create a unique_ptr so we don't leak if we error out below auto handler_data = std::make_unique(cx, &handler.toObject(), selector_arg.toString(), raw_selector); if (lol_html_rewriter_builder_add_element_content_handlers( builder(self), raw_selector, handle_element, handler_data.get(), nullptr, nullptr, nullptr, nullptr) != 0) { return false; } // This slot holds all element handlers so we can free them when the stream is finalized. // This will also free the lol-html selectors. auto element_handlers = static_cast *>( JS::GetReservedSlot(self, static_cast(Slots::ElementHandlers)).toPrivate()); element_handlers->push_back(handler_data.release()); args.rval().setObject(*self); return true; } struct OutputContextData { JSContext *cx; JS::Heap self; bool enqueue_failed; OutputContextData(JSContext *cx, JSObject *self) : cx(cx), self(self), enqueue_failed(false) {} void trace(JSTracer *trc) { TraceEdge(trc, &self, "OutputContextData self"); } }; void HTMLRewritingStream::finalize(JS::GCContext *gcx, JSObject *self) { MOZ_ASSERT(is_instance(self)); auto build = builder(self); if (build) { lol_html_rewriter_builder_free(static_cast(build)); } auto element_handlers = static_cast *>( JS::GetReservedSlot(self, static_cast(Slots::ElementHandlers)).toPrivate()); if (element_handlers) { for (auto handler : *element_handlers) { delete handler; } delete element_handlers; } auto output_context = static_cast( JS::GetReservedSlot(self, HTMLRewritingStream::Slots::OutputContext).toPrivate()); if (output_context) { delete output_context; } auto rewriter = raw_rewriter(self); if (rewriter) { lol_html_rewriter_free(static_cast(rewriter)); } } void HTMLRewritingStream::trace(JSTracer *trc, JSObject *self) { MOZ_ASSERT(is_instance(self)); auto element_handlers_val = JS::GetReservedSlot(self, static_cast(Slots::ElementHandlers)); if (!element_handlers_val.isUndefined()) { auto element_handlers = static_cast *>(element_handlers_val.toPrivate()); if (element_handlers) { for (auto *handler : *element_handlers) { handler->trace(trc); } } } auto output_context_val = JS::GetReservedSlot(self, static_cast(Slots::OutputContext)); if (!output_context_val.isUndefined()) { auto output_context = static_cast(output_context_val.toPrivate()); if (output_context) { output_context->trace(trc); } } } static void output_callback(const char *chunk, size_t chunk_len, void *user_data) { auto *ctx = static_cast(user_data); JSContext *cx = ctx->cx; JS::RootedObject self(cx, ctx->self); JS::RootedObject out_obj(cx, JS_NewUint8Array(cx, chunk_len)); if (!out_obj) { return; } { bool is_shared; JS::AutoCheckCannotGC nogc(cx); uint8_t *out_buffer = JS_GetUint8ArrayData(out_obj, &is_shared, nogc); memcpy(out_buffer, chunk, chunk_len); } JS::RootedObject controller(cx, TransformStream::controller(transform(self))); JS::RootedValue out_chunk(cx, JS::ObjectValue(*out_obj)); if (!TransformStreamDefaultController::Enqueue(cx, controller, out_chunk)) { ctx->enqueue_failed = true; return; } } // lol-html doesn't support registering handlers after any input has been processed, // so we finalize the builder and create the rewriter on the first chunk submitted to transform bool HTMLRewritingStream::finish_building(JSContext *cx, JS::HandleObject stream) { MOZ_ASSERT(is_instance(stream)); // The output callback needs the JSContext and the stream object so it can enqueue into output // stream. We use a unique_ptr to ensure we don't leak if something fails. auto output_context = std::make_unique(cx, stream); // Same defaults as Rust lol_html_memory_settings_t memory_settings = {1024, std::numeric_limits::max()}; auto encoding_string_length = 5; // "utf-8" auto rewriter = lol_html_rewriter_build(builder(stream), "utf-8", encoding_string_length, memory_settings, output_callback, output_context.get(), true); if (!rewriter) { return false; } JS_SetReservedSlot(stream, HTMLRewritingStream::Slots::OutputContext, JS::PrivateValue(output_context.release())); set_raw_rewriter(stream, rewriter); // The builder is no longer needed after building the rewriter and can be safely freed lol_html_rewriter_builder_free(builder(stream)); set_builder(stream, nullptr); // Ensure we don't try to free it again in finalize return true; } bool HTMLRewritingStream::transformAlgorithm(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER_WITH_NAME(1, "HTML rewriter transform algorithm") if (!raw_rewriter(self)) { HTMLRewritingStream::finish_building(cx, self); } auto rewriter = raw_rewriter(self); MOZ_ASSERT(rewriter); auto chunk = args.get(0); auto data = value_to_buffer(cx, chunk, "HTMLRewritingStream transform: chunks"); if (!data.has_value()) { return false; } if (data->size() == 0) { return true; } lol_html_take_last_error(); // Clear any previous error // lol-html will call output_callback with the processed data lol_html_rewriter_write(rewriter, reinterpret_cast(data->data()), data->size()); auto err = lol_html_take_last_error(); if (err.data) { // Error may not be null-terminated JS_ReportErrorASCII(cx, "Error processing HTML: %s", std::string(err.data, err.len).c_str()); return false; } auto output_context = static_cast( JS::GetReservedSlot(self, HTMLRewritingStream::Slots::OutputContext).toPrivate()); if (output_context->enqueue_failed) { JS_ReportErrorASCII(cx, "Error processing HTML: output stream enqueue failed"); return false; } args.rval().setUndefined(); return true; } bool HTMLRewritingStream::flushAlgorithm(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER_WITH_NAME(0, "HTML rewriter flush algorithm") // Just in case the stream is flushed immediately if (!raw_rewriter(self)) { HTMLRewritingStream::finish_building(cx, self); } auto rewriter = raw_rewriter(self); MOZ_ASSERT(rewriter); lol_html_take_last_error(); // Clear any previous error // lol-html will call output_callback with any remaining data lol_html_rewriter_end(rewriter); auto err = lol_html_take_last_error(); if (err.data) { // Error may not be null-terminated JS_ReportErrorASCII(cx, "Error processing HTML: %s", std::string(err.data, err.len).c_str()); return false; } args.rval().setUndefined(); return true; } bool HTMLRewritingStream::readable_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER_WITH_NAME(0, "get readable") args.rval().setObject(*TransformStream::readable(transform(self))); return true; } bool HTMLRewritingStream::writable_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER_WITH_NAME(0, "get writable") args.rval().setObject(*TransformStream::writable(transform(self))); return true; } JS::PersistentRooted transformAlgo; JS::PersistentRooted flushAlgo; bool HTMLRewritingStream::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { CTOR_HEADER("HTMLRewritingStream", 0) JS::RootedObject instance(cx, JS_NewObjectForConstructor(cx, &class_, args)); if (!instance) { return false; } auto builder = lol_html_rewriter_builder_new(); if (!builder) { return false; } set_builder(instance, builder); // We have no rewriter initially; it will be created on the first chunk processed set_raw_rewriter(instance, nullptr); JS::SetReservedSlot(instance, static_cast(Slots::OutputContext), JS::PrivateValue(nullptr)); JS::RootedValue stream_val(cx, JS::ObjectValue(*instance)); JS::RootedObject transform(cx, TransformStream::create(cx, 1, nullptr, 0, nullptr, stream_val, nullptr, transformAlgo, flushAlgo)); if (!transform) { return false; } TransformStream::set_used_as_mixin(transform); JS::SetReservedSlot(instance, HTMLRewritingStream::Slots::Transform, JS::ObjectValue(*transform)); JS::SetReservedSlot(instance, static_cast(Slots::ElementHandlers), JS::PrivateValue(new std::vector())); args.rval().setObject(*instance); return true; } bool HTMLRewritingStream::init_class(JSContext *cx, JS::HandleObject global) { if (!init_class_impl(cx, global)) { return false; } JSFunction *transformFun = JS_NewFunction(cx, transformAlgorithm, 1, 0, "HTML Rewriter Transform"); if (!transformFun) return false; transformAlgo.init(cx, JS_GetFunctionObject(transformFun)); JSFunction *flushFun = JS_NewFunction(cx, flushAlgorithm, 1, 0, "HTML Rewriter Flush"); if (!flushFun) return false; flushAlgo.init(cx, JS_GetFunctionObject(flushFun)); return true; } bool install(api::Engine *engine) { if (!HTMLRewritingStream::init_class(engine->cx(), engine->global())) { return false; } if (!Element::init_class(engine->cx(), engine->global())) { return false; } RootedObject html_rewriter_obj( engine->cx(), JS_GetConstructor(engine->cx(), builtins::BuiltinImpl::proto_obj)); RootedValue html_rewriter_val(engine->cx(), ObjectValue(*html_rewriter_obj)); RootedObject html_rewriter_ns(engine->cx(), JS_NewObject(engine->cx(), nullptr)); if (!JS_SetProperty(engine->cx(), html_rewriter_ns, "HTMLRewritingStream", html_rewriter_val)) { return false; } RootedValue html_rewriter_ns_val(engine->cx(), JS::ObjectValue(*html_rewriter_ns)); if (!engine->define_builtin_module("fastly:html-rewriter", html_rewriter_ns_val)) { return false; } return true; } } // namespace fastly::html_rewriter ================================================ FILE: runtime/fastly/builtins/html-rewriter.h ================================================ // An HTML rewriter implementation based on TransformStreams. #ifndef FASTLY_HTML_REWRITER_H #define FASTLY_HTML_REWRITER_H #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "extension-api.h" namespace fastly::html_rewriter { class Element : public builtins::BuiltinNoConstructor { private: static bool selector_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool tag_get(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "Element"; static const int ctor_length = 0; enum Slots { Raw, Selector, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool before(JSContext *cx, unsigned argc, JS::Value *vp); static bool prepend(JSContext *cx, unsigned argc, JS::Value *vp); static bool append(JSContext *cx, unsigned argc, JS::Value *vp); static bool after(JSContext *cx, unsigned argc, JS::Value *vp); static bool getAttribute(JSContext *cx, unsigned argc, JS::Value *vp); static bool setAttribute(JSContext *cx, unsigned argc, JS::Value *vp); static bool removeAttribute(JSContext *cx, unsigned argc, JS::Value *vp); static bool replaceChildren(JSContext *cx, unsigned argc, JS::Value *vp); static bool replaceWith(JSContext *cx, unsigned argc, JS::Value *vp); }; class HTMLRewritingStream : public builtins::TraceableBuiltinImpl { private: static bool transformAlgorithm(JSContext *cx, unsigned argc, JS::Value *vp); static bool flushAlgorithm(JSContext *cx, unsigned argc, JS::Value *vp); static bool readable_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool writable_get(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "HTMLRewritingStream"; static const int ctor_length = 0; enum Slots { RawBuilder, RawRewriter, Buffer, OutputContext, ElementHandlers, Transform, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool init_class(JSContext *cx, JS::HandleObject global); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); static bool onElement(JSContext *cx, unsigned argc, JS::Value *vp); static bool finish_building(JSContext *cx, JS::HandleObject stream); static void finalize(JS::GCContext *gcx, JSObject *self); static void trace(JSTracer *trc, JSObject *self); }; } // namespace fastly::html_rewriter #endif ================================================ FILE: runtime/fastly/builtins/image-optimizer-options.inc ================================================ // Defines X-Macros (https://en.wikipedia.org/wiki/X_macro) for enumerator image optimizer options #if !defined(FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION) && \ !defined(FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE) && \ !defined(FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE) #error "Must define at least one of the FASTLY_DEFINE_IMAGE_OPTIMIZER_*** macros" #endif #ifndef FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE #define FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(type, lowercase, str) #endif #ifndef FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION #define FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(name, str) #endif #ifndef FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE #define FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(type) #endif FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(Region, region, "region") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(UsEast, "us_east") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(UsCentral, "us_central") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(UsWest, "us_west") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(EuCentral, "eu_central") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(EuWest, "eu_west") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Asia, "asia") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Australia, "australia") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Region) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(Auto, auto, "auto") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(AVIF, "avif") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(WEBP, "webp") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Auto) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(Format, format, "format") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Auto, "auto") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(AVIF, "avif") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(BJPG, "bjpg") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(GIF, "gif") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(JPG, "jpg") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(JXL, "jxl") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(MP4, "mp4") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(PJPG, "pjpg") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(PJXL, "pjxl") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(PNG, "png") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(PNG8, "png8") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(SVG, "svg") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(WEBP, "webp") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(WEBPLL, "webpll") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(WEBPLY, "webply") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Format) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(BWAlgorithm, bw, "bw") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Threshold, "threshold") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Atkinson, "atkinson") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(BWAlgorithm) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(Disable, disable, "disable") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Upscale, "upscale") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Disable) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(Enable, enable, "enable") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Upscale, "upscale") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Enable) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(Fit, fit, "fit") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Bounds, "bounds") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Cover, "cover") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Crop, "crop") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Fit) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(Metadata, metadata, "metadata") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Copyright, "copyright") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(C2PA, "c2pa") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(CopyrightAndC2PA, "copyright,c2pa") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Metadata) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(Optimize, optimize, "optimize") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Low, "low") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Medium, "medium") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(High, "high") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Optimize) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(Orient, orient, "orient") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Default, "1") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(FlipHorizontal, "2") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(FlipHorizontalAndVertical, "3") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(FlipVertical, "4") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(FlipHorizontalOrientLeft, "5") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(OrientRight, "6") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(FlipHorizontalOrientRight, "7") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(OrientLeft, "8") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Orient) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(Profile, profile, "profile") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Baseline, "baseline") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Main, "main") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(High, "high") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Profile) FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(ResizeFilter, resize_filter, "resize-filter") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Nearest, "nearest") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Bilinear, "bilinear") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Linear, "linear") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Bicubic, "bicubic") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Cubic, "cubic") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Lanczos2, "lanczos2") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Lanczos3, "lanczos3") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Lanczos, "lanczos") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(ResizeFilter) // CropMode is not a "true" option, but we reuse some of this machinery to easily define the // constants FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(CropMode, crop_mode, "N/A") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Smart, "smart") FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(Safe, "safe") FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(Optimize) #undef FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION #undef FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE #undef FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE ================================================ FILE: runtime/fastly/builtins/image-optimizer.cpp ================================================ #include "image-optimizer.h" #include "fastly.h" namespace { std::optional from_percentage(std::string_view sv) { if (!sv.ends_with('%')) { return std::nullopt; } char *end; auto percentage = std::strtod(sv.data(), &end); if (end != sv.data() + sv.size() - 1 || percentage == HUGE_VAL) { return std::nullopt; } return percentage; } std::optional to_number_between_inclusive(JS::HandleValue val, double from, double to) { if (!val.isNumber()) { return std::nullopt; } auto num = val.toNumber(); if (num < from || num > to) { return std::nullopt; } return num; } bool exactly_one_defined(JS::HandleValue a, JS::HandleValue b) { return (!a.isUndefined() || !b.isUndefined()) && (a.isUndefined() != b.isUndefined()); } } // namespace namespace fastly::image_optimizer { const JSFunctionSpec EnumOption::static_methods[] = { JS_FS_END, }; const JSFunctionSpec EnumOption::methods[] = { JS_FS_END, }; const JSPropertySpec EnumOption::properties[] = { JS_PS_END, }; #define FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(type, lowercase, str) \ const JSPropertySpec type::static_properties[] = { #define FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(name, str) JS_STRING_PS(#name, str, JSPROP_READONLY), #define FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(type) \ JS_PS_END, \ } \ ; #include "image-optimizer-options.inc" bool install(api::Engine *engine) { RootedObject image_optimizer_ns(engine->cx(), JS_NewObject(engine->cx(), nullptr)); #define FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(type, lowercase, str) \ if (!type::init_class_impl(engine->cx(), image_optimizer_ns)) { \ return false; \ } \ RootedObject lowercase##_obj( \ engine->cx(), \ JS_GetConstructor( \ engine->cx(), \ builtins::BuiltinNoConstructor<::fastly::image_optimizer::type>::proto_obj)); \ RootedValue lowercase##_val(engine->cx(), ObjectValue(*lowercase##_obj)); \ if (!JS_SetProperty(engine->cx(), image_optimizer_ns, #type, lowercase##_val)) { \ return false; \ } #define FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(name, str) #define FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(type) #include "image-optimizer-options.inc" auto options_to_query_string_fn = JS_NewFunction( engine->cx(), &ImageOptimizerOptions::optionsToQueryString, 1, 0, "optionsToQueryString"); RootedObject options_to_query_string_obj(engine->cx(), JS_GetFunctionObject(options_to_query_string_fn)); RootedValue options_to_query_string_val(engine->cx(), JS::ObjectValue(*options_to_query_string_obj)); if (!JS_SetProperty(engine->cx(), image_optimizer_ns, "optionsToQueryString", options_to_query_string_val)) { return false; } RootedValue image_optimizer_ns_val(engine->cx(), JS::ObjectValue(*image_optimizer_ns)); if (!engine->define_builtin_module("fastly:image-optimizer", image_optimizer_ns_val)) { return false; } RootedObject fastly(engine->cx()); if (!fastly::get_fastly_object(engine, &fastly)) { return false; } if (!JS_SetProperty(engine->cx(), fastly, "imageOptimizer", image_optimizer_ns_val)) { return false; } return true; } // namespace fastly::image_optimizer std::unique_ptr ImageOptimizerOptions::create(JSContext *cx, JS::HandleValue opts_val) { // Extract properties. #define FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(type, lowercase, str) \ JS::RootedValue lowercase##_val(cx); #include "image-optimizer-options.inc" JS::RootedValue preserve_query_string_on_origin_request_val(cx); JS::RootedValue bg_color_val(cx); JS::RootedValue blur_val(cx); JS::RootedValue brightness_val(cx); JS::RootedValue canvas_val(cx); JS::RootedValue contrast_val(cx); JS::RootedValue crop_val(cx); JS::RootedValue dpr_val(cx); JS::RootedValue frame_val(cx); JS::RootedValue height_val(cx); JS::RootedValue level_val(cx); JS::RootedValue pad_val(cx); JS::RootedValue precrop_val(cx); JS::RootedValue quality_val(cx); JS::RootedValue saturation_val(cx); JS::RootedValue sharpen_val(cx); JS::RootedValue trim_val(cx); JS::RootedValue trim_color_val(cx); JS::RootedValue viewbox_val(cx); JS::RootedValue width_val(cx); JS::RootedObject opts(cx, opts_val.toObjectOrNull()); if (!JS_GetProperty(cx, opts, "region", ®ion_val) || !JS_GetProperty(cx, opts, "preserve_query_string_on_origin_request", &preserve_query_string_on_origin_request_val) || !JS_GetProperty(cx, opts, "auto", &auto_val) || !JS_GetProperty(cx, opts, "bgColor", &bg_color_val) || !JS_GetProperty(cx, opts, "blur", &blur_val) || !JS_GetProperty(cx, opts, "brightness", &brightness_val) || !JS_GetProperty(cx, opts, "bw", &bw_val) || !JS_GetProperty(cx, opts, "canvas", &canvas_val) || !JS_GetProperty(cx, opts, "contrast", &contrast_val) || !JS_GetProperty(cx, opts, "crop", &crop_val) || !JS_GetProperty(cx, opts, "disable", &disable_val) || !JS_GetProperty(cx, opts, "dpr", &dpr_val) || !JS_GetProperty(cx, opts, "enable", &enable_val) || !JS_GetProperty(cx, opts, "fit", &fit_val) || !JS_GetProperty(cx, opts, "format", &format_val) || !JS_GetProperty(cx, opts, "frame", &frame_val) || !JS_GetProperty(cx, opts, "height", &height_val) || !JS_GetProperty(cx, opts, "level", &level_val) || !JS_GetProperty(cx, opts, "metadata", &metadata_val) || !JS_GetProperty(cx, opts, "optimize", &optimize_val) || !JS_GetProperty(cx, opts, "orient", &orient_val) || !JS_GetProperty(cx, opts, "pad", &pad_val) || !JS_GetProperty(cx, opts, "precrop", &precrop_val) || !JS_GetProperty(cx, opts, "profile", &profile_val) || !JS_GetProperty(cx, opts, "quality", &quality_val) || !JS_GetProperty(cx, opts, "resizeFilter", &resize_filter_val) || !JS_GetProperty(cx, opts, "saturation", &saturation_val) || !JS_GetProperty(cx, opts, "sharpen", &sharpen_val) || !JS_GetProperty(cx, opts, "trim", &trim_val) || !JS_GetProperty(cx, opts, "trimColor", &trim_color_val) || !JS_GetProperty(cx, opts, "viewbox", &viewbox_val) || !JS_GetProperty(cx, opts, "width", &width_val)) { return nullptr; } if (region_val.isUndefined()) { api::throw_error(cx, api::Errors::TypeError, "Request", "imageOptimizerOptions", "contain region"); return nullptr; } #define TRY_CONVERT(name) \ decltype(to_##name(cx, name##_val)) name##_opt; \ if (!name##_val.isUndefined()) { \ name##_opt = to_##name(cx, name##_val); \ if (!name##_opt) { \ return nullptr; \ } \ } #define FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(type, lowercase, str) TRY_CONVERT(lowercase); #include "image-optimizer-options.inc" TRY_CONVERT(bg_color); TRY_CONVERT(blur); TRY_CONVERT(brightness); TRY_CONVERT(canvas); TRY_CONVERT(contrast); TRY_CONVERT(crop); TRY_CONVERT(dpr); TRY_CONVERT(frame); TRY_CONVERT(height); TRY_CONVERT(level); TRY_CONVERT(pad); TRY_CONVERT(precrop); TRY_CONVERT(quality); TRY_CONVERT(saturation); TRY_CONVERT(sharpen); TRY_CONVERT(trim); TRY_CONVERT(trim_color); TRY_CONVERT(viewbox); TRY_CONVERT(width); return std::unique_ptr{new ImageOptimizerOptions( *region_opt, auto_opt, std::move(bg_color_opt), blur_opt, brightness_opt, bw_opt, canvas_opt, contrast_opt, crop_opt, disable_opt, dpr_opt, enable_opt, fit_opt, format_opt, frame_opt, height_opt, std::move(level_opt), metadata_opt, optimize_opt, orient_opt, pad_opt, precrop_opt, profile_opt, quality_opt, resize_filter_opt, saturation_opt, sharpen_opt, trim_opt, std::move(trim_color_opt), viewbox_opt, width_opt)}; } bool ImageOptimizerOptions::optionsToQueryString(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "optionsToQueryString", 1)) { return false; } auto options = create(cx, args.get(0)); if (!options) { return false; } auto query = options->to_string(); args.rval().setString(JS_NewStringCopyZ(cx, query.data())); return true; } std::string ImageOptimizerOptions::to_string() const { using image_optimizer::to_string; std::string ret = to_string(region_); auto append = [&ret](auto &&v) { if (v) ret += "&" + to_string(*v); }; append(auto_); append(bg_color_); append(blur_); append(brightness_); append(bw_); append(canvas_); append(crop_); append(contrast_); append(disable_); append(dpr_); append(enable_); append(fit_); append(format_); append(frame_); append(height_); append(level_); append(metadata_); append(optimize_); append(orient_); append(pad_); append(precrop_); append(profile_); append(quality_); append(resizeFilter_); append(saturation_); append(sharpen_); append(trim_); append(trim_color_); append(viewbox_); append(width_); return ret; } fastly_image_optimizer_transform_config ImageOptimizerOptions::to_config() { fastly_image_optimizer_transform_config config; auto str = this->to_string(); host_api::HostString host_str(str); config.sdk_claims_opts = host_str.ptr.release(); config.sdk_claims_opts_len = host_str.len; return config; } std::optional ImageOptimizerOptions::to_size(JSContext *cx, JS::HandleValue val) { auto throw_error = [&](const char *object, const char *message) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", object, message); return std::nullopt; }; if (val.isUndefined() || !val.isObject()) { return throw_error("size", "be an object"); } JS::RootedValue absolute_val(cx); JS::RootedValue ratio_val(cx); JS::RootedObject size_obj(cx, &val.toObject()); if (!JS_GetProperty(cx, size_obj, "absolute", &absolute_val) || !JS_GetProperty(cx, size_obj, "ratio", &ratio_val)) { return std::nullopt; } if (!exactly_one_defined(absolute_val, ratio_val)) { return throw_error("size", "have exactly one of the keys absolute or ratio"); } JS::RootedValue width_val(cx); JS::RootedValue height_val(cx); if (!absolute_val.isUndefined()) { if (!absolute_val.isObject()) { return throw_error("size.absolute", "be an object"); } JS::RootedObject absolute_obj(cx, &absolute_val.toObject()); if (!JS_GetProperty(cx, absolute_obj, "width", &width_val) || !JS_GetProperty(cx, absolute_obj, "height", &height_val)) { return std::nullopt; } auto width = to_pixels_or_percentage(cx, width_val); auto height = to_pixels_or_percentage(cx, height_val); if (!width || !height) { return throw_error( "size.absolute", "have width and height values who are absolute pixel integers or percentage strings"); } return Size{Size::Absolute{*width, *height}}; } else { if (!ratio_val.isObject()) { return throw_error("size.ratio", "be an object"); } JS::RootedObject ratio_obj(cx, &ratio_val.toObject()); if (!JS_GetProperty(cx, ratio_obj, "width", &width_val) || !JS_GetProperty(cx, ratio_obj, "height", &height_val)) { return std::nullopt; } if (!width_val.isNumber() || !height_val.isNumber()) { return throw_error("size.ratio", "have width and height number values"); } return Size{Size::Ratio{width_val.toNumber(), height_val.toNumber()}}; } } std::optional ImageOptimizerOptions::to_position(JSContext *cx, JS::HandleValue val) { auto throw_error = [&](const char *object, const char *message) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", object, message); return std::nullopt; }; JS::RootedValue x_val(cx); JS::RootedValue y_val(cx); JS::RootedValue offset_x_val(cx); JS::RootedValue offset_y_val(cx); JS::RootedObject position_obj(cx, &val.toObject()); if (!JS_GetProperty(cx, position_obj, "x", &x_val) || !JS_GetProperty(cx, position_obj, "y", &y_val) || !JS_GetProperty(cx, position_obj, "offsetX", &offset_x_val) || !JS_GetProperty(cx, position_obj, "offsetY", &offset_y_val)) { return std::nullopt; } if (!exactly_one_defined(x_val, offset_x_val) || !exactly_one_defined(y_val, offset_y_val)) { return throw_error("position", "have exactly one of x/offsetX and exactly one of y/offsetY"); } auto absolute_or_offset = [&](JS::HandleValue absolute, JS::HandleValue offset) -> std::optional> { if (!absolute.isUndefined()) { return to_pixels_or_percentage(cx, absolute); } if (offset.isNumber()) { return offset.toNumber(); } return std::nullopt; }; auto x = absolute_or_offset(x_val, offset_x_val); auto y = absolute_or_offset(y_val, offset_y_val); if (!x || !y) { return throw_error("position", "have valid x and y components"); } return ImageOptimizerOptions::Position{*x, *y}; } std::optional ImageOptimizerOptions::to_canvas(JSContext *cx, JS::HandleValue val) { auto throw_error = [&](const char *object, const char *message) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", object, message); return std::nullopt; }; if (!val.isObject()) { return throw_error("canvas", "be an object"); } JS::RootedValue size_val(cx); JS::RootedValue position_val(cx); JS::RootedObject canvas_obj(cx, &val.toObject()); if (!JS_GetProperty(cx, canvas_obj, "size", &size_val) || !JS_GetProperty(cx, canvas_obj, "position", &position_val)) { return std::nullopt; } auto size = to_size(cx, size_val); if (!size) { return std::nullopt; } if (position_val.isUndefined()) { return ImageOptimizerOptions::Canvas{*size, std::nullopt}; } auto position = to_position(cx, position_val); if (!position) { return std::nullopt; } return ImageOptimizerOptions::Canvas{*size, *position}; } std::optional ImageOptimizerOptions::to_crop_spec(JSContext *cx, JS::HandleValue val) { auto throw_error = [&](const char *object, const char *message) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", object, message); return std::nullopt; }; if (!val.isObject()) { return throw_error("crop", "be an object"); } JS::RootedValue size_val(cx); JS::RootedValue position_val(cx); JS::RootedValue mode_val(cx); JS::RootedObject crop_obj(cx, &val.toObject()); if (!JS_GetProperty(cx, crop_obj, "size", &size_val) || !JS_GetProperty(cx, crop_obj, "position", &position_val) || !JS_GetProperty(cx, crop_obj, "mode", &mode_val)) { return std::nullopt; } auto size = to_size(cx, size_val); if (!size) { return std::nullopt; } std::optional position = std::nullopt; if (!position_val.isUndefined()) { position = to_position(cx, position_val); if (!position) { return std::nullopt; } } std::optional mode = std::nullopt; if (!mode_val.isUndefined()) { mode = to_crop_mode(cx, mode_val); if (!mode) { return std::nullopt; } } return ImageOptimizerOptions::CropSpec{*size, position, mode}; } std::optional ImageOptimizerOptions::to_brightness(JSContext *cx, JS::HandleValue val) { auto num = to_number_between_inclusive(val, -100, 100); if (!num) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "brightness", "must be a number between -100 and 100"); return std::nullopt; } return Brightness{*num}; } std::optional ImageOptimizerOptions::to_contrast(JSContext *cx, JS::HandleValue val) { auto num = to_number_between_inclusive(val, -100, 100); if (!num) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "contrast", "must be a number between -100 and 100"); return std::nullopt; } return Contrast{*num}; } std::optional ImageOptimizerOptions::to_quality(JSContext *cx, JS::HandleValue val) { if (!val.isInt32() || val.toInt32() < 0 || val.toInt32() > 100) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "quality", "must be n integer between 0 and 100"); return std::nullopt; } return Quality(val.toInt32()); } std::optional ImageOptimizerOptions::to_saturation(JSContext *cx, JS::HandleValue val) { auto num = to_number_between_inclusive(val, -100, 100); if (!num) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "saturation", "must be a number between -100 and 100"); return std::nullopt; } return Saturation{*num}; } std::optional ImageOptimizerOptions::to_dpr(JSContext *cx, JS::HandleValue val) { auto num = to_number_between_inclusive(val, 1, 10); if (!num) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "dpr", "must be a number between 1 and 10"); return std::nullopt; } return Dpr{*num}; } std::optional ImageOptimizerOptions::to_level(JSContext *cx, JS::HandleValue val) { auto throw_error = [&]() { api::throw_error( cx, api::Errors::TypeError, "imageOptimizerOptions", "level", "must be a string containing 1.0, 1.1, 1.2, 1.3, 2.0, 2.1, 2.2, 3.0, 3.1, 3.2, " "4.0, 4.1, 4.2, 5.0, 5.1, 5.2, 6.0, 6.1, or 6.2"); }; if (!val.isString()) { throw_error(); return std::nullopt; } JS::RootedString js_str(cx, val.toString()); auto str = core::encode(cx, js_str); std::string_view sv = str; if (sv != "1.0" && sv != "1.1" && sv != "1.2" && sv != "1.3" && sv != "2.0" && sv != "2.1" && sv != "2.2" && sv != "3.0" && sv != "3.1" && sv != "3.2" && sv != "4.0" && sv != "4.1" && sv != "4.2" && sv != "5.0" && sv != "5.1" && sv != "5.2" && sv != "6.0" && sv != "6.1" && sv != "6.2") { throw_error(); return std::nullopt; } return Level{std::move(str)}; } std::optional ImageOptimizerOptions::to_frame(JSContext *cx, JS::HandleValue val) { if (!val.isInt32() || val.toInt32() != 1) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "frame", "must be 1"); return std::nullopt; } return Frame{1}; } std::optional ImageOptimizerOptions::to_viewbox(JSContext *cx, JS::HandleValue val) { if (!val.isInt32() || val.toInt32() != 1) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "viewbox", "must be 1"); return std::nullopt; } return Viewbox{1}; } std::optional ImageOptimizerOptions::to_blur(JSContext *cx, JS::HandleValue val) { auto throw_error = [&]() { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "blur", "must be a number between 0.5 and 1000 or a string percentage value"); }; if (val.isNumber()) { auto num = to_number_between_inclusive(val, 0.5, 1000); if (!num) { throw_error(); return std::nullopt; } return Blur{.value = *num, .is_percentage = false}; } if (!val.isString()) { throw_error(); return std::nullopt; } JS::RootedString js_str(cx, val.toString()); auto str = core::encode(cx, js_str); auto percentage = from_percentage(str); if (!percentage) { throw_error(); return std::nullopt; } return Blur{.value = *percentage, .is_percentage = true}; } std::optional ImageOptimizerOptions::to_sharpen(JSContext *cx, JS::HandleValue val) { auto throw_error = [&]() { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "sharpen", "must be an object with keys `amount` (0.0-10.0), `radius` (0.5-1000.0), and " "`threshold` (0-255)"); }; if (!val.isObject()) { throw_error(); return std::nullopt; } JS::RootedValue amount_val(cx); JS::RootedValue radius_val(cx); JS::RootedValue threshold_val(cx); JS::RootedObject opts(cx, &val.toObject()); if (!JS_GetProperty(cx, opts, "amount", &amount_val) || !JS_GetProperty(cx, opts, "radius", &radius_val) || !JS_GetProperty(cx, opts, "threshold", &threshold_val)) { return std::nullopt; } auto amount = to_number_between_inclusive(amount_val, 0, 10); auto radius = to_number_between_inclusive(radius_val, 0.5, 1000); if (!amount || !radius || !threshold_val.isInt32() || threshold_val.toInt32() < 0 || threshold_val.toInt32() > 255) { throw_error(); return std::nullopt; } return Sharpen{*amount, *radius, threshold_val.toInt32()}; } std::optional ImageOptimizerOptions::to_pixels_or_percentage(JSContext *cx, JS::HandleValue val) { if (val.isInt32()) { return PixelsOrPercentage{.pixels = val.toInt32(), .is_percentage = false}; } if (!val.isString()) { return std::nullopt; } JS::RootedString js_str(cx, val.toString()); auto str = core::encode(cx, js_str); auto percentage = from_percentage(str); if (!percentage) { return std::nullopt; } return PixelsOrPercentage{.percentage = *percentage, .is_percentage = true}; } std::optional ImageOptimizerOptions::to_color(JSContext *cx, JS::HandleValue val) { // Hex strings of size 3 or 6 are allowed if (val.isString()) { JS::RootedString str_val(cx, val.toString()); auto str = core::encode(cx, str_val); if ((str.len == 3 || str.len == 6) && (std::all_of(str.begin(), str.end(), [](char c) { return std::isxdigit(c); }))) { return Color{std::move(str)}; } } // Otherwise, it should be an rgb(a) object if (!val.isObject()) { return std::nullopt; } JS::RootedValue r(cx); JS::RootedValue g(cx); JS::RootedValue b(cx); JS::RootedValue a(cx); JS::RootedObject obj(cx, &val.toObject()); if (!JS_GetProperty(cx, obj, "r", &r) || !JS_GetProperty(cx, obj, "g", &g) || !JS_GetProperty(cx, obj, "b", &b) || !JS_GetProperty(cx, obj, "a", &a)) { return std::nullopt; } auto is_valid_color_component = [](const auto &c) { return c.isInt32() && c.toInt32() >= 0 && c.toInt32() < 256; }; auto alpha_valid = a.isUndefined() || (a.isNumber() && a.toNumber() >= 0.0 && a.toNumber() <= 1.0); if (!is_valid_color_component(r) || !is_valid_color_component(g) || !is_valid_color_component(b) || !alpha_valid) { return std::nullopt; } std::string rep; rep += std::to_string(r.toInt32()) + ',' + std::to_string(g.toInt32()) + ',' + std::to_string(b.toInt32()); if (!a.isUndefined()) { rep += ',' + std::to_string(a.toNumber()); } return Color{host_api::HostString(rep)}; } std::optional ImageOptimizerOptions::to_sides(JSContext *cx, JS::HandleValue val) { if (!val.isObject()) { return std::nullopt; } JS::RootedValue top_val(cx); JS::RootedValue bottom_val(cx); JS::RootedValue left_val(cx); JS::RootedValue right_val(cx); JS::RootedObject sides_obj(cx, &val.toObject()); if (!JS_GetProperty(cx, sides_obj, "top", &top_val) || !JS_GetProperty(cx, sides_obj, "bottom", &bottom_val) || !JS_GetProperty(cx, sides_obj, "left", &left_val) || !JS_GetProperty(cx, sides_obj, "right", &right_val)) { return std::nullopt; } if (top_val.isUndefined() || bottom_val.isUndefined() || left_val.isUndefined() || right_val.isUndefined()) { return std::nullopt; } auto top = to_pixels_or_percentage(cx, top_val); auto bottom = to_pixels_or_percentage(cx, bottom_val); auto left = to_pixels_or_percentage(cx, left_val); auto right = to_pixels_or_percentage(cx, right_val); if (!top || !bottom || !left || !right) { return std::nullopt; } return Sides{ .top = *top, .right = *right, .bottom = *bottom, .left = *left, }; } std::optional ImageOptimizerOptions::to_trim_color(JSContext *cx, JS::HandleValue val) { auto throw_error = [&]() { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "trimColor", "must be either a color, or an object with color and threshold elements, " "where threshold is a number between 0 and 1"); return std::nullopt; }; if (val.isString()) { auto color = to_color(cx, val); if (!color) { return throw_error(); } return TrimColor{*std::move(color), std::nullopt}; } if (!val.isObject()) { return throw_error(); } JS::RootedValue color_val(cx); JS::RootedValue threshold_val(cx); JS::RootedObject trim_color_obj(cx, &val.toObject()); if (!JS_GetProperty(cx, trim_color_obj, "color", &color_val) || !JS_GetProperty(cx, trim_color_obj, "threshold", &threshold_val)) { return std::nullopt; } // Could be an rgb(a) object if (color_val.isUndefined()) { auto color = to_color(cx, val); if (!color) { return throw_error(); } return TrimColor{*std::move(color), std::nullopt}; } auto color = to_color(cx, color_val); if (!color) { return throw_error(); } std::optional threshold = std::nullopt; if (threshold_val.isNumber()) { threshold = to_number_between_inclusive(threshold_val, 0, 1); if (!threshold) { return throw_error(); } } return TrimColor{*std::move(color), threshold}; } #define FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(type, lowercase, str) \ std::optional ImageOptimizerOptions::to_##lowercase( \ JSContext *cx, JS::HandleValue val) { \ if (!val.isString()) { \ api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", #type, \ "must be a string"); \ return std::nullopt; \ } \ JS::RootedString str_val(cx, val.toString()); \ using enum type; #define FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(name, str) \ if (core::encode(cx, str_val) == std::string_view(str)) { \ return name; \ } #define FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(type) \ api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", #type, \ "be one of the allowed string values"); \ return std::nullopt; \ } #include "image-optimizer-options.inc" } // namespace fastly::image_optimizer ================================================ FILE: runtime/fastly/builtins/image-optimizer.h ================================================ #ifndef FASTLY_IMAGE_OPTIMIZER_H #define FASTLY_IMAGE_OPTIMIZER_H #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "encode.h" #include "extension-api.h" #include #include #define HANDLE_IMAGE_OPTIMIZER_ERROR(cx, err) \ ::host_api::handle_image_optimizer_error(cx, err, __LINE__, __func__) namespace fastly::image_optimizer { class EnumOption { public: enum Slots { Count }; static const JSFunctionSpec static_methods[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; }; #define FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(type, lowercase, str) \ class type : public EnumOption, public builtins::BuiltinNoConstructor { \ public: \ static const JSPropertySpec static_properties[]; \ static constexpr const char *class_name = #type; \ }; #include "image-optimizer-options.inc" class ImageOptimizerOptions { public: fastly_image_optimizer_transform_config to_config(); static std::unique_ptr create(JSContext *cx, JS::HandleValue opts_val); static bool optionsToQueryString(JSContext *cx, unsigned argc, JS::Value *vp); std::string to_string() const; #define FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(type, lowercase, str) enum class type { #define FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(name, str) name, #define FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(type) \ } \ ; #include "image-optimizer-options.inc" #define FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(type, lowercase, str) \ static std::optional to_##lowercase(JSContext *cx, JS::HandleValue val); #include "image-optimizer-options.inc" struct Blur { double value; bool is_percentage; }; static std::optional to_blur(JSContext *cx, JS::HandleValue val); struct Brightness { double value; }; static std::optional to_brightness(JSContext *cx, JS::HandleValue val); struct PixelsOrPercentage { union { int pixels; double percentage; }; bool is_percentage; }; static std::optional to_pixels_or_percentage(JSContext *cx, JS::HandleValue val); struct Size { struct Absolute { PixelsOrPercentage width; PixelsOrPercentage height; }; struct Ratio { double width_ratio; double height_ratio; }; std::variant value; }; static std::optional to_size(JSContext *cx, JS::HandleValue val); struct Position { // Absolute or offset std::variant x; std::variant y; }; static std::optional to_position(JSContext *cx, JS::HandleValue val); struct Canvas { Size size; std::optional position; }; static std::optional to_canvas(JSContext *cx, JS::HandleValue val); struct Color { host_api::HostString val; }; static std::optional to_color(JSContext *cx, JS::HandleValue val); struct Contrast { double value; }; static std::optional to_contrast(JSContext *cx, JS::HandleValue val); // Deduplicates between Crop and Precrop struct CropSpec { Size size; std::optional position; std::optional mode; }; static std::optional to_crop_spec(JSContext *cx, JS::HandleValue val); struct Crop { CropSpec value; }; static std::optional to_crop(JSContext *cx, JS::HandleValue val) { auto value = to_crop_spec(cx, val); if (!value) return std::nullopt; return Crop{*value}; } struct Dpr { double value; }; static std::optional to_dpr(JSContext *cx, JS::HandleValue val); struct Frame { int32_t value; }; static std::optional to_frame(JSContext *cx, JS::HandleValue val); struct Height { PixelsOrPercentage value; }; static std::optional to_height(JSContext *cx, JS::HandleValue val) { auto ret = to_pixels_or_percentage(cx, val); if (!ret) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "height", "must be an integer pixel value or a string percentage value"); return std::nullopt; } return Height{*ret}; } struct Level { host_api::HostString value; }; static std::optional to_level(JSContext *cx, JS::HandleValue val); struct Sides { PixelsOrPercentage top, right, bottom, left; }; static std::optional to_sides(JSContext *cx, JS::HandleValue val); struct Pad { Sides value; }; static std::optional to_pad(JSContext *cx, JS::HandleValue val) { auto sides = to_sides(cx, val); if (!sides) { api::throw_error( cx, api::Errors::TypeError, "imageOptimizerOptions", "trim", "must be an object with top, right, bottom, and left elements, each being an " "integer or a string percentage value"); return std::nullopt; } return Pad{*sides}; } struct Precrop { CropSpec value; }; static std::optional to_precrop(JSContext *cx, JS::HandleValue val) { auto value = to_crop_spec(cx, val); if (!value) return std::nullopt; return Precrop{*value}; } struct Quality { uint32_t value; }; static std::optional to_quality(JSContext *cx, JS::HandleValue val); struct Saturation { double value; }; static std::optional to_saturation(JSContext *cx, JS::HandleValue val); struct Sharpen { double amount; double radius; int32_t threshold; }; static std::optional to_sharpen(JSContext *cx, JS::HandleValue val); struct Trim { Sides value; }; static std::optional to_trim(JSContext *cx, JS::HandleValue val) { auto sides = to_sides(cx, val); if (!sides) { api::throw_error( cx, api::Errors::TypeError, "imageOptimizerOptions", "trim", "must be an object with top, right, bottom, and left elements, each being an " "integer or a string percentage value"); return std::nullopt; } return Trim{*sides}; } struct TrimColor { Color color; std::optional threshold; }; static std::optional to_trim_color(JSContext *cx, JS::HandleValue val); struct Viewbox { int32_t value; }; static std::optional to_viewbox(JSContext *cx, JS::HandleValue val); struct Width { PixelsOrPercentage value; }; static std::optional to_width(JSContext *cx, JS::HandleValue val) { auto ret = to_pixels_or_percentage(cx, val); if (!ret) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "width", "must be an integer pixel value or a string percentage value"); return std::nullopt; } return Width{*ret}; } struct BGColor { Color color; }; static std::optional to_bg_color(JSContext *cx, JS::HandleValue val) { auto color = to_color(cx, val); if (!color) { api::throw_error(cx, api::Errors::TypeError, "imageOptimizerOptions", "bgColor", "must be a 3/6 character hex string or RGB(A) object"); return std::nullopt; } return BGColor{std::move(*color)}; } private: ImageOptimizerOptions( Region region, std::optional auto_val, std::optional bg_color, std::optional blur, std::optional brightness, std::optional bw, std::optional canvas, std::optional contrast, std::optional crop, std::optional disable, std::optional dpr, std::optional enable, std::optional fit, std::optional format, std::optional frame, std::optional height, std::optional level, std::optional metadata, std::optional optimize, std::optional orient, std::optional pad, std::optional precrop, std::optional profile, std::optional quality, std::optional resize_filter, std::optional saturation, std::optional sharpen, std::optional trim, std::optional trim_color, std::optional viewbox, std::optional width) : region_(region), auto_(auto_val), bg_color_(std::move(bg_color)), blur_(blur), brightness_(brightness), bw_(bw), canvas_(canvas), contrast_(contrast), crop_(crop), disable_(disable), dpr_(dpr), enable_(enable), fit_(fit), format_(format), frame_(frame), height_(height), level_(std::move(level)), metadata_(metadata), optimize_(optimize), orient_(orient), pad_(pad), precrop_(precrop), profile_(profile), quality_(quality), resizeFilter_(resize_filter), saturation_(saturation), sharpen_(sharpen), trim_(trim), trim_color_(std::move(trim_color)), viewbox_(viewbox), width_(width) {} Region region_; std::optional auto_; std::optional bg_color_; std::optional blur_; std::optional brightness_; std::optional bw_; std::optional canvas_; std::optional contrast_; std::optional crop_; std::optional disable_; std::optional dpr_; std::optional enable_; std::optional fit_; std::optional format_; std::optional frame_; std::optional height_; std::optional level_; std::optional metadata_; std::optional optimize_; std::optional orient_; std::optional pad_; std::optional precrop_; std::optional profile_; std::optional quality_; std::optional resizeFilter_; std::optional saturation_; std::optional sharpen_; std::optional trim_; std::optional trim_color_; std::optional viewbox_; std::optional width_; }; inline std::string to_string(const ImageOptimizerOptions &opts) { return opts.to_string(); } #define FASTLY_BEGIN_IMAGE_OPTIMIZER_OPTION_TYPE(type, lowercase, str) \ inline std::string to_string(ImageOptimizerOptions::type val) { \ using enum ImageOptimizerOptions::type; \ std::string prefix = str; \ switch (val) { #define FASTLY_DEFINE_IMAGE_OPTIMIZER_OPTION(name, str) \ case name: \ return prefix + '=' + str; #define FASTLY_END_IMAGE_OPTIMIZER_OPTION_TYPE(type) \ } \ } #include "image-optimizer-options.inc" inline std::string to_string(const ImageOptimizerOptions::Color &c) { return std::string{std::string_view(c.val)}; } inline std::string to_string(const ImageOptimizerOptions::BGColor &bg) { return "bg-color=" + to_string(bg.color); } inline std::string to_string(const ImageOptimizerOptions::Blur &blur) { auto ret = "blur=" + std::to_string(blur.value); if (blur.is_percentage) { ret += 'p'; } return ret; } inline std::string to_string(const ImageOptimizerOptions::Brightness &brightness) { return "brightness=" + std::to_string(brightness.value); } inline std::string to_string(const ImageOptimizerOptions::PixelsOrPercentage &value) { if (value.is_percentage) { return std::to_string(value.percentage) + 'p'; } return std::to_string(value.pixels); } inline std::string to_string(const ImageOptimizerOptions::Size &size) { if (auto abs = std::get_if(&size.value)) { return to_string(abs->width) + ',' + to_string(abs->height); } auto ratio = std::get(size.value); return std::to_string(ratio.width_ratio) + ':' + std::to_string(ratio.height_ratio); } inline std::string to_string(const ImageOptimizerOptions::Position &position) { std::string ret; if (auto value = std::get_if(&position.x)) { ret += 'x' + to_string(*value); } else { auto dbl = std::get(position.x); ret += "offset-x" + std::to_string(dbl); } ret += ','; if (auto value = std::get_if(&position.y)) { ret += 'y' + to_string(*value); } else { auto dbl = std::get(position.y); ret += "offset-y" + std::to_string(dbl); } return ret; } inline std::string to_string(const ImageOptimizerOptions::Canvas &canvas) { std::string ret = "canvas=" + to_string(canvas.size); if (canvas.position) { ret += ',' + to_string(*canvas.position); } return ret; } inline std::string to_string(const ImageOptimizerOptions::Contrast &contrast) { return "contrast=" + std::to_string(contrast.value); } inline std::string to_string(const ImageOptimizerOptions::CropSpec &crop) { std::string ret = to_string(crop.size); if (crop.position) { ret += ',' + to_string(*crop.position); } if (crop.mode) { ret += ','; switch (*crop.mode) { case ImageOptimizerOptions::CropMode::Safe: ret += "safe"; break; case ImageOptimizerOptions::CropMode::Smart: ret += "smart"; break; } } return ret; } inline std::string to_string(const ImageOptimizerOptions::Crop &crop) { return "crop=" + to_string(crop.value); } inline std::string to_string(const ImageOptimizerOptions::Dpr &dpr) { return "dpr=" + std::to_string(dpr.value); } inline std::string to_string(const ImageOptimizerOptions::Frame &frame) { return "frame=" + std::to_string(frame.value); } inline std::string to_string(const ImageOptimizerOptions::Height &height) { return "height=" + to_string(height.value); } inline std::string to_string(const ImageOptimizerOptions::Level &level) { return "level=" + std::string(std::string_view(level.value)); } inline std::string to_string(const ImageOptimizerOptions::Sides &sides) { return to_string(sides.top) + ',' + to_string(sides.right) + ',' + to_string(sides.bottom) + ',' + to_string(sides.left); } inline std::string to_string(const ImageOptimizerOptions::Pad &pad) { return "pad=" + to_string(pad.value); } inline std::string to_string(const ImageOptimizerOptions::Precrop &precrop) { return "precrop=" + to_string(precrop.value); } inline std::string to_string(const ImageOptimizerOptions::Quality &quality) { return "quality=" + std::to_string(quality.value); } inline std::string to_string(const ImageOptimizerOptions::Saturation &saturation) { return "saturation=" + std::to_string(saturation.value); } inline std::string to_string(const ImageOptimizerOptions::Trim &trim) { return "trim=" + to_string(trim.value); } inline std::string to_string(const ImageOptimizerOptions::TrimColor &trim_color) { std::string ret = "trim-color=" + to_string(trim_color.color); if (trim_color.threshold) { ret += ",t" + std::to_string(*trim_color.threshold); } return ret; } inline std::string to_string(const ImageOptimizerOptions::Sharpen &sharpen) { return "sharpen=a" + std::to_string(sharpen.amount) + ",r" + std::to_string(sharpen.radius) + ",t" + std::to_string(sharpen.threshold); } inline std::string to_string(const ImageOptimizerOptions::Viewbox &viewbox) { return "viewbox=" + std::to_string(viewbox.value); } inline std::string to_string(const ImageOptimizerOptions::Width &width) { return "width=" + to_string(width.value); } } // namespace fastly::image_optimizer #endif ================================================ FILE: runtime/fastly/builtins/kv-store.cpp ================================================ #include #include #include #include #include // TODO: remove these once the warnings are fixed #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" #include "js/experimental/TypedData.h" #pragma clang diagnostic pop #include "js/ArrayBuffer.h" #include "js/Stream.h" #include "../../../StarlingMonkey/builtins/web/base64.h" #include "../../../StarlingMonkey/builtins/web/streams/native-stream-source.h" #include "../../../StarlingMonkey/builtins/web/url.h" #include "../common/validations.h" #include "../host-api/host_api_fastly.h" #include "./fastly.h" #include "builtin.h" #include "decode.h" #include "encode.h" #include "js/JSON.h" #include "kv-store.h" using builtins::web::streams::NativeStreamSource; using fastly::FastlyGetErrorMessage; using fastly::common::parse_and_validate_timeout; using fastly::common::validate_bytes; using fastly::fastly::convertBodyInit; using fastly::fetch::RequestOrResponse; namespace fastly::kv_store { namespace { api::Engine *ENGINE; std::string_view bad_chars{"#;?^|\n\r"}; std::optional find_invalid_character_for_kv_store_key(const char *str) { std::optional res; std::string_view view{str, strlen(str)}; auto it = std::find_if(view.begin(), view.end(), [](auto c) { return bad_chars.find(c) != std::string_view::npos; }); if (it != view.end()) { res = *it; } return res; } } // namespace template bool KVStoreEntry::bodyAll(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) return RequestOrResponse::bodyAll(cx, args, self); } bool KVStoreEntry::body_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) if (!JS::GetReservedSlot(self, static_cast(Slots::HasBody)).isBoolean()) { JS::SetReservedSlot(self, static_cast(Slots::HasBody), JS::BooleanValue(false)); } return RequestOrResponse::body_get(cx, args, self, true); } bool KVStoreEntry::bodyUsed_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) if (!JS::GetReservedSlot(self, static_cast(Slots::BodyUsed)).isBoolean()) { JS::SetReservedSlot(self, static_cast(Slots::BodyUsed), JS::BooleanValue(false)); } args.rval().setBoolean(RequestOrResponse::body_used(self)); return true; } bool KVStoreEntry::metadata(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) args.rval().set(JS::GetReservedSlot(self, static_cast(Slots::Metadata))); return true; } bool KVStoreEntry::metadata_text(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedValue metadata(cx, JS::GetReservedSlot(self, static_cast(Slots::Metadata))); if (metadata.isNull()) { args.rval().setNull(); return true; } uint8_t *data; size_t len; bool is_shared; if (!JS_GetObjectAsArrayBufferView(&metadata.toObject(), &len, &is_shared, &data)) { MOZ_ASSERT(false); } MOZ_ASSERT(!is_shared); JS::RootedString metadata_str( cx, core::decode(cx, std::string_view(reinterpret_cast(data), len))); if (!metadata_str) { return false; } args.rval().setString(metadata_str); return true; } const JSFunctionSpec KVStoreEntry::static_methods[] = { JS_FS_END, }; const JSPropertySpec KVStoreEntry::static_properties[] = { JS_PS_END, }; const JSFunctionSpec KVStoreEntry::methods[] = { JS_FN("arrayBuffer", bodyAll, 0, JSPROP_ENUMERATE), JS_FN("json", bodyAll, 0, JSPROP_ENUMERATE), JS_FN("text", bodyAll, 0, JSPROP_ENUMERATE), JS_FN("metadata", metadata, 0, JSPROP_ENUMERATE), JS_FN("metadataText", metadata_text, 0, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec KVStoreEntry::properties[] = { JS_PSG("body", body_get, JSPROP_ENUMERATE), JS_PSG("bodyUsed", bodyUsed_get, JSPROP_ENUMERATE), JS_PS_END, }; bool KVStoreEntry::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { JS_ReportErrorUTF8(cx, "KVStoreEntry can't be instantiated directly"); return false; } JSObject *KVStoreEntry::create(JSContext *cx, host_api::HttpBody body_handle, host_api::HostBytes metadata) { JS::RootedObject kvStoreEntry(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!kvStoreEntry) return nullptr; JS::SetReservedSlot(kvStoreEntry, static_cast(Slots::Body), JS::Int32Value(body_handle.handle)); JS::SetReservedSlot(kvStoreEntry, static_cast(Slots::BodyStream), JS::NullValue()); JS::SetReservedSlot(kvStoreEntry, static_cast(Slots::HasBody), JS::BooleanValue(true)); JS::SetReservedSlot(kvStoreEntry, static_cast(Slots::BodyUsed), JS::FalseValue()); if (metadata) { JS::RootedObject buffer( cx, JS::NewArrayBufferWithContents(cx, metadata.len, metadata.ptr.get(), JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory)); if (!buffer) { JS_ReportOutOfMemory(cx); return nullptr; } // `array_buffer` now owns `metadata` static_cast(metadata.ptr.release()); JS::RootedObject uint8_array(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 0, metadata.len)); JS::SetReservedSlot(kvStoreEntry, static_cast(Slots::Metadata), JS::ObjectValue(*uint8_array)); } else { JS::SetReservedSlot(kvStoreEntry, static_cast(Slots::Metadata), JS::NullValue()); } return kvStoreEntry; } namespace { host_api::KVStore kv_store(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, static_cast(KVStore::Slots::KVStore)); return host_api::KVStore(val.toInt32()); } bool parse_and_validate_key(JSContext *cx, const char *key, size_t len) { // If the converted string has a length of 0 then we throw an Error // because KVStore Keys have to be at-least 1 character. if (len == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_KEY_EMPTY); return false; } // If the converted string has a length of more than 1024 then we throw an Error // because KVStore Keys have to be less than 1025 characters. if (len > 1024) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_KEY_TOO_LONG); return false; } auto key_chars = key; auto res = find_invalid_character_for_kv_store_key(key_chars); if (res.has_value()) { std::string character; switch (res.value()) { case '\n': character = "newline"; break; case '\r': character = "carriage return"; break; case '^': character = '^'; break; case '|': character = '|'; break; case ';': character = ';'; break; case '?': character = '?'; break; case '#': character = '#'; break; } JS_ReportErrorNumberUTF8(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_KEY_INVALID_CHARACTER, character.c_str()); return false; } auto acme_challenge = ".well-known/acme-challenge/"; if (strncmp(key_chars, acme_challenge, strlen(acme_challenge)) == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_KEY_ACME); return false; } if (strcmp(key_chars, ".") == 0 || strcmp(key_chars, "..") == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_KEY_RELATIVE); return false; } return true; } bool process_pending_kv_store_list(JSContext *cx, host_api::KVStorePendingList::Handle handle, JS::HandleObject context, JS::HandleValue promise) { host_api::KVStorePendingList pending_list(handle); JS::RootedObject promise_obj(cx, &promise.toObject()); auto res = pending_list.wait(); if (auto *err = res.to_err()) { HANDLE_KV_ERROR(cx, *err, JSMSG_KV_STORE_LIST_ERROR); return RejectPromiseWithPendingError(cx, promise_obj); } auto buf_res = res.unwrap().read_all(); if (auto *err = buf_res.to_err()) { HANDLE_ERROR(cx, *err); return RejectPromiseWithPendingError(cx, promise_obj); } JS::RootedString str( cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(reinterpret_cast(buf_res.unwrap().ptr.get()), buf_res.unwrap().len))); if (!str) { return RejectPromiseWithPendingError(cx, promise_obj); } JS::RootedValue str_val(cx, JS::StringValue(str)); JS::RootedValue json(cx); if (!JS_ParseJSON(cx, str, &json)) { return RejectPromiseWithPendingError(cx, promise_obj); } if (!json.isObject()) { JS_ReportErrorLatin1(cx, "Bad data."); return RejectPromiseWithPendingError(cx, promise_obj); } JS::RootedValue list(cx); JS::RootedObject json_obj(cx, &json.toObject()); if (!JS_GetProperty(cx, json_obj, "data", &list)) { return RejectPromiseWithPendingError(cx, promise_obj); } JS::RootedValue meta(cx); if (!JS_GetProperty(cx, json_obj, "meta", &meta)) { return RejectPromiseWithPendingError(cx, promise_obj); } JS::RootedObject meta_obj(cx, &meta.toObject()); JS::RootedValue next_cursor(cx); if (!JS_GetProperty(cx, meta_obj, "next_cursor", &next_cursor)) { return RejectPromiseWithPendingError(cx, promise_obj); } JS::RootedObject list_out(cx, JS_NewPlainObject(cx)); JS_SetProperty(cx, list_out, "list", list); JS_SetProperty(cx, list_out, "cursor", next_cursor); JS::RootedValue list_out_val(cx, JS::ObjectValue(*list_out)); return JS::ResolvePromise(cx, promise_obj, list_out_val); } bool process_pending_kv_store_delete(JSContext *cx, host_api::KVStorePendingDelete::Handle handle, JS::HandleObject context, JS::HandleValue promise) { host_api::KVStorePendingDelete pending_delete(handle); JS::RootedObject promise_obj(cx, &promise.toObject()); auto res = pending_delete.wait(); if (auto *err = res.to_err()) { HANDLE_KV_ERROR(cx, *err, JSMSG_KV_STORE_DELETE_ERROR); return RejectPromiseWithPendingError(cx, promise_obj); } JS::ResolvePromise(cx, promise_obj, JS::UndefinedHandleValue); return true; } bool process_pending_kv_store_lookup(JSContext *cx, host_api::KVStorePendingLookup::Handle handle, JS::HandleObject context, JS::HandleValue promise) { host_api::KVStorePendingLookup pending_lookup(handle); JS::RootedObject promise_obj(cx, &promise.toObject()); auto res = pending_lookup.wait(); if (auto *err = res.to_err()) { HANDLE_KV_ERROR(cx, *err, JSMSG_KV_STORE_LOOKUP_ERROR); return RejectPromiseWithPendingError(cx, promise_obj); } // When no entry is found, we are going to resolve the Promise with `null`. if (!res.unwrap().has_value()) { JS::RootedValue result(cx); result.setNull(); JS::ResolvePromise(cx, promise_obj, result); } else { host_api::HttpBody body = std::get<0>(res.unwrap().value()); host_api::HostBytes metadata = std::move(std::get<1>(res.unwrap().value())); // uint32_t gen = std::get<2>(res.unwrap()); JS::RootedObject entry(cx, KVStoreEntry::create(cx, body, std::move(metadata))); if (!entry) { return RejectPromiseWithPendingError(cx, promise_obj); } JS::RootedValue result(cx); result.setObject(*entry); JS::ResolvePromise(cx, promise_obj, result); } return true; } } // namespace bool KVStore::delete_(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER_WITH_NAME(1, "delete"); JS::RootedObject result_promise(cx, JS::NewPromiseObject(cx, nullptr)); if (!result_promise) { return ReturnPromiseRejectedWithPendingError(cx, args); } JS::RootedValue key(cx, args.get(0)); // Convert the key argument into a String following https://tc39.es/ecma262/#sec-tostring auto key_chars = core::encode(cx, key); if (!key_chars) { return ReturnPromiseRejectedWithPendingError(cx, args); } if (!parse_and_validate_key(cx, key_chars.begin(), key_chars.len)) { return ReturnPromiseRejectedWithPendingError(cx, args); } auto res = kv_store(self).delete_(key_chars); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return ReturnPromiseRejectedWithPendingError(cx, args); } auto handle = res.unwrap(); JS::RootedValue result_promise_val(cx, JS::ObjectValue(*result_promise)); ENGINE->queue_async_task( new FastlyAsyncTask(handle, self, result_promise_val, process_pending_kv_store_delete)); args.rval().setObject(*result_promise); return true; } bool KVStore::get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::RootedObject result_promise(cx, JS::NewPromiseObject(cx, nullptr)); if (!result_promise) { return ReturnPromiseRejectedWithPendingError(cx, args); } JS::RootedValue key(cx, args.get(0)); // Convert the key argument into a String following https://tc39.es/ecma262/#sec-tostring auto key_chars = core::encode(cx, key); if (!key_chars) { return ReturnPromiseRejectedWithPendingError(cx, args); } if (!parse_and_validate_key(cx, key_chars.begin(), key_chars.len)) { return ReturnPromiseRejectedWithPendingError(cx, args); } auto res = kv_store(self).lookup(key_chars); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return ReturnPromiseRejectedWithPendingError(cx, args); } auto handle = res.unwrap(); JS::RootedValue result_promise_val(cx, JS::ObjectValue(*result_promise)); auto task = new FastlyAsyncTask(handle, self, result_promise_val, process_pending_kv_store_lookup); ENGINE->queue_async_task(task); args.rval().setObject(*result_promise); return true; } bool KVStore::put(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(2) JS::RootedObject result_promise(cx, JS::NewPromiseObject(cx, nullptr)); if (!result_promise) { return false; } JS::RootedValue key(cx, args.get(0)); // Convert the key argument into a String following https://tc39.es/ecma262/#sec-tostring auto key_chars = core::encode(cx, key); if (!key_chars) { return false; } if (!parse_and_validate_key(cx, key_chars.begin(), key_chars.len)) { return false; } JS::HandleValue body_val = args.get(1); JS::RootedValue metadata_val(cx); // used only if we have to do a custom text encoding host_api::HostString metadata_str; std::optional ttl = std::nullopt; std::optional if_gen = std::nullopt; std::optional> metadata = std::nullopt; std::optional mode = std::nullopt; if (args.get(2).isObject()) { JS::RootedObject opts_val(cx, &args.get(2).toObject()); JS::RootedValue ttl_val(cx); if (!JS_GetProperty(cx, opts_val, "ttl", &ttl_val)) { return false; } if (!ttl_val.isUndefined()) { auto parsed = parse_and_validate_timeout(cx, ttl_val, "KVStore.put", "ttl", 0x100000000); if (!parsed) { return false; } ttl = parsed; } JS::RootedValue gen_val(cx); if (!JS_GetProperty(cx, opts_val, "gen", &gen_val)) { return false; } if (!gen_val.isNullOrUndefined()) { if (gen_val.isNumber()) { if (gen_val.toNumber()) { if_gen.emplace(gen_val.toNumber()); } } if (!if_gen.has_value()) { api::throw_error(cx, api::Errors::TypeError, "KVStore.insert", "gen", "be an integer"); return ReturnPromiseRejectedWithPendingError(cx, args); } } if (!JS_GetProperty(cx, opts_val, "metadata", &metadata_val)) { return false; } // metadata is actually read just before the hostcall JS::RootedValue mode_val(cx); if (!JS_GetProperty(cx, opts_val, "mode", &mode_val)) { return false; } if (!mode_val.isUndefined()) { auto mode_name = JS::RootedString(cx, JS::ToString(cx, mode_val)); if (!mode_name) { return false; } bool match = false; if (!JS_StringEqualsLiteral(cx, mode_name, "add", &match)) { return false; } if (match) { mode = host_api::KVStore::InsertMode::add; } else { if (!JS_StringEqualsLiteral(cx, mode_name, "append", &match)) { return false; } if (match) { mode = host_api::KVStore::InsertMode::append; } else { if (!JS_StringEqualsLiteral(cx, mode_name, "overwrite", &match)) { return false; } if (match) { mode = host_api::KVStore::InsertMode::overwrite; } else { if (!JS_StringEqualsLiteral(cx, mode_name, "prepend", &match)) { return false; } if (match) { mode = host_api::KVStore::InsertMode::prepend; } } } } } } // We currently support five types of body inputs: // - byte sequence // - buffer source // - USV strings // - URLSearchParams // - ReadableStream // After the other other options are checked explicitly, all other inputs are // encoded to a UTF8 string to be treated as a USV string. // TODO: Support the other possible inputs to Body. JS::RootedObject body_obj(cx, body_val.isObject() ? &body_val.toObject() : nullptr); if (body_obj && JS::IsReadableStream(body_obj)) { if (RequestOrResponse::body_unusable(cx, body_obj)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_READABLE_STREAM_LOCKED_OR_DISTRUBED); return ReturnPromiseRejectedWithPendingError(cx, args); } // If the body stream is backed by a Fastly Compute body handle, we can directly pipe // that handle into the kv store. if (NativeStreamSource::stream_is_body(cx, body_obj)) { JS::RootedObject stream_source(cx, NativeStreamSource::get_stream_source(cx, body_obj)); JS::RootedObject source_owner(cx, NativeStreamSource::owner(stream_source)); auto body = RequestOrResponse::body_handle(source_owner); std::optional no_gc; // metadata object is read last because no JS can run after getting byte reference if (!metadata_val.isUndefined()) { if (metadata_val.isString()) { metadata_str = core::encode(cx, metadata_val); metadata = std::make_tuple(reinterpret_cast(metadata_str.ptr.get()), metadata_str.len); } else { auto metadata_buf = validate_bytes(cx, metadata_val, "KVStore.put metadata"); if (!metadata_buf) { return ReturnPromiseRejectedWithPendingError(cx, args); } auto &[data, len, noGC] = *metadata_buf; metadata = std::make_tuple(data, len); if (noGC) { no_gc.emplace(); } } } auto res = kv_store(self).insert(key_chars, body, mode, std::nullopt, metadata, ttl); if (no_gc) no_gc->reset(); // allow GC after hostcall if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return ReturnPromiseRejectedWithPendingError(cx, args); } // The insert was successful so we return a Promise which resolves to undefined JS::RootedValue rval(cx); rval.setUndefined(); JS::ResolvePromise(cx, result_promise, rval); args.rval().setObject(*result_promise); return true; } else { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_PUT_CONTENT_STREAM); return ReturnPromiseRejectedWithPendingError(cx, args); } } else { auto result = convertBodyInit(cx, body_val); if (result.isErr()) { return false; } size_t length; JS::UniqueChars data; std::tie(data, length) = result.unwrap(); // 30MB in bytes is the max size allowed for KVStore. if (length > 30 * 1024 * 1024) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_PUT_OVER_30_MB); return ReturnPromiseRejectedWithPendingError(cx, args); } auto make_res = host_api::HttpBody::make(); if (auto *err = make_res.to_err()) { HANDLE_ERROR(cx, *err); return ReturnPromiseRejectedWithPendingError(cx, args); } auto body = make_res.unwrap(); if (!body.valid()) { return ReturnPromiseRejectedWithPendingError(cx, args); } auto write_res = body.write_all_back(reinterpret_cast(data.get()), length); if (auto *err = write_res.to_err()) { HANDLE_ERROR(cx, *err); return ReturnPromiseRejectedWithPendingError(cx, args); } std::optional no_gc; // metadata object is read last because no JS can run after getting byte reference if (!metadata_val.isUndefined()) { if (metadata_val.isString()) { metadata_str = core::encode(cx, metadata_val); metadata = std::make_tuple(reinterpret_cast(metadata_str.ptr.get()), metadata_str.len); } else { auto metadata_buf = validate_bytes(cx, metadata_val, "KVStore.put metadata"); if (!metadata_buf) { return ReturnPromiseRejectedWithPendingError(cx, args); } auto &[data, len, noGC] = *metadata_buf; metadata = std::make_tuple(data, len); if (noGC) { no_gc.emplace(); } } } auto insert_res = kv_store(self).insert(key_chars, body, mode, if_gen, metadata, ttl); if (no_gc) no_gc->reset(); // allow GC after hostcall if (auto *err = insert_res.to_err()) { // Ensure that we throw an exception for all unexpected host errors. HANDLE_ERROR(cx, *err); return RejectPromiseWithPendingError(cx, result_promise); } host_api::KVStorePendingInsert pending_insert(insert_res.unwrap()); auto res = pending_insert.wait(); if (auto *err = res.to_err()) { HANDLE_KV_ERROR(cx, *err, JSMSG_KV_STORE_INSERT_ERROR); return RejectPromiseWithPendingError(cx, result_promise); } // The insert was successful so we return a Promise which resolves to undefined JS::RootedValue rval(cx); rval.setUndefined(); JS::ResolvePromise(cx, result_promise, rval); args.rval().setObject(*result_promise); return true; } return false; } bool KVStore::list(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) if (!args.get(0).isObject()) { api::throw_error(cx, api::Errors::TypeError, "KVStore.list", "options", "be an object"); return false; } JS::RootedObject options(cx, &args.get(0).toObject()); std::optional cursor = std::nullopt; host_api::HostString cursor_str; JS::RootedValue cursor_val(cx); if (!JS_GetProperty(cx, options, "cursor", &cursor_val)) { return false; } if (!cursor_val.isNullOrUndefined()) { if (!cursor_val.isString()) { api::throw_error(cx, api::Errors::TypeError, "KVStore.list", "cursor", "be a string"); return false; } cursor_str = core::encode(cx, cursor_val); if (!cursor_str) { return false; } cursor = cursor_str; } JS::RootedValue limit_val(cx); if (!JS_GetProperty(cx, options, "limit", &limit_val)) { return false; } std::optional limit = std::nullopt; if (!limit_val.isNullOrUndefined()) { if (limit_val.isNumber()) { if (limit_val.isDouble()) { double limit_double = limit_val.toDouble(); if (std::floor(limit_double) == limit_double) { limit.emplace(limit_double); } } else if (limit_val.isInt32()) { limit.emplace(limit_val.toInt32()); } } if (!limit.has_value()) { api::throw_error(cx, api::Errors::TypeError, "KVStore.list", "limit", "be an integer"); return false; } } std::optional prefix = std::nullopt; host_api::HostString prefix_str; JS::RootedValue prefix_val(cx); if (!JS_GetProperty(cx, options, "prefix", &prefix_val)) { return false; } if (!prefix_val.isNullOrUndefined()) { if (!prefix_val.isString()) { api::throw_error(cx, api::Errors::TypeError, "KVStore.list", "prefix", "be a string"); return false; } prefix_str = core::encode(cx, prefix_val); if (!prefix_str) { return false; } prefix = prefix_str; } bool no_sync = false; JS::RootedValue no_sync_val(cx); if (!JS_GetProperty(cx, options, "noSync", &no_sync_val)) { return false; } if (!no_sync_val.isNullOrUndefined()) { if (!no_sync_val.isBoolean()) { api::throw_error(cx, api::Errors::TypeError, "KVStore.list", "noSync", "be a boolean"); return false; } no_sync = no_sync_val.toBoolean(); } auto res = kv_store(self).list(cursor, limit, prefix, no_sync); if (auto *err = res.to_err()) { // Ensure that we throw an exception for all unexpected host errors. HANDLE_ERROR(cx, *err); return false; } auto handle = res.unwrap(); JS::RootedObject result_promise(cx, JS::NewPromiseObject(cx, nullptr)); if (!result_promise) { return false; } JS::RootedValue result_promise_val(cx, JS::ObjectValue(*result_promise)); auto task = new FastlyAsyncTask(handle, self, result_promise_val, process_pending_kv_store_list); ENGINE->queue_async_task(task); args.rval().setObject(*result_promise); return true; } const JSFunctionSpec KVStore::static_methods[] = { JS_FS_END, }; const JSPropertySpec KVStore::static_properties[] = { JS_PS_END, }; const JSFunctionSpec KVStore::methods[] = { JS_FN("delete", delete_, 1, JSPROP_ENUMERATE), JS_FN("get", get, 1, JSPROP_ENUMERATE), JS_FN("put", put, 1, JSPROP_ENUMERATE), JS_FN("list", list, 1, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec KVStore::properties[] = { JS_PS_END, }; bool KVStore::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The KVStore builtin"); CTOR_HEADER("KVStore", 1); JS::HandleValue name_arg = args.get(0); // Convert into a String following https://tc39.es/ecma262/#sec-tostring auto name = core::encode(cx, name_arg); if (!name) { return false; } // If the converted string has a length of 0 then we throw an Error // because KVStore names have to be at-least 1 character. if (name.len == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_NAME_EMPTY); return false; } // If the converted string has a length of more than 255 then we throw an Error // because KVStore names have to be less than 255 characters. if (name.len > 255) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_NAME_TOO_LONG); return false; } if (std::any_of(name.begin(), name.end(), [](auto character) { return std::iscntrl(static_cast(character)) != 0; })) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_NAME_NO_CONTROL_CHARACTERS); return false; } auto res = host_api::KVStore::open(name); if (auto *err = res.to_err()) { if (host_api::error_is_invalid_argument(*err)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_KV_STORE_DOES_NOT_EXIST, name.begin()); return false; } else { HANDLE_ERROR(cx, *err); return false; } } JS::RootedObject kv_store(cx, JS_NewObjectForConstructor(cx, &class_, args)); if (!kv_store) { return false; } JS::SetReservedSlot(kv_store, static_cast(Slots::KVStore), JS::Int32Value(res.unwrap().handle)); args.rval().setObject(*kv_store); return true; } bool install(api::Engine *engine) { ENGINE = engine; if (!KVStore::init_class_impl(engine->cx(), engine->global())) { return false; } if (!KVStoreEntry::init_class_impl(engine->cx(), engine->global())) { return false; } RootedValue kv_store_val(engine->cx()); if (!JS_GetProperty(engine->cx(), engine->global(), "KVStore", &kv_store_val)) { return false; } RootedObject kv_store_ns(engine->cx(), JS_NewObject(engine->cx(), nullptr)); if (!JS_SetProperty(engine->cx(), kv_store_ns, "KVStore", kv_store_val)) { return false; } RootedValue kv_store_ns_val(engine->cx(), JS::ObjectValue(*kv_store_ns)); if (!engine->define_builtin_module("fastly:kv-store", kv_store_ns_val)) { return false; } return true; } } // namespace fastly::kv_store ================================================ FILE: runtime/fastly/builtins/kv-store.h ================================================ #ifndef FASTLY_KV_STORE_H #define FASTLY_KV_STORE_H #include "../host-api/host_api_fastly.h" #include "./fetch/request-response.h" #include "builtin.h" #define HANDLE_KV_ERROR(cx, err, err_type) \ ::host_api::handle_kv_error(cx, err, err_type, __LINE__, __func__) namespace fastly::kv_store { class KVStoreEntry final : public builtins::BuiltinImpl { template static bool bodyAll(JSContext *cx, unsigned argc, JS::Value *vp); static bool body_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool bodyUsed_get(JSContext *cx, unsigned argc, JS::Value *vp); static bool metadata(JSContext *cx, unsigned argc, JS::Value *vp); static bool metadata_text(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "KVStoreEntry"; enum class Slots { Request = static_cast(fetch::RequestOrResponse::Slots::RequestOrResponse), Body = static_cast(fetch::RequestOrResponse::Slots::Body), BodyStream = static_cast(fetch::RequestOrResponse::Slots::BodyStream), HasBody = static_cast(fetch::RequestOrResponse::Slots::HasBody), BodyUsed = static_cast(fetch::RequestOrResponse::Slots::BodyUsed), Headers = static_cast(fetch::RequestOrResponse::Slots::Headers), URL = static_cast(fetch::RequestOrResponse::Slots::URL), ManualFramingHeaders = static_cast(fetch::RequestOrResponse::Slots::ManualFramingHeaders), Backend = static_cast(fetch::RequestOrResponse::Slots::Backend), Method = static_cast(fetch::RequestOrResponse::Slots::Count), Metadata, Count, }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static const unsigned ctor_length = 0; static bool init_class(JSContext *cx, JS::HandleObject global); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); static JSObject *create(JSContext *cx, host_api::HttpBody body_handle, host_api::HostBytes metadata); }; class KVStore final : public builtins::BuiltinImpl { static bool delete_(JSContext *cx, unsigned argc, JS::Value *vp); static bool get(JSContext *cx, unsigned argc, JS::Value *vp); static bool put(JSContext *cx, unsigned argc, JS::Value *vp); static bool list(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "KVStore"; enum class Slots { KVStore, Count, }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static const unsigned ctor_length = 1; static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); }; } // namespace fastly::kv_store #endif ================================================ FILE: runtime/fastly/builtins/logger.cpp ================================================ #include "logger.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../host-api/host_api_fastly.h" namespace builtins::web::console { class Console : public BuiltinNoConstructor { private: public: static constexpr const char *class_name = "Console"; enum LogType { Log, Info, Debug, Warn, Error, }; enum Slots { Count }; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; }; bool write_stderr = false; bool write_prefix = false; void builtin_impl_console_log(Console::LogType log_ty, const char *msg) { FILE *output = stdout; if (write_stderr) { if (log_ty == Console::LogType::Warn || log_ty == Console::LogType::Error) { output = stderr; } } if (write_prefix) { const char *prefix = ""; switch (log_ty) { case Console::LogType::Log: prefix = "Log"; break; case Console::LogType::Debug: prefix = "Debug"; break; case Console::LogType::Info: prefix = "Info"; break; case Console::LogType::Warn: prefix = "Warn"; break; case Console::LogType::Error: prefix = "Error"; break; } fprintf(output, "%s: %s\n", prefix, msg); fflush(output); } else { fprintf(output, "%s\n", msg); fflush(output); } } } // namespace builtins::web::console namespace fastly::logger { bool Logger::log(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::RootedValue endpoint_id(cx, JS::GetReservedSlot(self, Slots::Endpoint)); // If the endpoint has not yet been loaded up, do it now, throwing any endpoint error for the // first log. if (endpoint_id.isNull()) { JS::RootedString endpoint_name(cx, JS::GetReservedSlot(self, Slots::EndpointName).toString()); auto endpoint_name_str = core::encode(cx, endpoint_name); if (!endpoint_name_str) { return false; } auto res = host_api::LogEndpoint::get( std::string_view{endpoint_name_str.ptr.get(), endpoint_name_str.len}); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } endpoint_id.set(JS::Int32Value(res.unwrap().handle)); JS::SetReservedSlot(self, Slots::Endpoint, endpoint_id); MOZ_ASSERT(endpoint_id.isInt32()); } host_api::LogEndpoint endpoint(endpoint_id.toInt32()); auto msg = core::encode(cx, args.get(0)); if (!msg) { return false; } auto res = endpoint.write(msg); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } args.rval().setUndefined(); return true; } const JSFunctionSpec Logger::static_methods[] = { JS_FS_END, }; const JSPropertySpec Logger::static_properties[] = { JS_PS_END, }; const JSFunctionSpec Logger::methods[] = {JS_FN("log", log, 1, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec Logger::properties[] = {JS_PS_END}; JSObject *Logger::create(JSContext *cx, JS::HandleValue endpoint_name) { JS::RootedObject logger(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!logger) { return nullptr; } JS::SetReservedSlot(logger, Slots::Endpoint, JS::NullValue()); JS::SetReservedSlot(logger, Slots::EndpointName, endpoint_name); return logger; } bool Logger::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { CTOR_HEADER("Logger", 1); auto logger = Logger::create(cx, args[0]); args.rval().setObject(*logger); return true; } bool configure_console(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); // Check if we have at least one argument and it's an object if (args.length() < 1 || !args[0].isObject()) { JS_ReportErrorUTF8(cx, "configureConsole requires an options object as its argument"); return false; } // Get the options object JS::RootedObject options(cx, &args[0].toObject()); JS::RootedValue val(cx); // Handle prefixing option if (JS_GetProperty(cx, options, "prefixing", &val)) { if (!val.isUndefined()) { if (!val.isBoolean()) { JS_ReportErrorUTF8(cx, "prefixing option must be a boolean"); return false; } builtins::web::console::write_prefix = val.toBoolean(); } } else { return false; } // Handle stderr option if (JS_GetProperty(cx, options, "stderr", &val)) { if (!val.isUndefined()) { if (!val.isBoolean()) { JS_ReportErrorUTF8(cx, "stderr option must be a boolean"); return false; } builtins::web::console::write_stderr = val.toBoolean(); } } else { return false; } // Set the return value to undefined args.rval().setUndefined(); return true; } bool install(api::Engine *engine) { if (!Logger::init_class_impl(engine->cx(), engine->global())) { return false; } RootedObject logger_ns_obj(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue logger_ns_val(engine->cx(), JS::ObjectValue(*logger_ns_obj)); RootedObject logger_obj(engine->cx(), JS_GetConstructor(engine->cx(), Logger::proto_obj)); RootedValue logger_val(engine->cx(), ObjectValue(*logger_obj)); if (!JS_SetProperty(engine->cx(), logger_ns_obj, "Logger", logger_val)) { return false; } auto configure_console_fn = JS_NewFunction(engine->cx(), &configure_console, 1, 0, "configureConsole"); RootedObject configure_console_obj(engine->cx(), JS_GetFunctionObject(configure_console_fn)); RootedValue configure_console_val(engine->cx(), ObjectValue(*configure_console_obj)); if (!JS_SetProperty(engine->cx(), logger_ns_obj, "configureConsole", configure_console_val)) { return false; } if (!JS_SetProperty(engine->cx(), logger_obj, "configureConsole", configure_console_val)) { return false; } if (!engine->define_builtin_module("fastly:logger", logger_ns_val)) { return false; } return true; } } // namespace fastly::logger ================================================ FILE: runtime/fastly/builtins/logger.h ================================================ #ifndef FASTLY_LOGGER_H #define FASTLY_LOGGER_H #include "builtin.h" #include "extension-api.h" namespace fastly::logger { class Logger : public builtins::BuiltinImpl { private: static bool log(JSContext *cx, unsigned argc, JS::Value *vp); public: static constexpr const char *class_name = "Logger"; static const int ctor_length = 1; enum Slots { Endpoint, EndpointName, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static JSObject *create(JSContext *cx, JS::HandleValue endpoint_name); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); }; } // namespace fastly::logger #endif ================================================ FILE: runtime/fastly/builtins/secret-store.cpp ================================================ #include "secret-store.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../common/validations.h" #include "../host-api/host_api_fastly.h" #include "fastly.h" using fastly::FastlyGetErrorMessage; using fastly::common::validate_bytes; namespace fastly::secret_store { host_api::Secret SecretStoreEntry::secret_handle(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, SecretStoreEntry::Slots::Handle); return host_api::Secret(val.toInt32()); } bool SecretStoreEntry::plaintext(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) // Ensure that we throw an exception for all unexpected host errors. auto res = SecretStoreEntry::secret_handle(self).plaintext(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto ret = std::move(res.unwrap()); if (!ret.has_value()) { return false; } JS::RootedString text( cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(reinterpret_cast(ret->ptr.get()), ret->len))); if (!text) { return false; } args.rval().setString(text); return true; } bool SecretStoreEntry::raw_bytes(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) // Ensure that we throw an exception for all unexpected host errors. auto res = SecretStoreEntry::secret_handle(self).plaintext(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } auto ret = std::move(res.unwrap()); if (!ret.has_value()) { return false; } JS::RootedObject array_buffer( cx, JS::NewArrayBufferWithContents(cx, ret->len, ret->ptr.get(), JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory)); if (!array_buffer) { JS_ReportOutOfMemory(cx); return false; } // `array_buffer` now owns `metadata` static_cast(ret->ptr.release()); JS::RootedObject uint8_array(cx, JS_NewUint8ArrayWithBuffer(cx, array_buffer, 0, ret->len)); args.rval().setObject(*uint8_array); return true; } const JSFunctionSpec SecretStoreEntry::static_methods[] = { JS_FS_END, }; const JSPropertySpec SecretStoreEntry::static_properties[] = { JS_PS_END, }; const JSFunctionSpec SecretStoreEntry::methods[] = { JS_FN("plaintext", plaintext, 0, JSPROP_ENUMERATE), JS_FN("rawBytes", raw_bytes, 0, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec SecretStoreEntry::properties[] = {JS_PS_END}; bool SecretStoreEntry::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { JS_ReportErrorUTF8(cx, "SecretStoreEntry can't be instantiated directly"); return false; } JSObject *SecretStoreEntry::create(JSContext *cx, host_api::Secret secret) { JS::RootedObject entry( cx, JS_NewObjectWithGivenProto(cx, &SecretStoreEntry::class_, SecretStoreEntry::proto_obj)); if (!entry) { return nullptr; } JS::SetReservedSlot(entry, Slots::Handle, JS::Int32Value(secret.handle)); return entry; } host_api::SecretStore SecretStore::secret_store_handle(JSObject *obj) { JS::Value val = JS::GetReservedSlot(obj, SecretStore::Slots::Handle); return host_api::SecretStore(val.toInt32()); } bool SecretStore::get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(1) JS::RootedObject result_promise(cx, JS::NewPromiseObject(cx, nullptr)); if (!result_promise) { return ReturnPromiseRejectedWithPendingError(cx, args); } auto key = core::encode(cx, args[0]); if (!key) { return false; } // If the converted string has a length of 0 then we throw an Error // because keys have to be at-least 1 character. if (key.len == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_SECRET_STORE_KEY_EMPTY); return ReturnPromiseRejectedWithPendingError(cx, args); } // key has to be less than 256 if (key.len > 255) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_SECRET_STORE_KEY_TOO_LONG); return ReturnPromiseRejectedWithPendingError(cx, args); } // key must contain only letters, numbers, dashes (-), underscores (_), and periods (.). auto is_valid_key = std::all_of(key.begin(), key.end(), [&](auto character) { return std::isalnum(character) || character == '_' || character == '-' || character == '.'; }); if (!is_valid_key) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_SECRET_STORE_KEY_CONTAINS_INVALID_CHARACTER); return ReturnPromiseRejectedWithPendingError(cx, args); } // Ensure that we throw an exception for all unexpected host errors. auto get_res = SecretStore::secret_store_handle(self).get(key); if (auto *err = get_res.to_err()) { HANDLE_ERROR(cx, *err); return ReturnPromiseRejectedWithPendingError(cx, args); } // When no entry is found, we are going to resolve the Promise with `null`. auto secret = get_res.unwrap(); if (!secret.has_value()) { JS::RootedValue result(cx); result.setNull(); JS::ResolvePromise(cx, result_promise, result); } else { JS::RootedObject entry(cx, SecretStoreEntry::create(cx, *secret)); if (!entry) { return ReturnPromiseRejectedWithPendingError(cx, args); } JS::RootedValue result(cx); result.setObject(*entry); JS::ResolvePromise(cx, result_promise, result); } args.rval().setObject(*result_promise); return true; } bool SecretStore::from_bytes(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "SecretStore.fromBytes", 1)) { return false; } JS::RootedObject entry( cx, JS_NewObjectWithGivenProto(cx, &SecretStoreEntry::class_, SecretStoreEntry::proto_obj)); if (!entry) { return false; } auto bytes = args.get(0); auto maybe_byte_data = validate_bytes(cx, bytes, "SecretStore.fromBytes"); if (!maybe_byte_data) { return false; } auto &[data, len, noGC] = *maybe_byte_data; auto res = host_api::SecretStore::from_bytes(data, len); noGC.reset(); if (auto *err = res.to_err()) { HANDLE_ERROR(cx, *err); return false; } JS::SetReservedSlot(entry, Slots::Handle, JS::Int32Value(res.unwrap().handle)); args.rval().setObject(*entry); return true; } const JSFunctionSpec SecretStore::static_methods[] = { JS_FN("fromBytes", from_bytes, 1, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec SecretStore::static_properties[] = { JS_PS_END, }; const JSFunctionSpec SecretStore::methods[] = {JS_FN("get", get, 1, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec SecretStore::properties[] = {JS_PS_END}; bool SecretStore::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The SecretStore builtin"); CTOR_HEADER("SecretStore", 1); auto name = core::encode(cx, args[0]); if (!name) { return false; } // If the converted string has a length of 0 then we throw an Error // because names have to be at-least 1 character. if (name.len == 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_SECRET_STORE_NAME_EMPTY); return false; } // If the converted string has a length of more than 255 then we throw an Error // because names have to be less than 255 characters. if (name.len > 255) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_SECRET_STORE_NAME_TOO_LONG); return false; } // Name must contain only letters, numbers, dashes (-), underscores (_), and periods (.). auto is_valid_name = std::all_of(name.begin(), name.end(), [&](auto character) { return std::isalnum(character) || character == '_' || character == '-' || character == '.'; }); if (!is_valid_name) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_SECRET_STORE_NAME_CONTAINS_INVALID_CHARACTER); return false; } JS::RootedObject secret_store(cx, JS_NewObjectForConstructor(cx, &class_, args)); if (!secret_store) { return false; } auto res = host_api::SecretStore::open(name); if (auto *err = res.to_err()) { if (host_api::error_is_optional_none(*err)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_SECRET_STORE_DOES_NOT_EXIST, name.begin()); return false; } else { HANDLE_ERROR(cx, *err); return false; } } JS::SetReservedSlot(secret_store, SecretStore::Slots::Handle, JS::Int32Value(res.unwrap().handle)); args.rval().setObject(*secret_store); return true; } bool install(api::Engine *engine) { if (!SecretStoreEntry::init_class_impl(engine->cx(), engine->global())) { return false; } if (!SecretStore::init_class_impl(engine->cx(), engine->global())) { return false; } RootedObject secret_store_ns_obj(engine->cx(), JS_NewObject(engine->cx(), nullptr)); RootedValue secret_store_ns_val(engine->cx(), JS::ObjectValue(*secret_store_ns_obj)); RootedObject secret_store_obj(engine->cx(), JS_GetConstructor(engine->cx(), SecretStore::proto_obj)); RootedValue secret_store_val(engine->cx(), ObjectValue(*secret_store_obj)); if (!JS_SetProperty(engine->cx(), secret_store_ns_obj, "SecretStore", secret_store_val)) { return false; } RootedObject secret_store_entry_obj(engine->cx(), JS_GetConstructor(engine->cx(), SecretStoreEntry::proto_obj)); RootedValue secret_store_entry_val(engine->cx(), ObjectValue(*secret_store_entry_obj)); if (!JS_SetProperty(engine->cx(), secret_store_ns_obj, "SecretStoreEntry", secret_store_entry_val)) { return false; } if (!engine->define_builtin_module("fastly:secret-store", secret_store_ns_val)) { return false; } return true; } } // namespace fastly::secret_store ================================================ FILE: runtime/fastly/builtins/secret-store.h ================================================ #ifndef FASTLY_SECRET_STORE_H #define FASTLY_SECRET_STORE_H #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "extension-api.h" namespace fastly::secret_store { class SecretStoreEntry : public builtins::BuiltinImpl { private: public: static constexpr const char *class_name = "SecretStoreEntry"; static const int ctor_length = 0; enum Slots { Handle, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool plaintext(JSContext *cx, unsigned argc, JS::Value *vp); static bool raw_bytes(JSContext *cx, unsigned argc, JS::Value *vp); static host_api::Secret secret_handle(JSObject *obj); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); static JSObject *create(JSContext *cx, host_api::Secret handle); }; class SecretStore : public builtins::BuiltinImpl { private: public: static constexpr const char *class_name = "SecretStore"; static const int ctor_length = 1; enum Slots { Handle, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool get(JSContext *cx, unsigned argc, JS::Value *vp); static bool from_bytes(JSContext *cx, unsigned argc, JS::Value *vp); static host_api::SecretStore secret_store_handle(JSObject *obj); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); }; } // namespace fastly::secret_store #endif ================================================ FILE: runtime/fastly/builtins/shielding.cpp ================================================ #include "shielding.h" #include "../../../StarlingMonkey/runtime/encode.h" #include "../common/validations.h" #include "../host-api/host_api_fastly.h" #include "backend.h" #include "fastly.h" namespace fastly::shielding { const uint64_t MAX_BACKEND_TIMEOUT = 0x100000000; const JSFunctionSpec Shield::static_methods[] = { JS_FS_END, }; const JSPropertySpec Shield::static_properties[] = { JS_PS_END, }; const JSFunctionSpec Shield::methods[] = { JS_FN("runningOn", runningOn, 0, JSPROP_ENUMERATE), JS_FN("unencryptedBackend", unencryptedBackend, 0, JSPROP_ENUMERATE), JS_FN("encryptedBackend", encryptedBackend, 0, JSPROP_ENUMERATE), JS_FS_END}; const JSPropertySpec Shield::properties[] = {JS_PS_END}; bool Shield::runningOn(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); bool is_me = JS::GetReservedSlot(self, static_cast(Slots::IsMe)).toBoolean(); args.rval().setBoolean(is_me); return true; } bool Shield::unencryptedBackend(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedString target( cx, JS::GetReservedSlot(self, static_cast(Slots::PlainTarget)).toString()); return backend_for_shield(cx, target, args.rval(), args.get(0)); } bool Shield::encryptedBackend(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0) JS::RootedString target( cx, JS::GetReservedSlot(self, static_cast(Slots::SSLTarget)).toString()); return backend_for_shield(cx, target, args.rval(), args.get(0)); } bool Shield::backend_for_shield(JSContext *cx, JS::HandleString target, JS::MutableHandleValue rval, JS::HandleValue config) { auto name = core::encode(cx, target); fastly_shielding_shield_backend_config host_config{nullptr, 0, 0}; if (config.isObject()) { JS::RootedObject configObj(cx, &config.toObject()); // Timeouts for backends must be less than 2^32 milliseconds, or // about a month and a half. JS::RootedValue first_byte_timeout_val(cx); bool found; if (!JS_HasProperty(cx, configObj, "firstByteTimeout", &found)) { return false; } if (found) { if (!JS_GetProperty(cx, configObj, "firstByteTimeout", &first_byte_timeout_val)) { return false; } auto parsed = common::parse_and_validate_timeout(cx, first_byte_timeout_val, "Backend for shield", "firstByteTimeout", MAX_BACKEND_TIMEOUT); if (!parsed) { return false; } host_config.first_byte_timeout_ms = parsed.value(); } } auto options_mask = 0; std::uint32_t backend_name_size_out = 0; constexpr std::size_t max_backend_name_size = 1024; std::string backend_name_out(max_backend_name_size, 0); auto status = fastly_shielding_backend_for_shield(name.ptr.get(), name.len, options_mask, &host_config, backend_name_out.data(), max_backend_name_size, &backend_name_size_out); if (status != 0) { HANDLE_ERROR(cx, status); return false; } backend_name_out.resize(backend_name_size_out); host_api::HostString backend_name(backend_name_out); return backend::Backend::get_from_valid_name(cx, std::move(backend_name), rval); } bool Shield::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { REQUEST_HANDLER_ONLY("The Shield builtin"); CTOR_HEADER("Shield", 1); JS::HandleValue name_arg = args.get(0); auto name = core::encode(cx, name_arg); // Keep calling fastly_shielding_shield_info with a increasingly large buffer until it returns OK std::uint32_t buf_size = 1024; std::vector out_buf(buf_size); while (true) { std::uint32_t used_amount = 0; auto status = fastly_shielding_shield_info(name.ptr.get(), name.len, out_buf.data(), buf_size, &used_amount); if (status == 0) { out_buf.resize(used_amount); break; } else if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { buf_size *= 2; out_buf = std::vector(buf_size); } else { HANDLE_ERROR(cx, status); return false; } } if (out_buf.size() < 3) { JS_ReportErrorASCII(cx, "Shield: invalid response from host"); return false; } JS::RootedObject self(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj)); if (!self) { return false; } bool is_me = out_buf[0] != 0; JS_SetReservedSlot(self, static_cast(Slots::IsMe), JS::BooleanValue(is_me)); JS::RootedString plain_target(cx, JS_NewStringCopyZ(cx, out_buf.data() + 1)); if (!plain_target) { return false; } JS_SetReservedSlot(self, static_cast(Slots::PlainTarget), JS::StringValue(plain_target)); auto plain_bytes_end = std::find(begin(out_buf) + 1, end(out_buf), 0); if (plain_bytes_end == end(out_buf) || plain_bytes_end + 1 == end(out_buf)) { JS_ReportErrorASCII(cx, "Shield: invalid response from host"); return false; } JS::RootedString ssl_target(cx, JS_NewStringCopyZ(cx, &*plain_bytes_end + 1)); if (!ssl_target) { return false; } JS_SetReservedSlot(self, static_cast(Slots::SSLTarget), JS::StringValue(ssl_target)); args.rval().setObject(*self); return true; } bool install(api::Engine *engine) { RootedObject shielding_ns(engine->cx(), JS_NewObject(engine->cx(), nullptr)); if (!Shield::init_class_impl(engine->cx(), shielding_ns)) { return false; } RootedObject shield_obj(engine->cx(), JS_GetConstructor(engine->cx(), Shield::proto_obj)); RootedValue shield_val(engine->cx(), ObjectValue(*shield_obj)); if (!JS_SetProperty(engine->cx(), shielding_ns, "Shield", shield_val)) { return false; } RootedValue shielding_ns_val(engine->cx(), JS::ObjectValue(*shielding_ns)); if (!engine->define_builtin_module("fastly:shielding", shielding_ns_val)) { return false; } RootedObject fastly(engine->cx()); if (!fastly::get_fastly_object(engine, &fastly)) { return false; } if (!JS_SetProperty(engine->cx(), fastly, "shielding", shielding_ns_val)) { return false; } return true; } } // namespace fastly::shielding ================================================ FILE: runtime/fastly/builtins/shielding.h ================================================ #ifndef FASTLY_SHIELDING_H #define FASTLY_SHIELDING_H #include "../host-api/host_api_fastly.h" #include "builtin.h" #include "extension-api.h" namespace fastly::shielding { class Shield : public builtins::BuiltinImpl { private: static bool backend_for_shield(JSContext *cx, JS::HandleString target, JS::MutableHandleValue rval, JS::HandleValue config); public: static constexpr const char *class_name = "Shield"; static const int ctor_length = 0; enum Slots { IsMe, PlainTarget, SSLTarget, Count }; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool runningOn(JSContext *cx, unsigned argc, JS::Value *vp); static bool unencryptedBackend(JSContext *cx, unsigned argc, JS::Value *vp); static bool encryptedBackend(JSContext *cx, unsigned argc, JS::Value *vp); static bool constructor(JSContext *cx, unsigned argc, JS::Value *vp); }; } // namespace fastly::shielding #endif ================================================ FILE: runtime/fastly/common/ip_octets_to_js_string.cpp ================================================ #include #include "builtin.h" #include "extension-api.h" #include "host_api.h" namespace fastly::common { JSString *ip_octets_to_js_string(JSContext *cx, host_api::HostBytes octets) { char address_chars[INET6_ADDRSTRLEN]; int addr_family = 0; socklen_t size = 0; switch (octets.len) { case 0: { // No address to be had, leave `address` as a nullptr. break; } case 4: { addr_family = AF_INET; size = INET_ADDRSTRLEN; break; } case 16: { addr_family = AF_INET6; size = INET6_ADDRSTRLEN; break; } } JS::RootedString address(cx); if (octets.len > 0) { // TODO: do we need to do error handling here, or can we depend on the // host giving us a valid address? inet_ntop(addr_family, octets.begin(), address_chars, size); address = JS_NewStringCopyZ(cx, address_chars); if (!address) { return nullptr; } } return address; } } // namespace fastly::common ================================================ FILE: runtime/fastly/common/ip_octets_to_js_string.h ================================================ #ifndef FASTLY_IP_OCTETS_TO_JS_STRING_H #define FASTLY_IP_OCTETS_TO_JS_STRING_H #include #include "builtin.h" #include "extension-api.h" #include "host_api.h" namespace fastly::common { JSString *ip_octets_to_js_string(JSContext *cx, host_api::HostBytes octets); } // namespace fastly::common #endif ================================================ FILE: runtime/fastly/common/normalize_http_method.cpp ================================================ #include #include #include namespace fastly::common { // https://fetch.spec.whatwg.org/#concept-method-normalize // To normalize a method, if it is a byte-case-insensitive match for `DELETE`, `GET`, `HEAD`, // `OPTIONS`, `POST`, or `PUT`, byte-uppercase it. bool normalize_http_method(char *method, size_t length) { // Ordered by most likely to occur. constexpr std::string_view methods[] = {"GET", "HEAD", "OPTIONS", "POST", "PUT", "DELETE"}; std::string_view m(method, length); auto iequal = [](unsigned char a, unsigned char b) { return std::toupper(a) == std::toupper(b); }; auto it = std::ranges::find_if(methods, [&](std::string_view candidate) { return std::ranges::equal(m, candidate, iequal); }); if (it == std::ranges::end(methods) || *it == m) { return false; // not a recognized method, or already normalized } std::ranges::copy(*it, method); // copy the already-uppercase canonical form return true; } } // namespace fastly::common ================================================ FILE: runtime/fastly/common/normalize_http_method.h ================================================ #ifndef FASTLY_NORMALIZE_HTTP_METHOD_H #define FASTLY_NORMALIZE_HTTP_METHOD_H namespace fastly::common { // https://fetch.spec.whatwg.org/#concept-method-normalize // To normalize a method, if it is a byte-case-insensitive match for `DELETE`, `GET`, `HEAD`, // `OPTIONS`, `POST`, or `PUT`, byte-uppercase it. // Returns `true` if the method name was normalized, `false` otherwise. bool normalize_http_method(char *method, size_t length); } // namespace fastly::common #endif ================================================ FILE: runtime/fastly/common/sequence.hpp ================================================ #ifndef FASTLY_SEQUENCE_HPP #define FASTLY_SEQUENCE_HPP // TODO: remove these once the warnings are fixed #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #include "jsapi.h" #include "jsfriendapi.h" #include "js/ForOfIterator.h" #pragma clang diagnostic pop namespace fastly::common { inline bool report_sequence_or_record_arg_error(JSContext *cx, const char *name, const char *alt_text) { JS_ReportErrorUTF8(cx, "Failed to construct %s object. If defined, the first " "argument must be either a [ ['name', 'value'], ... ] sequence, " "or a { 'name' : 'value', ... } record%s.", name, alt_text); return false; } /** * Extract pairs from the given value if it is either a * sequence or a record. */ template bool maybe_consume_sequence_or_record(JSContext *cx, JS::HandleValue initv, JS::HandleObject target, bool *consumed, const char *ctor_name, const char *alt_text = "") { if (initv.isUndefined()) { *consumed = true; return true; } JS::RootedValue key(cx); JS::RootedValue value(cx); // First, try consuming args[0] as a sequence>. JS::ForOfIterator it(cx); if (!it.init(initv, JS::ForOfIterator::AllowNonIterable)) return false; // Note: this currently doesn't treat strings as iterable even though they // are. We don't have any constructors that want to iterate over strings, and // this makes things a lot easier. if (initv.isObject() && it.valueIsIterable()) { JS::RootedValue entry(cx); while (true) { bool done; if (!it.next(&entry, &done)) return false; if (done) break; if (!entry.isObject()) return report_sequence_or_record_arg_error(cx, ctor_name, alt_text); JS::ForOfIterator entr_iter(cx); if (!entr_iter.init(entry, JS::ForOfIterator::AllowNonIterable)) return false; if (!entr_iter.valueIsIterable()) return report_sequence_or_record_arg_error(cx, ctor_name, alt_text); { bool done; // Extract key. if (!entr_iter.next(&key, &done)) return false; if (done) return report_sequence_or_record_arg_error(cx, ctor_name, alt_text); // Extract value. if (!entr_iter.next(&value, &done)) return false; if (done) return report_sequence_or_record_arg_error(cx, ctor_name, alt_text); // Ensure that there aren't any further entries. if (!entr_iter.next(&entry, &done)) return false; if (!done) return report_sequence_or_record_arg_error(cx, ctor_name, alt_text); if (!apply(cx, target, key, value, ctor_name)) return false; } } *consumed = true; } else if (initv.isObject()) { // init isn't an iterator, so if it's an object, it must be a record to be // valid input. JS::RootedObject init(cx, &initv.toObject()); JS::RootedIdVector ids(cx); if (!js::GetPropertyKeys(cx, init, JSITER_OWNONLY | JSITER_SYMBOLS, &ids)) return false; JS::RootedId curId(cx); for (size_t i = 0; i < ids.length(); ++i) { curId = ids[i]; key = js::IdToValue(curId); if (!JS_GetPropertyById(cx, init, curId, &value)) return false; if (!apply(cx, target, key, value, ctor_name)) return false; } *consumed = true; } else { *consumed = false; } return true; } } #endif ================================================ FILE: runtime/fastly/common/validations.cpp ================================================ #include "validations.h" #include "../builtins/fastly.h" #include "../host-api/host_api_fastly.h" #include "encode.h" using fastly::FastlyGetErrorMessage; namespace fastly::common { std::optional parse_and_validate_timeout(JSContext *cx, JS::HandleValue value, const char *subsystem, std::string property_name, uint64_t max_timeout) { double native_value; if (!JS::ToNumber(cx, value, &native_value)) { return std::nullopt; } if (std::isnan(native_value)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_TIMEOUT_NAN, subsystem, property_name.c_str()); return std::nullopt; } if (native_value < 0) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_TIMEOUT_NEGATIVE, subsystem, property_name.c_str()); return std::nullopt; } if (native_value >= max_timeout) { std::string max_timeout_str = std::to_string(max_timeout); JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_TIMEOUT_TOO_BIG, subsystem, property_name.c_str(), max_timeout_str.c_str()); return std::nullopt; } return std::round(native_value); } std::optional>> validate_bytes(JSContext *cx, JS::HandleValue bytes, const char *subsystem) { if (!bytes.isObject()) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_INVALID_BUFFER, subsystem); return std::nullopt; } JS::RootedObject bytes_obj(cx, &bytes.toObject()); if (!JS::IsArrayBufferObject(bytes_obj) && !JS_IsArrayBufferViewObject(bytes_obj)) { JS_ReportErrorNumberASCII(cx, FastlyGetErrorMessage, nullptr, JSMSG_INVALID_BUFFER, subsystem); return std::nullopt; } const uint8_t *buf; size_t length; bool is_shared; std::optional noGC; if (JS_IsArrayBufferViewObject(bytes_obj)) { noGC.emplace(); length = JS_GetArrayBufferViewByteLength(bytes_obj); buf = (const uint8_t *)JS_GetArrayBufferViewData(bytes_obj, &is_shared, *noGC); MOZ_ASSERT(!is_shared); } else { JS::GetArrayBufferLengthAndData(bytes_obj, &length, &is_shared, (uint8_t **)&buf); } return std::make_tuple(buf, length, std::move(noGC)); } } // namespace fastly::common ================================================ FILE: runtime/fastly/common/validations.h ================================================ #ifndef FASTLY_VALIDATIONS_H #define FASTLY_VALIDATIONS_H #include "builtin.h" #include "js/GCAPI.h" #include #include namespace fastly::common { std::optional parse_and_validate_timeout(JSContext *cx, JS::HandleValue value, const char *subsystem, std::string property_name, uint64_t max_timeout); std::optional>> validate_bytes(JSContext *cx, JS::HandleValue bytes, const char *subsystem); } // namespace fastly::common #endif ================================================ FILE: runtime/fastly/crates/rust-lol-html/Cargo.toml ================================================ [package] name = "lol_html_c_api" version = "1.3.0" description = "Low output latency streaming HTML parser/rewriter" authors = [ "Ivan Nikulin ", "Joshua Nelson ", ] edition = "2021" links = "lolhtml" publish = false [features] default = ["capi"] # Required to exist for cargo-c to work capi = [] [dependencies] encoding_rs = "0.8.35" lol_html = "=2.7.0" libc = "0" thiserror = "2" [profile.release] panic = "abort" lto = true [lib] crate-type = ["staticlib", "cdylib", "rlib"] [package.metadata.capi.header] name = "lol_html" subdirectory = "" generation = false [package.metadata.capi.install.include] asset = [{ from = "include/lol_html.h" }] [package.metadata.capi.pkg_config] name = "lol-html" filename = "lol-html" ================================================ FILE: runtime/fastly/crates/rust-lol-html/LICENSE ================================================ Copyright (C) 2019, Cloudflare, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: runtime/fastly/crates/rust-lol-html/build.rs ================================================ // Required for the links attribute fn main() {} ================================================ FILE: runtime/fastly/crates/rust-lol-html/include/lol_html.h ================================================ #ifndef LOL_HTML_H #define LOL_HTML_H #if defined(__cplusplus) extern "C" { #endif #include #include // NOTE: all functions that accept pointers will panic abort the thread // if NULL pointer is passed (with an exception for the cases where // explicitly stated that function can accept NULL pointers). // NOTE: all UTF8-strings passed to the API functions allow interior '\0's // and their length determined by the corresponding length parameter only. // Opaque structures used by the rewriter. // WARNING: these structures should never be deallocated by the C code. // There are appropriate methods exposed that take care of these structures // deallocation. typedef struct lol_html_HtmlRewriterBuilder lol_html_rewriter_builder_t; typedef struct lol_html_HtmlRewriter lol_html_rewriter_t; typedef struct lol_html_Doctype lol_html_doctype_t; typedef struct lol_html_DocumentEnd lol_html_doc_end_t; typedef struct lol_html_EndTag lol_html_end_tag_t; typedef struct lol_html_Comment lol_html_comment_t; typedef struct lol_html_TextChunk lol_html_text_chunk_t; typedef struct lol_html_Element lol_html_element_t; typedef struct lol_html_AttributesIterator lol_html_attributes_iterator_t; typedef struct lol_html_Attribute lol_html_attribute_t; typedef struct lol_html_Selector lol_html_selector_t; typedef struct lol_html_CStreamingHandlerSink lol_html_streaming_sink_t; // Library-allocated UTF8 string fat pointer. // // The string is not NULL-terminated. // // Should NEVER be deallocated in the C code. Use special `lol_html_str_free` // function instead. typedef struct { // String data pointer. const char *data; // The length of the string in bytes. size_t len; } lol_html_str_t; // A fat pointer to text chunk content. // // The difference between this struct and `lol_html_str_t` is // that text chunk content shouldn't be deallocated manually via // `lol_html_str_free` method call. Instead the pointer becomes // invalid ones related `lol_html_text_chunk_t` struct goes out // of scope. typedef struct { // String data pointer. const char *data; // The length of the string in bytes. size_t len; } lol_html_text_chunk_content_t; // Utilities //--------------------------------------------------------------------- // Frees the memory held by the library-allocated string. // // This is valid to call even if `str.data == NULL` (it does nothing, like `free(NULL)`). void lol_html_str_free(lol_html_str_t str); // Returns the last error message and resets last error to NULL. // // The `data` field will be NULL if there was no error. lol_html_str_t lol_html_take_last_error(); // Creates new HTML rewriter builder. lol_html_rewriter_builder_t *lol_html_rewriter_builder_new(); // Content handlers //--------------------------------------------------------------------- // Rewriter directive that should be returned from each content handler. // If LOL_HTML_STOP directive is returned then rewriting stops immediately // and `write()` or `end()` methods of the rewriter return an error code. typedef enum { LOL_HTML_CONTINUE, LOL_HTML_STOP } lol_html_rewriter_directive_t; typedef lol_html_rewriter_directive_t (*lol_html_doctype_handler_t)(lol_html_doctype_t *doctype, void *user_data); typedef lol_html_rewriter_directive_t (*lol_html_comment_handler_t)(lol_html_comment_t *comment, void *user_data); typedef lol_html_rewriter_directive_t (*lol_html_text_handler_handler_t)( lol_html_text_chunk_t *chunk, void *user_data); typedef lol_html_rewriter_directive_t (*lol_html_element_handler_t)(lol_html_element_t *element, void *user_data); typedef lol_html_rewriter_directive_t (*lol_html_doc_end_handler_t)(lol_html_doc_end_t *doc_end, void *user_data); typedef lol_html_rewriter_directive_t (*lol_html_end_tag_handler_t)(lol_html_end_tag_t *end_tag, void *user_data); // `size_t` byte offsets from the start of the input document typedef struct lol_html_SourceLocationBytes { size_t start; size_t end; } lol_html_source_location_bytes_t; // For use with streaming content handlers. // // Safety: the user data and the callbacks must be safe to use from a different thread (e.g. can't // rely on thread-local storage). It doesn't have to be `Sync`, it will be used only by one thread // at a time. // // Handler functions copy this struct. It can (and should) be created on the stack. typedef struct lol_html_CStreamingHandler { // Anything you like void *user_data; // Called when the handler is supposed to produce its output. Return `0` for success. // The `sink` argument is guaranteed non-`NULL`. It is valid only for the duration of this call, // and can only be used on the same thread. The sink is for [`lol_html_streaming_sink_write_str`] // and [`lol_html_streaming_sink_write_utf8_chunk`]. `user_data` comes from this struct. // `write_all_callback` must not be `NULL`. int (*write_all_callback)(lol_html_streaming_sink_t *sink, void *user_data); // Called exactly once, after the last use of this handler. // `user_data` comes from this struct. // May be `NULL`. void (*drop_callback)(void *user_data); // *Always* initialize to `NULL`. void *reserved; } lol_html_streaming_handler_t; // Selector //--------------------------------------------------------------------- // Parses given CSS selector string. // // Returns NULL if parsing error occurs. The actual error message // can be obtained using `lol_html_take_last_error` function. // // WARNING: Selector SHOULD NOT be deallocated if there are any active rewriter // builders that accepted it as an argument to // `lol_html_rewriter_builder_add_element_content_handlers()` method. Deallocate all dependant // rewriter builders first and then use `lol_html_selector_free` function to free the selector. lol_html_selector_t *lol_html_selector_parse(const char *selector, size_t selector_len); // Frees the memory held by the parsed selector object. void lol_html_selector_free(lol_html_selector_t *selector); // Rewriter builder //--------------------------------------------------------------------- // Adds document-level content handlers to the builder. // // If a particular handler is not required then NULL can be passed // instead. Don't use stub handlers in this case as this affects // performance - rewriter skips parsing of the content that doesn't // need to be processed. // // Each handler can optionally have associated user data which will be // passed to the handler on each invocation along with the rewritable // unit argument. // // If any of handlers return LOL_HTML_STOP directive then rewriting // stops immediately and `write()` or `end()` of the rewriter methods // return an error code. // // WARNING: Pointers passed to handlers are valid only during the // handler execution. So they should never be leaked outside of handlers. void lol_html_rewriter_builder_add_document_content_handlers( lol_html_rewriter_builder_t *builder, lol_html_doctype_handler_t doctype_handler, void *doctype_handler_user_data, lol_html_comment_handler_t comment_handler, void *comment_handler_user_data, lol_html_text_handler_handler_t text_handler, void *text_handler_user_data, lol_html_doc_end_handler_t doc_end_handler, void *doc_end_user_data); // Adds element content handlers to the builder for the // given CSS selector. // // Selector should be a valid UTF8-string. // // If a particular handler is not required then NULL can be passed // instead. Don't use stub handlers in this case as this affects // performance - rewriter skips parsing of the content that doesn't // need to be processed. // // Each handler can optionally have associated user data which will be // passed to the handler on each invocation along with the rewritable // unit argument. // // If any of handlers return LOL_HTML_STOP directive then rewriting // stops immediately and `write()` or `end()` of the rewriter methods // return an error code. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. // // WARNING: Pointers passed to handlers are valid only during the // handler execution. So they should never be leaked outside of handlers. int lol_html_rewriter_builder_add_element_content_handlers( lol_html_rewriter_builder_t *builder, const lol_html_selector_t *selector, lol_html_element_handler_t element_handler, void *element_handler_user_data, lol_html_comment_handler_t comment_handler, void *comment_handler_user_data, lol_html_text_handler_handler_t text_handler, void *text_handler_user_data); // Frees the memory held by the builder. // // Note that builder can be freed before any rewriters constructed from // it if it's not intended to be used anymore. void lol_html_rewriter_builder_free(lol_html_rewriter_builder_t *builder); // Rewriter //--------------------------------------------------------------------- // Memory management settings for the rewriter. typedef struct { // Preallocated size of the parsing buffer. // // Can be set to 0. In this case rewriter won't consume any memory initially, // though there might be a performance penalty due to later reallocations. size_t preallocated_parsing_buffer_size; // Maximum amount of memory to be used by a rewriter. // // `lol_html_rewriter_write` and `lol_html_rewriter_end` will return an error // if this limit is exceeded. size_t max_allowed_memory_usage; } lol_html_memory_settings_t; // Builds HTML-rewriter out of the provided builder. Can be called // multiple times to construct different rewriters from the same // builder. // // `output_sink` receives a zero-length chunk on the end of the output. // // `output_sink` can optionally have associated user data that will // be passed to handler on each invocation along with other arguments. // // `strict` mode will bail out from tokenization process in cases when // there is no way to determine correct parsing context. Recommended // setting for safety reasons. // // In case of an error the function returns a NULL pointer. lol_html_rewriter_t * lol_html_rewriter_build(lol_html_rewriter_builder_t *builder, const char *encoding, size_t encoding_len, lol_html_memory_settings_t memory_settings, void (*output_sink)(const char *chunk, size_t chunk_len, void *user_data), void *output_sink_user_data, bool strict); lol_html_rewriter_t *unstable_lol_html_rewriter_build_with_esi_tags( lol_html_rewriter_builder_t *builder, const char *encoding, size_t encoding_len, lol_html_memory_settings_t memory_settings, void (*output_sink)(const char *chunk, size_t chunk_len, void *user_data), void *output_sink_user_data, bool strict); // Write HTML chunk to rewriter. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. // // WARNING: if this function errors the rewriter gets into the unrecoverable state, // so any further attempts to use the rewriter will cause a thread panic. int lol_html_rewriter_write(lol_html_rewriter_t *rewriter, const char *chunk, size_t chunk_len); // Completes rewriting and flushes the remaining output. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. // // WARNING: after calling this function, further attempts to use the rewriter // (other than `lol_html_rewriter_free`) will cause a thread panic. int lol_html_rewriter_end(lol_html_rewriter_t *rewriter); // Frees the memory held by the rewriter. void lol_html_rewriter_free(lol_html_rewriter_t *rewriter); // Doctype //--------------------------------------------------------------------- // Returns doctype's name. // // The `data` field will be NULL if the doctype doesn't have a name. lol_html_str_t lol_html_doctype_name_get(const lol_html_doctype_t *doctype); // Returns doctype's PUBLIC identifier. // // The `data` field will be NULL if the doctype doesn't have a PUBLIC identifier. lol_html_str_t lol_html_doctype_public_id_get(const lol_html_doctype_t *doctype); // Returns doctype's SYSTEM identifier. // // The `data` field will be NULL if the doctype doesn't have a SYSTEM identifier. lol_html_str_t lol_html_doctype_system_id_get(const lol_html_doctype_t *doctype); // Attaches custom user data to the doctype. // // The same doctype can be passed to multiple handlers if it has been // captured by multiple selectors. It might be handy to store some processing // state on the doctype, so it can be shared between handlers. void lol_html_doctype_user_data_set(const lol_html_doctype_t *doctype, void *user_data); // Returns user data attached to the doctype. void *lol_html_doctype_user_data_get(const lol_html_doctype_t *doctype); // Removes the doctype. void lol_html_doctype_remove(lol_html_doctype_t *doctype); // Returns `true` if the doctype has been removed. bool lol_html_doctype_is_removed(const lol_html_doctype_t *doctype); // Returns [`SourceLocationBytes`]. // // `doctype` must be valid and non-`NULL`. lol_html_source_location_bytes_t lol_html_doctype_source_location_bytes(lol_html_doctype_t *doctype); // Comment //--------------------------------------------------------------------- // Returns comment text. lol_html_str_t lol_html_comment_text_get(const lol_html_comment_t *comment); // Sets comment text. // // Text should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_comment_text_set(lol_html_comment_t *comment, const char *text, size_t text_len); // Inserts the content string before the comment either as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_comment_before(lol_html_comment_t *comment, const char *content, size_t content_len, bool is_html); // Inserts the content string after the comment either as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_comment_after(lol_html_comment_t *comment, const char *content, size_t content_len, bool is_html); // Replace the comment with the content of the string which is interpreted // either as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_comment_replace(lol_html_comment_t *comment, const char *content, size_t content_len, bool is_html); // Removes the comment. // `comment` must be valid and non-`NULL`. // // Calls [`Comment::remove`]. void lol_html_comment_remove(lol_html_comment_t *comment); // Returns `true` if the comment has been removed. bool lol_html_comment_is_removed(const lol_html_comment_t *comment); // Attaches custom user data to the comment. // // The same comment can be passed to multiple handlers if it has been // captured by multiple selectors. It might be handy to store some // processing state on the comment, so it can be shared between handlers. void lol_html_comment_user_data_set(const lol_html_comment_t *comment, void *user_data); // Returns user data attached to the comment. void *lol_html_comment_user_data_get(const lol_html_comment_t *comment); // Returns [`SourceLocationBytes`]. // // `comment` must be valid and non-`NULL`. lol_html_source_location_bytes_t lol_html_comment_source_location_bytes(lol_html_comment_t *comment); // Element //--------------------------------------------------------------------- // Returns the tag name of the element. lol_html_str_t lol_html_element_tag_name_get(const lol_html_element_t *element); // Returns the tag name of the element, preserving its case. lol_html_str_t lol_html_element_tag_name_get_preserve_case(const lol_html_element_t *element); // Sets the tag name of the element. // // Name should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_element_tag_name_set(lol_html_element_t *element, const char *name, size_t name_len); // Whether the tag syntactically ends with `/>`. In HTML content this is purely a decorative, // unnecessary, and has no effect of any kind. // // The `/>` syntax only affects parsing of elements in foreign content (SVG and MathML). // It will never close any HTML tags that aren't already defined as void in HTML. // // This function only reports the parsed syntax, and will not report which elements are actually // void in HTML. Use `lol_html_element_can_have_content` to check if the element is non-void. // // If the `/` is part of an unquoted attribute, it's not parsed as the self-closing syntax. bool lol_html_element_is_self_closing(lol_html_element_t *element); // Whether the element can have inner content. Returns `true` unless the element is an [HTML void // element](https://html.spec.whatwg.org/multipage/syntax.html#void-elements) or has a // self-closing tag (eg, ``). bool lol_html_element_can_have_content(lol_html_element_t *element); // Returns the namespace URI of the element. // // NOTE: This method returns static zero-terminated C string, so it don't // need to be freed. const char *lol_html_element_namespace_uri_get(const lol_html_element_t *element); // Returns the iterator over the element attributes. // // WARNING: The iterator is valid only during the handler execution and // should never be leaked outside of it. // // Use `lol_html_attributes_iterator_free` function to deallocate // returned iterator. lol_html_attributes_iterator_t *lol_html_attributes_iterator_get(const lol_html_element_t *element); // Frees the memory held by the attribute iterator. void lol_html_attributes_iterator_free(lol_html_attributes_iterator_t *iterator); // Advances the iterator and returns next attribute. // // Returns NULL if iterator has been exhausted. // // WARNING: Returned attribute is valid only during the handler // execution and should never be leaked outside of it. const lol_html_attribute_t * lol_html_attributes_iterator_next(lol_html_attributes_iterator_t *iterator); // Returns the attribute name. lol_html_str_t lol_html_attribute_name_get(const lol_html_attribute_t *attribute); // Returns the attribute name, preserving its case. lol_html_str_t lol_html_attribute_name_get_preserve_case(const lol_html_attribute_t *attribute); // Returns the attribute value. lol_html_str_t lol_html_attribute_value_get(const lol_html_attribute_t *attribute); // Returns [`SourceLocationBytes`]. // // `element` must be valid and non-`NULL`. lol_html_source_location_bytes_t lol_html_element_source_location_bytes(lol_html_element_t *element); // Returns the attribute value. The `data` field will be NULL if an attribute with the given name // doesn't exist on the element. // // Name should be a valid UTF8-string. // // If the provided name is invalid UTF8-string the function returns NULL as well. // Therefore one should always check `lol_html_take_last_error` result after the call. lol_html_str_t lol_html_element_get_attribute(const lol_html_element_t *element, const char *name, size_t name_len); // Returns 1 if element has attribute with the given name, and 0 otherwise. // Returns -1 in case of an error. // // Name should be a valid UTF8-string. int lol_html_element_has_attribute(const lol_html_element_t *element, const char *name, size_t name_len); // Updates the attribute value if attribute with the given name already exists on // the element, or creates adds new attribute with given name and value otherwise. // // Name and value should be valid UTF8-strings. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_element_set_attribute(lol_html_element_t *element, const char *name, size_t name_len, const char *value, size_t value_len); // Removes the attribute with the given name from the element. // // Name should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_element_remove_attribute(lol_html_element_t *element, const char *name, size_t name_len); // Inserts the content string before the element either as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. // // Calls [`Element::before`]. int lol_html_element_before(lol_html_element_t *element, const char *content, size_t content_len, bool is_html); // Inserts the content string right after the element's start tag // either as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_element_prepend(lol_html_element_t *element, const char *content, size_t content_len, bool is_html); // Inserts the content string right before the element's end tag // either as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. // // Calls [`Element::append`]. int lol_html_element_append(lol_html_element_t *element, const char *content, size_t content_len, bool is_html); // Inserts the content string right after the element's end tag as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_element_after(lol_html_element_t *element, const char *content, size_t content_len, bool is_html); // Sets either text or HTML inner content of the element. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_element_set_inner_content(lol_html_element_t *element, const char *content, size_t content_len, bool is_html); // Replaces the element with the provided text or HTML content. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_element_replace(lol_html_element_t *element, const char *content, size_t content_len, bool is_html); // Removes the element. void lol_html_element_remove(const lol_html_element_t *element); // Removes the element, but leaves its inner content intact. void lol_html_element_remove_and_keep_content(const lol_html_element_t *element); // Returns `true` if the element has been removed. bool lol_html_element_is_removed(const lol_html_element_t *element); // Attaches custom user data to the element. // // The same element can be passed to multiple handlers if it has been // captured by multiple selectors. It might be handy to store some processing // state on the element, so it can be shared between handlers. void lol_html_element_user_data_set(const lol_html_element_t *element, void *user_data); // Returns user data attached to the element. void *lol_html_element_user_data_get(const lol_html_element_t *element); // Adds content handlers to the builder for the end tag of the given element. // // Subsequent calls to the method on the same element adds new handler. // They will run in the order in which they were registered. // // The handler can optionally have associated user data which will be // passed to the handler on each invocation along with the rewritable // unit argument. // // If the handler returns LOL_HTML_STOP directive then rewriting // stops immediately and `write()` or `end()` of the rewriter methods // return an error code. // // Not all elements (for example, `
`) support end tags. If this function is // called on such an element, this function returns an error code as described // below. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. // // WARNING: Pointers passed to handlers are valid only during the // handler execution. So they should never be leaked outside of handlers. int lol_html_element_add_end_tag_handler(lol_html_element_t *element, lol_html_end_tag_handler_t end_tag_handler, void *user_data); // Clears the handlers that would run on the end tag of the given element. void lol_html_element_clear_end_tag_handlers(lol_html_element_t *element); // Inserts the content string before the element's end tag either as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. // // Calls [`EndTag::before`]. int lol_html_end_tag_before(lol_html_end_tag_t *end_tag, const char *content, size_t content_len, bool is_html); // Inserts the content string right after the element's end tag as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_end_tag_after(lol_html_end_tag_t *end_tag, const char *content, size_t content_len, bool is_html); // Removes the end tag. // `end_tag` must be valid and non-`NULL`. // // Calls [`EndTag::remove`]. void lol_html_end_tag_remove(lol_html_end_tag_t *end_tag); // Returns the end tag name. lol_html_str_t lol_html_end_tag_name_get(const lol_html_end_tag_t *end_tag); // Returns the end tag name, preserving its case. lol_html_str_t lol_html_end_tag_name_get_preserve_case(const lol_html_end_tag_t *end_tag); // Sets the tag name of the end tag. // // Name should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_end_tag_name_set(lol_html_end_tag_t *end_tag, const char *name, size_t name_len); // Inserts the content at the end of the document, either as raw text or as HTML. // // The content should be a valid UTF-8 string. // // Returns 0 if successful, and -1 otherwise. The actual error message // can be obtained using the `lol_html_take_last_error` function. int lol_html_doc_end_append(lol_html_doc_end_t *doc_end, const char *content, size_t content_len, bool is_html); // [`Element::streaming_prepend`] // // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `element` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. int lol_html_element_streaming_prepend(lol_html_element_t *element, lol_html_streaming_handler_t *streaming_writer); // [`Element::streaming_append`] // // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `element` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. int lol_html_element_streaming_append(lol_html_element_t *element, lol_html_streaming_handler_t *streaming_writer); // [`Element::streaming_before`] // // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `element` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. int lol_html_element_streaming_before(lol_html_element_t *element, lol_html_streaming_handler_t *streaming_writer); // [`Element::streaming_after`] // // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `element` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. int lol_html_element_streaming_after(lol_html_element_t *element, lol_html_streaming_handler_t *streaming_writer); // [`Element::streaming_set_inner_content`] // // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `element` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. int lol_html_element_streaming_set_inner_content(lol_html_element_t *element, lol_html_streaming_handler_t *streaming_writer); // [`Element::streaming_replace`] // // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `element` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. int lol_html_element_streaming_replace(lol_html_element_t *element, lol_html_streaming_handler_t *streaming_writer); // Returns [`SourceLocationBytes`]. // // `end_tag` must be valid and non-`NULL`. lol_html_source_location_bytes_t lol_html_end_tag_source_location_bytes(lol_html_end_tag_t *end_tag); // [`EndTag::streaming_before`] // // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `end_tag` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. // // Calls [`EndTag::streaming_before`]. int lol_html_end_tag_streaming_before(lol_html_end_tag_t *end_tag, lol_html_streaming_handler_t *streaming_writer); // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `end_tag` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. // // Calls [`EndTag::streaming_after`]. int lol_html_end_tag_streaming_after(lol_html_end_tag_t *end_tag, lol_html_streaming_handler_t *streaming_writer); // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `end_tag` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. // // Calls [`EndTag::streaming_replace`]. int lol_html_end_tag_streaming_replace(lol_html_end_tag_t *end_tag, lol_html_streaming_handler_t *streaming_writer); // Write another piece of UTF-8 data to the output. Returns `0` on success, and `-1` if it wasn't // valid UTF-8. All pointers must be non-NULL. int lol_html_streaming_sink_write_str(lol_html_streaming_sink_t *sink, const char *string_utf8, size_t string_utf8_len, bool is_html); // [`StreamingHandlerSink::write_utf8_chunk`] // // Writes as much of the given UTF-8 fragment as possible, converting the encoding and HTML-escaping // if `is_html` is `false`. // // The `bytes_utf8` doesn't need to be a complete UTF-8 string, as long as consecutive calls to this // function create a valid UTF-8 string. Any incomplete UTF-8 sequence at the end of the content is // buffered and flushed as soon as it's completed. // // Other functions like [`lol_html_streaming_sink_write_str`] should not be called after a // `lol_html_streaming_sink_write_utf8_chunk` call with an incomplete UTF-8 sequence. // // Returns `0` on success, and `-1` if it wasn't valid UTF-8. // All pointers must be non-`NULL`. int lol_html_streaming_sink_write_utf8_chunk(lol_html_streaming_sink_t *sink, const char *bytes_utf8, size_t bytes_utf8_len, bool is_html); // Text chunk //--------------------------------------------------------------------- // Returns a fat pointer to the UTF8 representation of content of the chunk. // // If the chunk is last in the current text node then content can be an empty string. // // WARNING: The pointer is valid only during the handler execution and // should never be leaked outside of handlers. lol_html_text_chunk_content_t lol_html_text_chunk_content_get(const lol_html_text_chunk_t *chunk); // Inserts the content string before the text chunk either as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_text_chunk_before(lol_html_text_chunk_t *chunk, const char *content, size_t content_len, bool is_html); // Inserts the content string after the text chunk either as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_text_chunk_after(lol_html_text_chunk_t *chunk, const char *content, size_t content_len, bool is_html); // Replace the text chunk with the content of the string which is interpreted // either as raw text or as HTML. // // Content should be a valid UTF8-string. // // Returns 0 in case of success and -1 otherwise. The actual error message // can be obtained using `lol_html_take_last_error` function. int lol_html_text_chunk_replace(lol_html_text_chunk_t *chunk, const char *content, size_t content_len, bool is_html); // Removes the text chunk. void lol_html_text_chunk_remove(lol_html_text_chunk_t *chunk); // Returns `true` if the text chunk has been removed. bool lol_html_text_chunk_is_removed(const lol_html_text_chunk_t *chunk); // Returns `true` if the chunk is last in the current text node. // `text_chunk` must be valid and non-`NULL`. // Returns `_Bool`. // // Calls [`TextChunk::last_in_text_node`]. bool lol_html_text_chunk_is_last_in_text_node(lol_html_text_chunk_t *text_chunk); // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `text_chunk` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. // // Calls [`TextChunk::streaming_before`]. int lol_html_text_chunk_streaming_before(lol_html_text_chunk_t *text_chunk, lol_html_streaming_handler_t *streaming_writer); // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `text_chunk` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. // // Calls [`TextChunk::streaming_after`]. int lol_html_text_chunk_streaming_after(lol_html_text_chunk_t *text_chunk, lol_html_streaming_handler_t *streaming_writer); // The [`CStreamingHandler`] contains callbacks that will be called // when the content needs to be written. // // `streaming_writer` is copied immediately, and doesn't have a stable address. // `streaming_writer` may be used from another thread (`Send`), but it's only going // to be used by one thread at a time (`!Sync`). // // `text_chunk` must be valid and non-`NULL`. // If `streaming_writer` is `NULL`, an error will be reported. // // Returns 0 on success. // // Calls [`TextChunk::streaming_replace`]. int lol_html_text_chunk_streaming_replace(lol_html_text_chunk_t *text_chunk, lol_html_streaming_handler_t *streaming_writer); // Returns [`SourceLocationBytes`]. // // `text_chunk` must be valid and non-`NULL`. lol_html_source_location_bytes_t lol_html_text_chunk_source_location_bytes(lol_html_text_chunk_t *text_chunk); // Attaches custom user data to the text chunk. // // The same text chunk can be passed to multiple handlers if it has been // captured by multiple selectors. It might be handy to store some processing // state on the chunk, so it can be shared between handlers. void lol_html_text_chunk_user_data_set(lol_html_text_chunk_t *chunk, void *user_data); // Returns user data attached to the text chunk. void *lol_html_text_chunk_user_data_get(const lol_html_text_chunk_t *chunk); #if defined(__cplusplus) } // extern C #endif #endif // LOL_HTML_H ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/comment.rs ================================================ use super::*; #[no_mangle] pub unsafe extern "C" fn lol_html_comment_text_get(comment: *const Comment) -> Str { Str::new(to_ref!(comment).text()) } #[no_mangle] pub unsafe extern "C" fn lol_html_comment_text_set( comment: *mut Comment, text: *const c_char, text_len: size_t, ) -> c_int { let comment = to_ref_mut!(comment); let text = unwrap_or_ret_err_code! { to_str!(text, text_len) }; unwrap_or_ret_err_code! { comment.set_text(text) }; 0 } impl_content_mutation_handlers! { comment: Comment [ /// Inserts the content string before the comment either as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_comment_before => before, /// Inserts the content string after the comment either as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_comment_after => after, /// Replace the comment with the content of the string which is interpreted /// either as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_comment_replace => replace, /// Removes the comment. @VOID lol_html_comment_remove => remove, /// Returns `true` if the comment has been removed. @BOOL lol_html_comment_is_removed => removed, @STREAM lol_html_comment_streaming_before => streaming_before, @STREAM lol_html_comment_streaming_after => streaming_after, @STREAM lol_html_comment_streaming_replace => streaming_replace, lol_html_comment_source_location_bytes => source_location_bytes, ] } /// Attaches custom user data to the comment. /// /// The same comment can be passed to multiple handlers if it has been /// captured by multiple selectors. It might be handy to store some /// processing state on the comment, so it can be shared between handlers. #[no_mangle] pub unsafe extern "C" fn lol_html_comment_user_data_set( comment: *mut Comment, user_data: *mut c_void, ) { to_ref_mut!(comment).set_user_data(user_data); } #[no_mangle] pub unsafe extern "C" fn lol_html_comment_user_data_get(comment: *const Comment) -> *mut c_void { get_user_data!(comment) } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/doctype.rs ================================================ use super::*; #[no_mangle] pub unsafe extern "C" fn lol_html_doctype_name_get(doctype: *const Doctype) -> Str { Str::from_opt(to_ref!(doctype).name()) } #[no_mangle] pub unsafe extern "C" fn lol_html_doctype_public_id_get(doctype: *const Doctype) -> Str { Str::from_opt(to_ref!(doctype).public_id()) } #[no_mangle] pub unsafe extern "C" fn lol_html_doctype_system_id_get(doctype: *const Doctype) -> Str { Str::from_opt(to_ref!(doctype).system_id()) } #[no_mangle] pub unsafe extern "C" fn lol_html_doctype_user_data_set( doctype: *mut Doctype, user_data: *mut c_void, ) { to_ref_mut!(doctype).set_user_data(user_data); } #[no_mangle] pub unsafe extern "C" fn lol_html_doctype_user_data_get(doctype: *const Doctype) -> *mut c_void { get_user_data!(doctype) } impl_content_mutation_handlers! { doctype: Doctype [ /// Removes the doctype. @VOID lol_html_doctype_remove => remove, /// Returns `true` if the doctype has been removed. @BOOL lol_html_doctype_is_removed => removed, lol_html_doctype_source_location_bytes => source_location_bytes, ] } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/document_end.rs ================================================ use super::*; impl_content_mutation_handlers! { doc_end: DocumentEnd [ /// Inserts the content at the end of the document, either as raw text or as HTML. /// /// The content should be a valid UTF-8 string. /// /// Returns 0 if successful, and -1 otherwise. The actual error message /// can be obtained using the `lol_html_take_last_error` function. lol_html_doc_end_append => append, ] } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/element.rs ================================================ use super::*; use std::slice::Iter; /// Returns the tag name of the element. #[no_mangle] pub unsafe extern "C" fn lol_html_element_tag_name_get(element: *const Element) -> Str { let element = to_ref!(element); Str::new(element.tag_name()) } /// Returns the tag name of the element, preserving its case. #[no_mangle] pub unsafe extern "C" fn lol_html_element_tag_name_get_preserve_case( element: *const Element, ) -> Str { let element = to_ref!(element); Str::new(element.tag_name_preserve_case()) } /// Sets the tag name of the element. /// /// Name should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. #[no_mangle] pub unsafe extern "C" fn lol_html_element_tag_name_set( element: *mut Element, name: *const c_char, name_len: size_t, ) -> c_int { let element = to_ref_mut!(element); let name = unwrap_or_ret_err_code! { to_str!(name, name_len) }; unwrap_or_ret_err_code! { element.set_tag_name(name) }; 0 } /// Returns the namespace URI of the element. /// /// NOTE: This method returns static zero-terminated C string, so it don't /// need to be freed. #[no_mangle] pub unsafe extern "C" fn lol_html_element_namespace_uri_get( element: *mut Element, ) -> *const c_char { let element = to_ref!(element); match element.namespace_uri() { "http://www.w3.org/1999/xhtml" => static_c_str!("http://www.w3.org/1999/xhtml"), "http://www.w3.org/2000/svg" => static_c_str!("http://www.w3.org/2000/svg"), "http://www.w3.org/1998/Math/MathML" => static_c_str!("http://www.w3.org/1998/Math/MathML"), _ => unreachable!("Unknown namespace URI"), } } /// Returns the iterator over the element attributes. /// /// WARNING: The iterator is valid only during the handler execution and /// should never be leaked outside of it. /// /// Use `lol_html_attributes_iterator_free` function to deallocate /// returned iterator. #[no_mangle] pub unsafe extern "C" fn lol_html_attributes_iterator_get<'r, 't>( element: *const Element<'r, 't>, ) -> *mut Iter<'r, Attribute<'t>> { let attributes = to_ref!(element).attributes(); to_ptr_mut(attributes.iter()) } // Advances the iterator and returns next attribute. // // Returns NULL if iterator has been exhausted. // // WARNING: Returned attribute is valid only during the handler // execution and should never be leaked outside of it. #[no_mangle] pub unsafe extern "C" fn lol_html_attributes_iterator_next<'t>( iterator: *mut Iter<'_, Attribute<'t>>, ) -> *const Attribute<'t> { let iterator = to_ref_mut!(iterator); match iterator.next() { Some(attr) => attr, None => ptr::null(), } } // Frees the memory held by the attribute iterator. #[no_mangle] pub unsafe extern "C" fn lol_html_attributes_iterator_free(iterator: *mut Iter) { drop(to_box!(iterator)); } /// Returns the attribute name. #[no_mangle] pub unsafe extern "C" fn lol_html_attribute_name_get(attribute: *const Attribute) -> Str { let attribute = to_ref!(attribute); Str::new(attribute.name()) } /// Returns the attribute name, preserving its case. #[no_mangle] pub unsafe extern "C" fn lol_html_attribute_name_get_preserve_case( attribute: *const Attribute, ) -> Str { let attribute = to_ref!(attribute); Str::new(attribute.name_preserve_case()) } /// Returns the attribute value. #[no_mangle] pub unsafe extern "C" fn lol_html_attribute_value_get(attribute: *const Attribute) -> Str { let attribute = to_ref!(attribute); Str::new(attribute.value()) } /// Returns the attribute value. The `data` field will be NULL if an attribute with the given name /// doesn't exist on the element. /// /// Name should be a valid UTF8-string. /// /// If the provided name is invalid UTF8-string the function returns NULL as well. /// Therefore one should always check `lol_html_take_last_error` result after the call. #[no_mangle] pub unsafe extern "C" fn lol_html_element_get_attribute( element: *const Element, name: *const c_char, name_len: size_t, ) -> Str { let element = to_ref!(element); let name = unwrap_or_ret!(to_str!(name, name_len), Str::from_opt(None)); Str::from_opt(element.get_attribute(name)) } /// Returns 1 if element has attribute with the given name, and 0 otherwise. /// Returns -1 in case of an error. /// /// Name should be a valid UTF8-string. #[no_mangle] pub unsafe extern "C" fn lol_html_element_has_attribute( element: *const Element, name: *const c_char, name_len: size_t, ) -> c_int { let element = to_ref!(element); let name = unwrap_or_ret_err_code! { to_str!(name, name_len) }; if element.has_attribute(name) { 1 } else { 0 } } /// Updates the attribute value if attribute with the given name already exists on /// the element, or creates adds new attribute with given name and value otherwise. /// /// Name and value should be valid UTF8-strings. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. #[no_mangle] pub unsafe extern "C" fn lol_html_element_set_attribute( element: *mut Element, name: *const c_char, name_len: size_t, value: *const c_char, value_len: size_t, ) -> c_int { let element = to_ref_mut!(element); let name = unwrap_or_ret_err_code! { to_str!(name, name_len) }; let value = unwrap_or_ret_err_code! { to_str!(value, value_len) }; unwrap_or_ret_err_code! { element.set_attribute(name, value) }; 0 } /// Removes the attribute with the given name from the element. /// /// Name should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. #[no_mangle] pub unsafe extern "C" fn lol_html_element_remove_attribute( element: *mut Element, name: *const c_char, name_len: size_t, ) -> c_int { let element = to_ref_mut!(element); let name = unwrap_or_ret_err_code! { to_str!(name, name_len) }; element.remove_attribute(name); 0 } impl_content_mutation_handlers! { element: Element [ /// Inserts the content string right after the element's start tag /// either as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_element_prepend => prepend, /// Inserts the content string right before the element's end tag /// either as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_element_append => append, /// Inserts the content string before the element either as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_element_before => before, /// Inserts the content string right after the element's end tag as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_element_after => after, /// Sets either text or HTML inner content of the element. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_element_set_inner_content => set_inner_content, /// Replaces the element with the provided text or HTML content. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_element_replace => replace, /// Removes the element. @VOID lol_html_element_remove => remove, /// Removes the element, but leaves its inner content intact. @VOID lol_html_element_remove_and_keep_content => remove_and_keep_content, /// Returns `true` if the element has been removed. @BOOL lol_html_element_is_removed => removed, /// Whether the tag syntactically ends with `/>`. In HTML content this is purely a decorative, unnecessary, and has no effect of any kind. /// /// The `/>` syntax only affects parsing of elements in foreign content (SVG and MathML). /// It will never close any HTML tags that aren't already defined as void in HTML. /// /// This function only reports the parsed syntax, and will not report which elements are actually void in HTML. /// Use `lol_html_element_can_have_content` to check if the element is non-void. /// /// If the `/` is part of an unquoted attribute, it's not parsed as the self-closing syntax. @BOOL lol_html_element_is_self_closing => is_self_closing, /// Whether the element can have inner content. Returns `true` unless the element is an [HTML void /// element](https://html.spec.whatwg.org/multipage/syntax.html#void-elements) or has a /// self-closing tag (eg, ``). @BOOL lol_html_element_can_have_content => can_have_content, @STREAM lol_html_element_streaming_prepend => streaming_prepend, @STREAM lol_html_element_streaming_append => streaming_append, @STREAM lol_html_element_streaming_before => streaming_before, @STREAM lol_html_element_streaming_after => streaming_after, @STREAM lol_html_element_streaming_set_inner_content => streaming_set_inner_content, @STREAM lol_html_element_streaming_replace => streaming_replace, lol_html_element_source_location_bytes => source_location_bytes, ] } /// Attaches custom user data to the element. /// /// The same element can be passed to multiple handlers if it has been /// captured by multiple selectors. It might be handy to store some processing /// state on the element, so it can be shared between handlers. #[no_mangle] pub unsafe extern "C" fn lol_html_element_user_data_set( element: *mut Element, user_data: *mut c_void, ) { to_ref_mut!(element).set_user_data(user_data); } /// Returns user data attached to the element. #[no_mangle] pub unsafe extern "C" fn lol_html_element_user_data_get(element: *mut Element) -> *mut c_void { get_user_data!(element) } type EndTagHandler = unsafe extern "C" fn(*mut EndTag, *mut c_void) -> RewriterDirective; /// Adds content handlers to the builder for the end tag of the given element. /// /// Subsequent calls to the method on the same element adds new handler. /// They will run in the order in which they were registered. /// /// The handler can optionally have associated user data which will be /// passed to the handler on each invocation along with the rewritable /// unit argument. /// /// If the handler returns LOL_HTML_STOP directive then rewriting /// stops immediately and `write()` or `end()` of the rewriter methods /// return an error code. /// /// Not all elements (for example, `
`) support end tags. If this function is /// called on such an element, this function returns an error code as described /// below. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. /// /// WARNING: Pointers passed to handlers are valid only during the /// handler execution. So they should never be leaked outside of handlers. #[no_mangle] pub unsafe extern "C" fn lol_html_element_add_end_tag_handler( element: *mut Element, handler: EndTagHandler, user_data: *mut c_void, ) -> c_int { let element = to_ref_mut!(element); let handlers = unwrap_or_ret_err_code! { element.end_tag_handlers().ok_or("No end tag.") }; handlers.push(Box::new(move |end_tag| { match unsafe { handler(end_tag, user_data) } { RewriterDirective::Continue => Ok(()), RewriterDirective::Stop => Err("The rewriter has been stopped.".into()), } })); 0 } /// Clears the handlers that would run on the end tag of the given element. #[no_mangle] pub unsafe extern "C" fn lol_html_element_clear_end_tag_handlers(element: *mut Element) { let element = to_ref_mut!(element); if let Some(handlers) = element.end_tag_handlers() { handlers.clear(); } } impl_content_mutation_handlers! { end_tag: EndTag [ /// Inserts the content string before the element's end tag either as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_end_tag_before => before, /// Inserts the content string right after the element's end tag as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_end_tag_after => after, lol_html_end_tag_replace => replace, /// Removes the end tag. @VOID lol_html_end_tag_remove => remove, @STREAM lol_html_end_tag_streaming_before => streaming_before, @STREAM lol_html_end_tag_streaming_after => streaming_after, @STREAM lol_html_end_tag_streaming_replace => streaming_replace, lol_html_end_tag_source_location_bytes => source_location_bytes, ] } /// Returns the end tag name. #[no_mangle] pub unsafe extern "C" fn lol_html_end_tag_name_get(end_tag: *mut EndTag) -> Str { let tag = to_ref_mut!(end_tag); Str::new(tag.name()) } /// Returns the end tag name, preserving its case. #[no_mangle] pub unsafe extern "C" fn lol_html_end_tag_name_get_preserve_case(end_tag: *mut EndTag) -> Str { let tag = to_ref_mut!(end_tag); Str::new(tag.name_preserve_case()) } /// Sets the tag name of the end tag. /// /// Name should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. #[no_mangle] pub unsafe extern "C" fn lol_html_end_tag_name_set( end_tag: *mut EndTag, name: *const c_char, len: size_t, ) -> c_int { let tag = to_ref_mut!(end_tag); let name = unwrap_or_ret_err_code! { to_str!(name, len) }; tag.set_name_str(name.to_string()); 0 } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/errors.rs ================================================ use super::*; use std::error::Error; thread_local! { pub static LAST_ERROR: RefCell>> = RefCell::new(None); } #[no_mangle] pub extern "C" fn lol_html_take_last_error() -> Str { let err = LAST_ERROR.with(|e| e.borrow_mut().take()); Str::from_opt(err.map(|e| e.to_string())) } #[derive(Error, Debug, Eq, PartialEq, Copy, Clone)] pub enum CStreamingHandlerError { #[error("Not all fields of the struct were initialized")] Uninitialized, #[error("write_all_callback reported error: {0}")] HandlerError(c_int), } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/lib.rs ================================================ #![allow(clippy::missing_safety_doc)] pub use crate::streaming::CStreamingHandler; use libc::{c_char, c_int, c_void, size_t}; use lol_html::html_content::*; use lol_html::*; use std::cell::RefCell; use std::{ptr, slice, str}; use thiserror::Error; #[inline] fn to_ptr_mut(val: T) -> *mut T { Box::into_raw(Box::new(val)) } // NOTE: abort the thread if we receive NULL where unexpected macro_rules! assert_not_null { ($var:ident) => { assert!(!$var.is_null(), "{} is NULL", stringify!($var)); }; } // NOTE: all these utilities are macros so we can propagate the variable // name to the null pointer assertion. macro_rules! to_ref { ($ptr:ident) => {{ unsafe { $ptr.as_ref().expect(concat!(stringify!($var), " is NULL")) } }}; } macro_rules! to_ref_mut { ($ptr:ident) => {{ unsafe { $ptr.as_mut().expect(concat!(stringify!($var), " is NULL")) } }}; } macro_rules! to_box { ($ptr:ident) => {{ assert_not_null!($ptr); unsafe { Box::from_raw($ptr) } }}; } macro_rules! to_bytes { ($data:ident, $len:ident) => {{ assert_not_null!($data); unsafe { slice::from_raw_parts($data as *const u8, $len) } }}; } macro_rules! to_str { ($data:ident, $len:ident) => { str::from_utf8(to_bytes!($data, $len)).into() }; } macro_rules! static_c_str { ($s:expr) => { concat!($s, "\0").as_ptr() as *const c_char }; } macro_rules! unwrap_or_ret { ($expr:expr, $ret_val:expr) => { match $expr { Ok(v) => v, Err(err) => { crate::errors::LAST_ERROR.with(|e| *e.borrow_mut() = Some(err.into())); return $ret_val; } } }; } macro_rules! unwrap_or_ret_err_code { ($expr:expr) => { unwrap_or_ret!($expr, -1) }; } macro_rules! unwrap_or_ret_null { ($expr:expr) => { unwrap_or_ret!($expr, ptr::null_mut()) }; } macro_rules! impl_content_mutation_handlers { ($name:ident: $typ:ty [ $($(#[$meta:meta])* $(@$kind:ident)? $fn_name:ident => $method:ident),+$(,)? ]) => { $( // stable Rust can't concatenate idents, so fn_name must be written out manually, // but it is possible to compare concatenated strings. #[cfg(debug_assertions)] const _: () = { let expected_fn_name_prefix = concat!("lol_html_", stringify!($name), "_").as_bytes(); let fn_name = stringify!($fn_name).as_bytes(); // removed vs is_removed prevents exact comparison assert!(fn_name.len() >= expected_fn_name_prefix.len() + (stringify!($method).len()), stringify!($fn_name)); let mut i = 0; while i < expected_fn_name_prefix.len() { assert!(expected_fn_name_prefix[i] == fn_name[i], stringify!($fn_name)); i += 1; } }; impl_content_mutation_handlers! { IMPL $($kind)? $name: $typ, $(#[$meta])* $fn_name => $method } )+ }; (IMPL $name:ident: $typ:ty, $fn_name:ident => source_location_bytes) => { /// Returns [`SourceLocationBytes`]. /// #[doc = concat!(" `", stringify!($name), "` must be valid and non-`NULL`.")] #[no_mangle] pub unsafe extern "C" fn $fn_name($name: *mut $typ) -> SourceLocationBytes { let loc = to_ref_mut!($name).source_location().bytes(); SourceLocationBytes { start: loc.start, end: loc.end, } } }; (IMPL $name:ident: $typ:ty, $(#[$meta:meta])* $fn_name:ident => $method:ident) => { $(#[$meta])* /// The `content` must be a valid UTF-8 string. It's copied immediately. /// If `is_html` is `true`, then the `content` will be written without HTML-escaping. /// #[doc = concat!(" `", stringify!($name), "` must be valid and non-`NULL`.")] /// If `content` is `NULL`, an error will be reported. /// /// Returns 0 on success. /// #[doc = concat!(" Calls [`", stringify!($typ), "::", stringify!($method), "`].")] #[no_mangle] pub unsafe extern "C" fn $fn_name( $name: *mut $typ, content: *const c_char, content_len: size_t, is_html: bool, ) -> c_int { content_insertion_fn_body! { $name.$method(content, content_len, is_html) } } }; (IMPL STREAM $name:ident: $typ:ty, $(#[$meta:meta])* $fn_name:ident => $method:ident) => { $(#[$meta])* /// The [`CStreamingHandler`] contains callbacks that will be called /// when the content needs to be written. /// /// `streaming_writer` is copied immediately, and doesn't have a stable address. /// `streaming_writer` may be used from another thread (`Send`), but it's only going /// to be used by one thread at a time (`!Sync`). /// #[doc = concat!(" `", stringify!($name), "` must be valid and non-`NULL`.")] /// If `streaming_writer` is `NULL`, an error will be reported. /// /// Returns 0 on success. /// #[doc = concat!(" Calls [`", stringify!($typ), "::", stringify!($method), "`].")] #[no_mangle] pub unsafe extern "C" fn $fn_name( $name: *mut $typ, streaming_writer: *mut CStreamingHandler, ) -> c_int { content_insertion_fn_body! { $name.$method(streaming_writer) } } }; (IMPL VOID $name:ident: $typ:ty, $(#[$meta:meta])* $fn_name:ident => $method:ident) => { $(#[$meta])* #[doc = concat!(" `", stringify!($name), "` must be valid and non-`NULL`.")] /// #[doc = concat!(" Calls [`", stringify!($typ), "::", stringify!($method), "`].")] #[no_mangle] pub unsafe extern "C" fn $fn_name( $name: *mut $typ, ) { to_ref_mut!($name).$method(); } }; (IMPL BOOL $name:ident: $typ:ty, $(#[$meta:meta])* $fn_name:ident => $method:ident) => { $(#[$meta])* #[doc = concat!(" `", stringify!($name), "` must be valid and non-`NULL`.")] /// Returns `_Bool`. /// #[doc = concat!(" Calls [`", stringify!($typ), "::", stringify!($method), "`].")] #[no_mangle] pub unsafe extern "C" fn $fn_name( $name: *mut $typ, ) -> bool { to_ref_mut!($name).$method() } }; } macro_rules! content_insertion_fn_body { ($target:ident.$method:ident($content:ident, $content_len:ident, $is_html:ident)) => {{ let target = to_ref_mut!($target); let content = unwrap_or_ret_err_code! { to_str!($content, $content_len) }; target.$method( content, if $is_html { ContentType::Html } else { ContentType::Text }, ); 0 }}; ($target:ident.$method:ident($handler:expr)) => {{ let handler_ptr: *mut CStreamingHandler = $handler; if unsafe { handler_ptr.as_ref() }.is_none() || !handler_ptr.as_ref().unwrap().reserved.is_null() { // we can't even safely call drop callback on this return -1; } // Taking ownership of the CStreamingHandler let handler: Box = Box::new(unsafe { handler_ptr.read() }); if handler.write_all_callback.is_none() { return -1; } if let Some(target) = unsafe { $target.as_mut() } { target.$method(handler); 0 } else { -1 } }}; } macro_rules! get_user_data { ($unit:ident) => { to_ref!($unit) .user_data() .downcast_ref::<*mut c_void>() .map(|d| *d) .unwrap_or(ptr::null_mut()) }; } pub mod comment; pub mod doctype; pub mod document_end; pub mod element; pub mod errors; pub mod rewriter; pub mod rewriter_builder; pub mod selector; pub mod streaming; pub mod string; pub mod text_chunk; pub use self::string::Str; /// `size_t` byte offsets from the start of the input document #[repr(C)] pub struct SourceLocationBytes { pub start: usize, pub end: usize, } // NOTE: prevent dead code from complaining about enum // never being constructed in the Rust code. pub use self::rewriter_builder::RewriterDirective; /// An error that occurs if incorrect [`encoding`] label was provided in [`Settings`]. /// /// [`encoding`]: ../struct.Settings.html#structfield.encoding /// [`Settings`]: ../struct.Settings.html #[derive(Error, Debug, PartialEq, Copy, Clone)] pub enum EncodingError { /// The provided value doesn't match any of the [labels specified in the standard]. /// /// [labels specified in the standard]: https://encoding.spec.whatwg.org/#names-and-labels #[error("Unknown character encoding has been provided.")] UnknownEncoding, /// The provided label is for one of the non-ASCII-compatible encodings (`UTF-16LE`, `UTF-16BE`, /// `ISO-2022-JP` and `replacement`). These encodings are not supported. #[error("Expected ASCII-compatible encoding.")] NonAsciiCompatibleEncoding, } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/rewriter.rs ================================================ use super::rewriter_builder::HtmlRewriterBuilder; use super::*; use libc::c_void; // NOTE: we use `ExternOutputSink` proxy type, because we need an // existential type parameter for the `HtmlRewriter` and FnMut can't // be used as such since it's a trait. pub struct ExternOutputSink { handler: unsafe extern "C" fn(*const c_char, size_t, *mut c_void), user_data: *mut c_void, } /// This is a wrapper around `lol_html::HtmlRewriter` which allows /// use after the rewriter itself is dropped. pub struct HtmlRewriter(Option>); impl ExternOutputSink { #[inline] fn new( handler: unsafe extern "C" fn(*const c_char, size_t, *mut c_void), user_data: *mut c_void, ) -> Self { Self { handler, user_data } } } impl OutputSink for ExternOutputSink { #[inline] fn handle_chunk(&mut self, chunk: &[u8]) { let chunk_len = chunk.len(); let chunk = chunk.as_ptr().cast::(); unsafe { (self.handler)(chunk, chunk_len, self.user_data) }; } } #[no_mangle] pub unsafe extern "C" fn lol_html_rewriter_build( builder: *mut HtmlRewriterBuilder, encoding: *const c_char, encoding_len: size_t, memory_settings: MemorySettings, output_sink: unsafe extern "C" fn(*const c_char, size_t, *mut c_void), output_sink_user_data: *mut c_void, strict: bool, ) -> *mut HtmlRewriter { let builder = to_ref!(builder); let handlers = builder.get_safe_handlers(); let maybe_encoding = encoding_rs::Encoding::for_label_no_replacement(to_bytes!(encoding, encoding_len)); let encoding = unwrap_or_ret_null! { maybe_encoding.ok_or(EncodingError::UnknownEncoding) }; let settings = Settings { element_content_handlers: handlers.element, document_content_handlers: handlers.document, encoding: unwrap_or_ret_null! { encoding.try_into().or(Err(EncodingError::NonAsciiCompatibleEncoding)) }, memory_settings, strict, enable_esi_tags: false, adjust_charset_on_meta_tag: false, }; let output_sink = ExternOutputSink::new(output_sink, output_sink_user_data); let rewriter = lol_html::HtmlRewriter::new(settings, output_sink); to_ptr_mut(HtmlRewriter(Some(rewriter))) } #[no_mangle] pub unsafe extern "C" fn unstable_lol_html_rewriter_build_with_esi_tags( builder: *mut HtmlRewriterBuilder, encoding: *const c_char, encoding_len: size_t, memory_settings: MemorySettings, output_sink: unsafe extern "C" fn(*const c_char, size_t, *mut c_void), output_sink_user_data: *mut c_void, strict: bool, ) -> *mut HtmlRewriter { let builder = to_ref!(builder); let handlers = builder.get_safe_handlers(); let maybe_encoding = encoding_rs::Encoding::for_label_no_replacement(to_bytes!(encoding, encoding_len)); let encoding = unwrap_or_ret_null! { maybe_encoding.ok_or(EncodingError::UnknownEncoding) }; let settings = Settings { element_content_handlers: handlers.element, document_content_handlers: handlers.document, encoding: unwrap_or_ret_null! { encoding.try_into().or(Err(EncodingError::NonAsciiCompatibleEncoding)) }, memory_settings, strict, enable_esi_tags: true, adjust_charset_on_meta_tag: false, }; let output_sink = ExternOutputSink::new(output_sink, output_sink_user_data); let rewriter = lol_html::HtmlRewriter::new(settings, output_sink); to_ptr_mut(HtmlRewriter(Some(rewriter))) } #[no_mangle] pub unsafe extern "C" fn lol_html_rewriter_write( rewriter: *mut HtmlRewriter, chunk: *const c_char, chunk_len: size_t, ) -> c_int { let chunk = to_bytes!(chunk, chunk_len); let rewriter = to_ref_mut!(rewriter) .0 .as_mut() .expect("cannot call `lol_html_rewriter_write` after calling `end()`"); unwrap_or_ret_err_code! { rewriter.write(chunk) }; 0 } #[no_mangle] pub unsafe extern "C" fn lol_html_rewriter_end(rewriter: *mut HtmlRewriter) -> c_int { let rewriter = to_ref_mut!(rewriter) .0 .take() // Using `take()` allows calling `free()` afterwards (it will be a no-op). .expect("cannot call `lol_html_rewriter_end` after calling `end()`"); unwrap_or_ret_err_code! { rewriter.end() }; 0 } #[no_mangle] pub unsafe extern "C" fn lol_html_rewriter_free(rewriter: *mut HtmlRewriter) { // SAFETY: `to_box` includes a check that `rewriter` is non-null. // The caller is required to ensure that `rewriter` is aligned and that `free` has not been called before. // NOTE: if `end()` was called before, it is valid (but not recommended) to call `free()` more than once. drop(to_box!(rewriter)); } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/rewriter_builder.rs ================================================ use super::*; use libc::c_void; use std::borrow::Cow; #[repr(C)] pub enum RewriterDirective { Continue, Stop, } type ElementHandler = unsafe extern "C" fn(*mut Element, *mut c_void) -> RewriterDirective; type DoctypeHandler = unsafe extern "C" fn(*mut Doctype, *mut c_void) -> RewriterDirective; type CommentsHandler = unsafe extern "C" fn(*mut Comment, *mut c_void) -> RewriterDirective; type TextHandler = unsafe extern "C" fn(*mut TextChunk, *mut c_void) -> RewriterDirective; type DocumentEndHandler = unsafe extern "C" fn(*mut DocumentEnd, *mut c_void) -> RewriterDirective; struct ExternHandler { func: Option, user_data: *mut c_void, } impl ExternHandler { const fn new(func: Option, user_data: *mut c_void) -> Self { Self { func, user_data } } } macro_rules! add_handler { ($handlers:ident, $el_ty:ident, $self:ident.$ty:ident) => {{ if let Some(handler) = $self.$ty.func { // NOTE: the closure actually holds a reference to the content // handler object, but since we pass the object to the C side this // ownership information gets erased. // It's not a problem since handler is an extern static function that // will remain intact even if Rust-side builder object gets freed. // However, it's not a case for the user data pointer, it might become // invalid if content handlers object that holds it gets freed before // a handler invocation. Therefore, we close on a local variable instead // of structure field. let user_data = $self.$ty.user_data; $handlers = $handlers.$ty( move |arg: &mut $el_ty| match unsafe { handler(arg, user_data) } { RewriterDirective::Continue => Ok(()), RewriterDirective::Stop => Err("The rewriter has been stopped.".into()), }, ); } }}; } pub struct ExternDocumentContentHandlers { doctype: ExternHandler, comments: ExternHandler, text: ExternHandler, end: ExternHandler, } impl ExternDocumentContentHandlers { #[must_use] pub fn as_safe_document_content_handlers(&self) -> DocumentContentHandlers<'_> { let mut handlers = DocumentContentHandlers::default(); add_handler!(handlers, Doctype, self.doctype); add_handler!(handlers, Comment, self.comments); add_handler!(handlers, TextChunk, self.text); add_handler!(handlers, DocumentEnd, self.end); handlers } } pub struct ExternElementContentHandlers { element: ExternHandler, comments: ExternHandler, text: ExternHandler, } impl ExternElementContentHandlers { #[must_use] pub fn as_safe_element_content_handlers(&self) -> ElementContentHandlers<'_> { let mut handlers = ElementContentHandlers::default(); add_handler!(handlers, Element, self.element); add_handler!(handlers, Comment, self.comments); add_handler!(handlers, TextChunk, self.text); handlers } } pub struct SafeContentHandlers<'b> { pub document: Vec>, pub element: Vec<(Cow<'b, Selector>, ElementContentHandlers<'b>)>, } #[derive(Default)] pub struct HtmlRewriterBuilder { document_content_handlers: Vec, element_content_handlers: Vec<(&'static Selector, ExternElementContentHandlers)>, } impl HtmlRewriterBuilder { #[must_use] pub fn get_safe_handlers(&self) -> SafeContentHandlers<'_> { SafeContentHandlers { document: self .document_content_handlers .iter() .map(|h| h.as_safe_document_content_handlers()) .collect(), element: self .element_content_handlers .iter() .map(|(s, h)| (Cow::Borrowed(*s), h.as_safe_element_content_handlers())) .collect(), } } } #[no_mangle] pub unsafe extern "C" fn lol_html_rewriter_builder_new() -> *mut HtmlRewriterBuilder { to_ptr_mut(HtmlRewriterBuilder::default()) } #[no_mangle] pub unsafe extern "C" fn lol_html_rewriter_builder_add_document_content_handlers( builder: *mut HtmlRewriterBuilder, doctype_handler: Option, doctype_handler_user_data: *mut c_void, comments_handler: Option, comments_handler_user_data: *mut c_void, text_handler: Option, text_handler_user_data: *mut c_void, document_end_handler: Option, document_end_handler_user_data: *mut c_void, ) { let builder = to_ref_mut!(builder); let handlers = ExternDocumentContentHandlers { doctype: ExternHandler::new(doctype_handler, doctype_handler_user_data), comments: ExternHandler::new(comments_handler, comments_handler_user_data), text: ExternHandler::new(text_handler, text_handler_user_data), end: ExternHandler::new(document_end_handler, document_end_handler_user_data), }; builder.document_content_handlers.push(handlers); } #[no_mangle] pub unsafe extern "C" fn lol_html_rewriter_builder_add_element_content_handlers( builder: *mut HtmlRewriterBuilder, selector: *const Selector, element_handler: Option, element_handler_user_data: *mut c_void, comments_handler: Option, comments_handler_user_data: *mut c_void, text_handler: Option, text_handler_user_data: *mut c_void, ) -> c_int { let selector = to_ref!(selector); let builder = to_ref_mut!(builder); let handlers = ExternElementContentHandlers { element: ExternHandler::new(element_handler, element_handler_user_data), comments: ExternHandler::new(comments_handler, comments_handler_user_data), text: ExternHandler::new(text_handler, text_handler_user_data), }; builder.element_content_handlers.push((selector, handlers)); 0 } #[no_mangle] pub unsafe extern "C" fn lol_html_rewriter_builder_free(builder: *mut HtmlRewriterBuilder) { drop(to_box!(builder)); } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/selector.rs ================================================ use super::*; #[no_mangle] pub unsafe extern "C" fn lol_html_selector_parse( selector: *const c_char, selector_len: size_t, ) -> *mut Selector { let selector = unwrap_or_ret_null! { to_str!(selector, selector_len) }; let selector = unwrap_or_ret_null! { selector.parse::() }; to_ptr_mut(selector) } #[no_mangle] pub unsafe extern "C" fn lol_html_selector_free(selector: *mut Selector) { drop(to_box!(selector)); } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/streaming.rs ================================================ use super::*; use crate::errors::CStreamingHandlerError; use lol_html::html_content::StreamingHandler; use lol_html::html_content::StreamingHandlerSink; /// Opaque type from C's perspective pub type CStreamingHandlerSink<'tmp> = StreamingHandlerSink<'tmp>; /// Write another piece of UTF-8 data to the output. Returns `0` on success, and `-1` if it wasn't valid UTF-8. /// All pointers must be non-NULL. #[no_mangle] pub unsafe extern "C" fn lol_html_streaming_sink_write_str( sink: *mut CStreamingHandlerSink<'_>, string_utf8: *const c_char, string_utf8_len: size_t, is_html: bool, ) -> c_int { let sink = to_ref_mut!(sink); let content = unwrap_or_ret_err_code! { to_str!(string_utf8, string_utf8_len) }; let is_html = if is_html { ContentType::Html } else { ContentType::Text }; sink.write_str(content, is_html); 0 } /// [`StreamingHandlerSink::write_utf8_chunk`] /// /// Writes as much of the given UTF-8 fragment as possible, converting the encoding and HTML-escaping if `is_html` is `false`. /// /// The `bytes_utf8` doesn't need to be a complete UTF-8 string, as long as consecutive calls to this function create a valid UTF-8 string. /// Any incomplete UTF-8 sequence at the end of the content is buffered and flushed as soon as it's completed. /// /// Other functions like [`lol_html_streaming_sink_write_str`] should not be called after a /// `lol_html_streaming_sink_write_utf8_chunk` call with an incomplete UTF-8 sequence. /// /// Returns `0` on success, and `-1` if it wasn't valid UTF-8. /// All pointers must be non-`NULL`. #[no_mangle] pub unsafe extern "C" fn lol_html_streaming_sink_write_utf8_chunk( sink: *mut CStreamingHandlerSink<'_>, bytes_utf8: *const c_char, bytes_utf8_len: size_t, is_html: bool, ) -> c_int { let sink = to_ref_mut!(sink); let content = to_bytes!(bytes_utf8, bytes_utf8_len); let is_html = if is_html { ContentType::Html } else { ContentType::Text }; unwrap_or_ret_err_code! { sink.write_utf8_chunk(content, is_html) }; 0 } /// Safety: the user data and the callbacks must be safe to use from a different thread (e.g. can't rely on thread-local storage). /// /// It doesn't have to be `Sync`, it will be used only by one thread at a time. /// /// Handler functions copy this struct. It can (and should) be created on the stack. #[repr(C)] pub struct CStreamingHandler { /// Anything you like pub user_data: *mut c_void, /// Called when the handler is supposed to produce its output. Return `0` for success. /// The `sink` argument is guaranteed non-`NULL`. It is valid only for the duration of this call, and can only be used on the same thread. /// The sink is for [`lol_html_streaming_sink_write_str`] and [`lol_html_streaming_sink_write_utf8_chunk`]. /// `user_data` comes from this struct. /// `write_all_callback` must not be `NULL`. pub write_all_callback: Option< unsafe extern "C" fn(sink: &mut CStreamingHandlerSink<'_>, user_data: *mut c_void) -> c_int, >, /// Called exactly once, after the last use of this handler. /// `user_data` comes from this struct. /// May be `NULL`. pub drop_callback: Option, /// *Always* initialize to `NULL`. pub reserved: *mut c_void, } // It's up to C to obey this unsafe impl Send for CStreamingHandler {} impl StreamingHandler for CStreamingHandler { fn write_all( self: Box, sink: &mut StreamingHandlerSink<'_>, ) -> Result<(), Box<(dyn std::error::Error + Send + Sync)>> { if !self.reserved.is_null() { return Err(CStreamingHandlerError::Uninitialized.into()); } let cb = self .write_all_callback .ok_or(CStreamingHandlerError::Uninitialized)?; let res = unsafe { (cb)(sink, self.user_data) }; if res == 0 { Ok(()) } else { Err(CStreamingHandlerError::HandlerError(res).into()) } } } impl Drop for CStreamingHandler { fn drop(&mut self) { if let Some(cb) = self.drop_callback { unsafe { cb(self.user_data); } } } } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/string.rs ================================================ use super::*; // NOTE: we don't use CStr and CString as the transfer type because UTF8 // string comming from both sides can contain interior NULLs. #[repr(C)] pub struct Str { data: *const c_char, len: size_t, } impl Str { #[must_use] pub fn new(string: String) -> Self { Self { len: string.len(), data: Box::into_raw(string.into_boxed_str()) as *const c_char, } } /// Convert an `Option` to a C-style string. /// /// If `string` is `None`, `data` will be set to `NULL`. #[inline] #[must_use] pub fn from_opt(string: Option) -> Self { match string { Some(string) => Self::new(string), None => Self { data: ptr::null(), len: 0, }, } } } impl Drop for Str { fn drop(&mut self) { if self.data.is_null() { return; } let bytes = unsafe { slice::from_raw_parts_mut(self.data.cast_mut(), self.len) }; drop(unsafe { Box::from_raw(bytes) }); } } #[no_mangle] pub unsafe extern "C" fn lol_html_str_free(string: Str) { drop(string); } ================================================ FILE: runtime/fastly/crates/rust-lol-html/src/text_chunk.rs ================================================ use super::*; #[repr(C)] pub struct TextChunkContent { data: *const c_char, len: size_t, } impl TextChunkContent { fn new(chunk: &TextChunk) -> Self { let content = chunk.as_str(); Self { data: content.as_ptr().cast::(), len: content.len(), } } } /// Returns a fat pointer to the UTF8 representation of content of the chunk. /// /// If the chunk is last in the current text node then content can be an empty string. /// /// WARNING: The pointer is valid only during the handler execution and /// should never be leaked outside of handlers. #[no_mangle] pub unsafe extern "C" fn lol_html_text_chunk_content_get( chunk: *mut TextChunk, ) -> TextChunkContent { TextChunkContent::new(to_ref!(chunk)) } impl_content_mutation_handlers! { text_chunk: TextChunk [ /// Inserts the content string before the text chunk either as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_text_chunk_before => before, /// Inserts the content string after the text chunk either as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_text_chunk_after => after, /// Replace the text chunk with the content of the string which is interpreted /// either as raw text or as HTML. /// /// Content should be a valid UTF8-string. /// /// Returns 0 in case of success and -1 otherwise. The actual error message /// can be obtained using `lol_html_take_last_error` function. lol_html_text_chunk_replace => replace, /// Removes the text chunk. @VOID lol_html_text_chunk_remove => remove, /// Returns `true` if the text chunk has been removed. @BOOL lol_html_text_chunk_is_removed => removed, /// Returns `true` if the chunk is last in the current text node. @BOOL lol_html_text_chunk_is_last_in_text_node => last_in_text_node, @STREAM lol_html_text_chunk_streaming_before => streaming_before, @STREAM lol_html_text_chunk_streaming_after => streaming_after, @STREAM lol_html_text_chunk_streaming_replace => streaming_replace, lol_html_text_chunk_source_location_bytes => source_location_bytes, ] } /// Attaches custom user data to the text chunk. /// /// The same text chunk can be passed to multiple handlers if it has been /// captured by multiple selectors. It might be handy to store some processing /// state on the chunk, so it can be shared between handlers. #[no_mangle] pub unsafe extern "C" fn lol_html_text_chunk_user_data_set( chunk: *mut TextChunk, user_data: *mut c_void, ) { to_ref_mut!(chunk).set_user_data(user_data); } /// Returns user data attached to the text chunk. #[no_mangle] pub unsafe extern "C" fn lol_html_text_chunk_user_data_get(chunk: *const TextChunk) -> *mut c_void { get_user_data!(chunk) } ================================================ FILE: runtime/fastly/handler.cpp ================================================ #include "../StarlingMonkey/builtins/web/performance.h" #include "./builtins/fastly.h" #include "./builtins/fetch-event.h" #include "./host-api/fastly.h" #include "./host-api/host_api_fastly.h" #include "extension-api.h" #include "host_api.h" #include #include using fastly::fetch_event::FetchEvent; using std::chrono::duration_cast; using std::chrono::microseconds; using std::chrono::system_clock; namespace fastly::runtime { api::Engine *ENGINE; // Install corresponds to Wizer time, so we configure the engine here bool install(api::Engine *engine) { #if defined(JS_GC_ZEAL) && defined(FASTLY_GC_FREQUENCY) JS::SetGCZeal(engine->cx(), 2, FASTLY_GC_FREQUENCY); #endif ENGINE = engine; return true; } bool handle_incoming(host_api::Request req) { builtins::web::performance::Performance::timeOrigin.emplace( std::chrono::high_resolution_clock::now()); double total_compute = 0; std::chrono::system_clock::time_point start; if (ENGINE->debug_logging_enabled()) { start = system_clock::now(); } __wasilibc_ensure_environ(); if (ENGINE->debug_logging_enabled()) { printf("Running JS handleRequest function for Fastly Compute service version %s\n", getenv("FASTLY_SERVICE_VERSION")); fflush(stdout); } RootedObject fetch_event(ENGINE->cx(), FetchEvent::create(ENGINE->cx())); if (!FetchEvent::init_request(ENGINE->cx(), fetch_event, req.req, req.body)) { ENGINE->dump_pending_exception("initialization of FetchEvent"); return false; } if (ENGINE->debug_logging_enabled()) { fetch_event::dispatch_fetch_event(fetch_event, &total_compute); } else { fetch_event::dispatch_fetch_event(fetch_event); } // Loop until no more resolved promises or backend requests are pending. if (ENGINE->debug_logging_enabled()) { printf("Start processing async jobs ...\n"); fflush(stdout); } bool success = ENGINE->run_event_loop(); if (JS_IsExceptionPending(ENGINE->cx())) { ENGINE->dump_pending_exception("evaluating code"); return false; } else if (!success) { if (ENGINE->has_pending_async_tasks()) { fprintf(stderr, "Warning: JS event loop terminated with async tasks pending. " "Use FetchEvent#waitUntil to extend the service's lifetime " "if needed.\n"); return false; } else { fprintf(stderr, "Warning: JS event loop terminated without completing the request.\n"); return false; } } if (ENGINE->has_pending_async_tasks()) { if (ENGINE->debug_logging_enabled()) { fprintf(stderr, "Warning: JS event loop terminated with async tasks pending. " "Use FetchEvent#waitUntil to extend the service's lifetime " "if needed.\n"); } return false; } // Respond with status `500` if no response was ever sent. if (!FetchEvent::response_started(fetch_event)) { FetchEvent::respondWithError(ENGINE->cx(), fetch_event); return false; } if (ENGINE->debug_logging_enabled()) { auto end = system_clock::now(); double diff = duration_cast(end - start).count(); printf("Done. Total request processing time: %fms. Total compute time: %fms\n", diff / 1000, total_compute / 1000); } return true; } } // namespace fastly::runtime int main(int argc, const char *argv[]) { using fastly::fastly::Fastly; using fastly::runtime::ENGINE; Fastly::reusableSandboxOptions.freeze(); host_api::HttpReqPromise::DownstreamNextOptions options; if (Fastly::reusableSandboxOptions.between_request_timeout()) { options.timeout_ms = static_cast( Fastly::reusableSandboxOptions.between_request_timeout().value().count()); } auto req = host_api::Request::downstream_get(); if (req.is_err()) { HANDLE_ERROR(ENGINE->cx(), *req.to_err()); return -1; } const auto max_requests = Fastly::reusableSandboxOptions.max_requests().value_or(1); std::size_t requests_handled = 0; const auto start_time = std::chrono::high_resolution_clock::now(); while (true) { bool success = fastly::runtime::handle_incoming(req.unwrap()); if (!success) { if (ENGINE->debug_logging_enabled()) { printf("Request handling not successful, exiting process.\n"); fflush(stdout); } return -1; } requests_handled++; // Check if we should exit based on configured max requests // Note that a max request value of 0 means unlimited, // so we only check the max requests condition if max_requests is greater than 0. if (max_requests > 0 && requests_handled >= max_requests) { if (fastly::runtime::ENGINE->debug_logging_enabled()) { printf("Max requests handled (%zu), exiting process.\n", requests_handled); } break; } // Check if we should exit based on configured sandbox timeout if (Fastly::reusableSandboxOptions.sandbox_timeout()) { auto now = std::chrono::high_resolution_clock::now(); auto elapsed = now - start_time; if (elapsed >= Fastly::reusableSandboxOptions.sandbox_timeout().value()) { if (fastly::runtime::ENGINE->debug_logging_enabled()) { printf("Sandbox timeout reached (%llu ms), exiting process.\n", std::chrono::duration_cast(elapsed).count()); } break; } } // Check if we should exit based on configured max memory usage if (Fastly::reusableSandboxOptions.max_memory_mib()) { uint32_t heap_mib; if (fastly::compute_get_heap_mib(&heap_mib) != 0) { // If we fail to get heap memory usage, log a warning but continue anyway since this isn't a // critical failure. if (fastly::runtime::ENGINE->debug_logging_enabled()) { printf("Failed to get heap memory usage, continuing anyway.\n"); } } else if (heap_mib >= Fastly::reusableSandboxOptions.max_memory_mib().value()) { if (fastly::runtime::ENGINE->debug_logging_enabled()) { printf("Max memory exceeded (heap usage: %u MiB, max: %u MiB), exiting process.\n", heap_mib, Fastly::reusableSandboxOptions.max_memory_mib().value()); } break; } } auto next = host_api::HttpReqPromise::downstream_next(options); if (next.is_err()) { HANDLE_ERROR(ENGINE->cx(), *next.to_err()); return -1; } req = next.unwrap().wait(); if (req.is_err()) { HANDLE_ERROR(ENGINE->cx(), *req.to_err()); return -1; } if (JS_IsExceptionPending(ENGINE->cx())) { ENGINE->dump_pending_exception("running event loop"); return -1; } ENGINE->reset(); } if (fastly::runtime::ENGINE->debug_logging_enabled()) { printf("Exiting process after handling %zu requests.\n", requests_handled); fflush(stdout); } return 0; } ================================================ FILE: runtime/fastly/host-api/error_numbers.msg ================================================ /* * Our own version of spidermonkey/js/friend/ErrorNumbers.msg * where we can add our own custom error messages for use within the runtime */ /* * This is our JavaScript error message file. * * The format for each JS error message is: * * MSG_DEF(, , , * ) * * where ; * is a legal C identifer that will be used in the * JS engine source. * * is an integer literal specifying the total number of * replaceable arguments in the following format string. * * is an enum JSExnType value, defined in js/ErrorReport.h. * * is a string literal, optionally containing sequences * {X} where X is an integer representing the argument number that will * be replaced with a string value when the error is reported. * * e.g. * * MSG_DEF(JSMSG_NOT_A_SUBSPECIES, 2, JSEXN_TYPEERROR, * "{0} is not a member of the {1} family") * * can be used: * * JS_ReportErrorNumberASCII(JSMSG_NOT_A_SUBSPECIES, "Rhino", "Monkey"); * * to report: * * "TypeError: Rhino is not a member of the Monkey family" */ // clang-format off MSG_DEF(JSMSG_NOT_AN_ERROR, 0, JSEXN_ERR, "") MSG_DEF(JSMSG_ACL_NAME_NOT_STRING, 0, JSEXN_TYPEERR, "Acl open: name must be a string") MSG_DEF(JSMSG_ACL_NAME_TOO_LONG, 0, JSEXN_TYPEERR, "Acl open: name can not be more than 254 characters") MSG_DEF(JSMSG_ACL_NAME_EMPTY, 0, JSEXN_TYPEERR, "Acl open: name can not be an empty string") MSG_DEF(JSMSG_ACL_NOT_FOUND, 1, JSEXN_TYPEERR, "Acl open: \"{0}\" acl not found") MSG_DEF(JSMSG_CONFIG_STORE_DOES_NOT_EXIST, 1, JSEXN_TYPEERR, "ConfigStore constructor: No ConfigStore named '{0}' exists") MSG_DEF(JSMSG_CONFIG_STORE_KEY_EMPTY, 0, JSEXN_TYPEERR, "ConfigStore key can not be an empty string") MSG_DEF(JSMSG_CONFIG_STORE_KEY_TOO_LONG, 0, JSEXN_TYPEERR, "ConfigStore key can not be more than 255 characters") MSG_DEF(JSMSG_CONFIG_STORE_NAME_CONTAINS_INVALID_CHARACTER, 0, JSEXN_TYPEERR, "ConfigStore constructor: name can contain only ascii alphanumeric characters, underscores, and ascii whitespace") MSG_DEF(JSMSG_CONFIG_STORE_NAME_EMPTY, 0, JSEXN_TYPEERR, "ConfigStore constructor: name can not be an empty string") MSG_DEF(JSMSG_CONFIG_STORE_NAME_START_WITH_ASCII_ALPHA, 0, JSEXN_TYPEERR, "ConfigStore constructor: name must start with an ascii alpabetical character") MSG_DEF(JSMSG_CONFIG_STORE_NAME_TOO_LONG, 0, JSEXN_TYPEERR, "ConfigStore constructor: name can not be more than 255 characters") MSG_DEF(JSMSG_DICTIONARY_DOES_NOT_EXIST, 1, JSEXN_TYPEERR, "Dictionary constructor: No Dictionary named '{0}' exists") MSG_DEF(JSMSG_DICTIONARY_KEY_EMPTY, 0, JSEXN_TYPEERR, "Dictionary key can not be an empty string") MSG_DEF(JSMSG_DICTIONARY_KEY_TOO_LONG, 0, JSEXN_TYPEERR, "Dictionary key can not be more than 255 characters") MSG_DEF(JSMSG_DICTIONARY_NAME_CONTAINS_INVALID_CHARACTER, 0, JSEXN_TYPEERR, "Dictionary constructor: name can contain only ascii alphanumeric characters, underscores, and ascii whitespace") MSG_DEF(JSMSG_DICTIONARY_NAME_EMPTY, 0, JSEXN_TYPEERR, "Dictionary constructor: name can not be an empty string") MSG_DEF(JSMSG_DICTIONARY_NAME_START_WITH_ASCII_ALPHA, 0, JSEXN_TYPEERR, "Dictionary constructor: name must start with an ascii alpabetical character") MSG_DEF(JSMSG_DICTIONARY_NAME_TOO_LONG, 0, JSEXN_TYPEERR, "Dictionary constructor: name can not be more than 255 characters") MSG_DEF(JSMSG_KV_STORE_NAME_EMPTY, 0, JSEXN_TYPEERR, "KVStore constructor: name can not be an empty string") MSG_DEF(JSMSG_KV_STORE_NAME_TOO_LONG, 0, JSEXN_TYPEERR, "KVStore constructor: name can not be more than 255 characters") MSG_DEF(JSMSG_KV_STORE_NAME_NO_CONTROL_CHARACTERS, 0, JSEXN_TYPEERR, "KVStore constructor: name can not contain control characters (\\u0000-\\u001F)") MSG_DEF(JSMSG_KV_STORE_DOES_NOT_EXIST, 1, JSEXN_TYPEERR, "KVStore constructor: No KVStore named '{0}' exists") MSG_DEF(JSMSG_KV_STORE_KEY_EMPTY, 0, JSEXN_TYPEERR, "KVStore key can not be an empty string") MSG_DEF(JSMSG_KV_STORE_KEY_TOO_LONG, 0, JSEXN_TYPEERR, "KVStore key can not be more than 1024 characters") MSG_DEF(JSMSG_KV_STORE_KEY_INVALID_CHARACTER, 1, JSEXN_TYPEERR, "KVStore key can not contain {0} character") MSG_DEF(JSMSG_KV_STORE_KEY_ACME, 0, JSEXN_TYPEERR, "KVStore key can not start with .well-known/acme-challenge/") MSG_DEF(JSMSG_KV_STORE_KEY_RELATIVE, 0, JSEXN_TYPEERR, "KVStore key can not be '.' or '..'") MSG_DEF(JSMSG_KV_STORE_PUT_CONTENT_STREAM, 0, JSEXN_TYPEERR, "Content-provided streams are not yet supported for streaming into KVStore") MSG_DEF(JSMSG_KV_STORE_PUT_OVER_30_MB, 0, JSEXN_TYPEERR, "KVStore value can not be more than 30 Megabytes in size") MSG_DEF(JSMSG_KV_STORE_LIST_ERROR, 1, JSEXN_TYPEERR, "KVStore list: {0}") MSG_DEF(JSMSG_KV_STORE_DELETE_ERROR, 1, JSEXN_TYPEERR, "KVStore delete: {0}") MSG_DEF(JSMSG_KV_STORE_LOOKUP_ERROR, 1, JSEXN_TYPEERR, "KVStore lookup: {0}") MSG_DEF(JSMSG_KV_STORE_INSERT_ERROR, 1, JSEXN_TYPEERR, "KVStore insert: {0}") MSG_DEF(JSMSG_SECRET_STORE_DOES_NOT_EXIST, 1, JSEXN_TYPEERR, "SecretStore constructor: No SecretStore named '{0}' exists") MSG_DEF(JSMSG_SECRET_STORE_KEY_EMPTY, 0, JSEXN_TYPEERR, "SecretStore key can not be an empty string") MSG_DEF(JSMSG_SECRET_STORE_KEY_TOO_LONG, 0, JSEXN_TYPEERR, "SecretStore key can not be more than 255 characters") MSG_DEF(JSMSG_SECRET_STORE_KEY_CONTAINS_INVALID_CHARACTER, 0, JSEXN_TYPEERR, "SecretStore key can contain only ascii alphanumeric characters, underscores, dashes, and ascii whitespace") MSG_DEF(JSMSG_SECRET_STORE_NAME_CONTAINS_INVALID_CHARACTER, 0, JSEXN_TYPEERR, "SecretStore constructor: name can contain only ascii alphanumeric characters, underscores, dashes, and ascii whitespace") MSG_DEF(JSMSG_SECRET_STORE_NAME_EMPTY, 0, JSEXN_TYPEERR, "SecretStore constructor: name can not be an empty string") MSG_DEF(JSMSG_SECRET_STORE_NAME_START_WITH_ASCII_ALPHA, 0, JSEXN_TYPEERR, "SecretStore constructor: name must start with an ascii alpabetical character") MSG_DEF(JSMSG_SECRET_STORE_NAME_TOO_LONG, 0, JSEXN_TYPEERR, "SecretStore constructor: name can not be more than 255 characters") MSG_DEF(JSMSG_READABLE_STREAM_LOCKED_OR_DISTRUBED, 0, JSEXN_TYPEERR, "Can't use a ReadableStream that's locked or has ever been read from or canceled") MSG_DEF(JSMSG_DYNAMIC_BACKENDS_UNSUPPORTED_EXPLICIT, 2, JSEXN_ERR, "fetch(): No backend provided fetching '{1}'. Since dynamic backends are not enabled for this Fastly service, `fetch()` requires an explicit backend parameter. See https://js-compute-reference-docs.edgecompute.app/docs/globals/fetch for more info. Alternatively, contact Fastly support to enable dynamic backends.") MSG_DEF(JSMSG_DYNAMIC_BACKENDS_UNSUPPORTED_IMPLICIT, 1, JSEXN_ERR, "Backend constructor: Unable to create a dynamic backend for '{0}' - dynamic backends are unsupported on this service. Either explicitly configure backend services or contact Fastly support to enable dynamic backends.") MSG_DEF(JSMSG_BACKEND_FROMNAME_BACKEND_DOES_NOT_EXIST, 1, JSEXN_ERR, "Backend.fromName: backend named '{0}' does not exist") MSG_DEF(JSMSG_BACKEND_IS_HEALTHY_BACKEND_DOES_NOT_EXIST, 1, JSEXN_ERR, "Backend.health: backend named '{0}' does not exist") MSG_DEF(JSMSG_BACKEND_PARAMETER_NOT_OBJECT, 0, JSEXN_TYPEERR, "Backend constructor: configuration parameter must be an Object") MSG_DEF(JSMSG_BACKEND_NAME_NOT_SET, 0, JSEXN_TYPEERR, "Backend constructor: name can not be null or undefined") MSG_DEF(JSMSG_BACKEND_NAME_TOO_LONG, 0, JSEXN_TYPEERR, "Backend constructor: name can not be more than 254 characters") MSG_DEF(JSMSG_BACKEND_NAME_EMPTY, 0, JSEXN_TYPEERR, "Backend constructor: name can not be an empty string") MSG_DEF(JSMSG_BACKEND_TARGET_NOT_SET, 0, JSEXN_TYPEERR, "Backend constructor: target can not be null or undefined") MSG_DEF(JSMSG_BACKEND_TARGET_EMPTY, 0, JSEXN_TYPEERR, "Backend constructor: target can not be an empty string") MSG_DEF(JSMSG_BACKEND_TARGET_INVALID, 0, JSEXN_TYPEERR, "Backend constructor: target does not contain a valid IPv4, IPv6, or hostname address") MSG_DEF(JSMSG_BACKEND_CIPHERS_EMPTY, 0, JSEXN_TYPEERR, "Backend constructor: ciphers can not be an empty string") MSG_DEF(JSMSG_BACKEND_CIPHERS_NOT_AVALIABLE, 0, JSEXN_TYPEERR, "Backend constructor: none of the provided ciphers are supported by Fastly. The list of supported ciphers is available on https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration") MSG_DEF(JSMSG_BACKEND_HOST_OVERRIDE_EMPTY, 0, JSEXN_TYPEERR, "Backend constructor: hostOverride can not be an empty string") MSG_DEF(JSMSG_BACKEND_CERTIFICATE_HOSTNAME_EMPTY, 0, JSEXN_TYPEERR, "Backend constructor: certificateHostname can not be an empty string") MSG_DEF(JSMSG_BACKEND_SNI_HOSTNAME_EMPTY, 0, JSEXN_TYPEERR, "Backend constructor: sniHostname can not be an empty string") MSG_DEF(JSMSG_BACKEND_CA_CERTIFICATE_EMPTY, 0, JSEXN_TYPEERR, "Backend constructor: caCertificate can not be an empty string") MSG_DEF(JSMSG_BACKEND_TLS_MIN_INVALID, 0, JSEXN_RANGEERR, "Backend constructor: tlsMinVersion must be either 1, 1.1, 1.2, or 1.3") MSG_DEF(JSMSG_BACKEND_TLS_MAX_INVALID, 0, JSEXN_RANGEERR, "Backend constructor: tlsMaxVersion must be either 1, 1.1, 1.2, or 1.3") MSG_DEF(JSMSG_BACKEND_TLS_MIN_GREATER_THAN_TLS_MAX, 0, JSEXN_RANGEERR, "Backend constructor: tlsMinVersion must be less than or equal to tlsMaxVersion") MSG_DEF(JSMSG_BACKEND_PORT_INVALID, 0, JSEXN_RANGEERR, "Backend constructor: port must be more than 0 and less than 2^16 (65,536)") MSG_DEF(JSMSG_BACKEND_CLIENT_CERTIFICATE_NOT_OBJECT, 0, JSEXN_TYPEERR, "Backend constructor: clientCertificate must be an object containing 'certificate' and 'key' properties") MSG_DEF(JSMSG_BACKEND_CLIENT_CERTIFICATE_NO_CERTIFICATE, 0, JSEXN_TYPEERR, "Backend constructor: clientCertificate 'certificate' must be a certificate string") MSG_DEF(JSMSG_BACKEND_CLIENT_CERTIFICATE_CERTIFICATE_EMPTY, 0, JSEXN_TYPEERR, "Backend constructor: clientCertificate 'certificate' can not be an empty string") MSG_DEF(JSMSG_BACKEND_CLIENT_CERTIFICATE_KEY_INVALID, 0, JSEXN_TYPEERR, "Backend constructor: clientCertificate 'key' must be a SecretStoreEntry instance") MSG_DEF(JSMSG_BACKEND_TCP_KEEPALIVE_NOT_OBJECT_OR_BOOL, 0, JSEXN_TYPEERR, "Backend constructor: tcpKeepalive must be a bool or object containing optional 'timeSecs', 'intervalSecs' and 'probes' properties") MSG_DEF(JSMSG_BACKEND_TCP_KEEPALIVE_INVALID_PROBES, 0, JSEXN_TYPEERR, "Backend constructor: tcpKeepalive 'probes' must be an integer number greater than zero") MSG_DEF(JSMSG_CACHE_OVERRIDE_MODE_INVALID, 1, JSEXN_TYPEERR, "CacheOverride constructor: 'mode' has to be \"none\", \"pass\", or \"override\", but got \"{0}\"") MSG_DEF(JSMSG_RESPONSE_VALUE_NOT_UINT8ARRAY, 0, JSEXN_TYPEERR, "Can't convert value to Uint8Array while consuming Body") MSG_DEF(JSMSG_RESPONSE_BODY_DISTURBED_OR_LOCKED, 0, JSEXN_TYPEERR, "Response body object should not be disturbed or locked") MSG_DEF(JSMSG_RESPONSE_CONSTRUCTOR_INVALID_STATUS, 1, JSEXN_RANGEERR, "Response constructor: Invalid response status code. The status provided ({0}) is outside the range [200, 599].") MSG_DEF(JSMSG_RESPONSE_CONSTRUCTOR_INVALID_STATUS_TEXT, 0, JSEXN_TYPEERR, "Response constructor: Invalid response status text. The statusText provided contains invalid characters.") MSG_DEF(JSMSG_RESPONSE_CONSTRUCTOR_BODY_WITH_NULL_BODY_STATUS, 0, JSEXN_TYPEERR, "Response constructor: Response body is given with a null body status.") MSG_DEF(JSMSG_REQUEST_BACKEND_DOES_NOT_EXIST, 1, JSEXN_TYPEERR, "Requested backend named '{0}' does not exist") MSG_DEF(JSMSG_RESPONSE_REDIRECT_INVALID_URI, 0, JSEXN_TYPEERR, "Response.redirect: url parameter is not a valid URL.") MSG_DEF(JSMSG_RESPONSE_REDIRECT_INVALID_STATUS, 0, JSEXN_RANGEERR, "Response.redirect: Invalid redirect status code.") MSG_DEF(JSMSG_RESPONSE_NULL_BODY_STATUS_WITH_BODY, 0, JSEXN_TYPEERR, "Response with null body status cannot have body") MSG_DEF(JSMSG_RESPONSE_JSON_INVALID_VALUE, 0, JSEXN_TYPEERR, "Redirect.json: The data is not JSON serializable") MSG_DEF(JSMSG_TIMEOUT_NEGATIVE, 2, JSEXN_RANGEERR, "{0}: {1} can not be a negative number") MSG_DEF(JSMSG_TIMEOUT_TOO_BIG, 3, JSEXN_RANGEERR, "{0}: {1} is above the maximum of {2}") MSG_DEF(JSMSG_TIMEOUT_NAN, 2, JSEXN_RANGEERR, "{0}: {1} is not a valid number") MSG_DEF(JSMSG_INVALID_BUFFER, 1, JSEXN_TYPEERR, "{0}: bytes must be an ArrayBuffer or ArrayBufferView object") MSG_DEF(JSMSG_SIMPLE_CACHE_SET_CONTENT_STREAM, 0, JSEXN_TYPEERR, "Content-provided streams are not yet supported for streaming into SimpleCache") MSG_DEF(JSMSG_BODY_APPEND_CONTENT_STREAM, 0, JSEXN_TYPEERR, "Content-provided streams are not yet supported for appending onto a FastlyBody") MSG_DEF(JSMSG_BODY_PREPEND_CONTENT_STREAM, 0, JSEXN_TYPEERR, "Content-provided streams are not yet supported for prepending onto a FastlyBody") //clang-format on ================================================ FILE: runtime/fastly/host-api/fastly.h ================================================ #ifndef fastly_H #define fastly_H #ifdef __cplusplus extern "C" { namespace fastly { #endif #include #include #include typedef struct fastly_world_string { uint8_t *ptr; size_t len; } fastly_world_string; typedef struct fastly_world_list_string { fastly_world_string *ptr; size_t len; } fastly_world_list_string; typedef struct fastly_world_list_u8 { uint8_t *ptr; size_t len; } fastly_world_list_u8; typedef struct fastly_world_list_list_u8 { fastly_world_list_u8 *ptr; size_t len; } fastly_world_list_list_u8; typedef struct { bool is_some; fastly_world_list_list_u8 val; } fastly_world_option_list_list_u8; typedef struct fastly_host_http_response { uint32_t f0; uint32_t f1; } fastly_host_http_response; typedef struct fastly_host_http_inspect_options { const char *corp; uint32_t corp_len; const char *workspace; uint32_t workspace_len; const char *override_client_ip_ptr; uint32_t override_client_ip_len; } fastly_host_http_inspect_options; typedef fastly_host_http_response fastly_world_tuple2_handle_handle; #define WASM_IMPORT(module, name) __attribute__((import_module(module), import_name(name))) // max header size to match vcl #define HEADER_MAX_LEN 69000 #define METHOD_MAX_LEN 1024 #define URI_MAX_LEN 8192 #define CONFIG_STORE_INITIAL_BUF_LEN 512 #define DICTIONARY_ENTRY_MAX_LEN 8000 // Ensure that all the things we want to use the hostcall buffer for actually // fit into the buffer. #define HOSTCALL_BUFFER_LEN HEADER_MAX_LEN static_assert(DICTIONARY_ENTRY_MAX_LEN < HOSTCALL_BUFFER_LEN); static_assert(METHOD_MAX_LEN < HOSTCALL_BUFFER_LEN); static_assert(URI_MAX_LEN < HOSTCALL_BUFFER_LEN); #define LIST_ALLOC_SIZE 50 typedef uint8_t fastly_host_error; // Unknown error value. // It should be an internal error if this is returned. #define FASTLY_HOST_ERROR_UNKNOWN_ERROR 0 // Generic error value. // This means that some unexpected error occurred during a hostcall. #define FASTLY_HOST_ERROR_GENERIC_ERROR 1 // Invalid argument. #define FASTLY_HOST_ERROR_INVALID_ARGUMENT 2 // Invalid handle. // Thrown when a handle is not valid. E.G. No dictionary exists with the given name. #define FASTLY_HOST_ERROR_BAD_HANDLE 3 // Buffer length error. // Thrown when a buffer is too long. #define FASTLY_HOST_ERROR_BUFFER_LEN 4 // Unsupported operation error. // This error is thrown when some operation cannot be performed, because it is not supported. #define FASTLY_HOST_ERROR_UNSUPPORTED 5 // Alignment error. // This is thrown when a pointer does not point to a properly aligned slice of memory. #define FASTLY_HOST_ERROR_BAD_ALIGN 6 // Invalid HTTP error. // This can be thrown when a method, URI, header, or status is not valid. This can also // be thrown if a message head is too large. #define FASTLY_HOST_ERROR_HTTP_INVALID 7 // HTTP user error. // This is thrown in cases where user code caused an HTTP error. For example, attempt to send // a 1xx response code, or a request with a non-absolute URI. This can also be caused by // an unexpected header: both `content-length` and `transfer-encoding`, for example. #define FASTLY_HOST_ERROR_HTTP_USER 8 // HTTP incomplete message error. // This can be thrown when a stream ended unexpectedly. #define FASTLY_HOST_ERROR_HTTP_INCOMPLETE 9 // A `None` error. // This status code is used to indicate when an optional value did not exist, as opposed to // an empty value. // Note, this value should no longer be used, as we have explicit optional types now. #define FASTLY_HOST_ERROR_OPTIONAL_NONE 10 // Message head too large. #define FASTLY_HOST_ERROR_HTTP_HEAD_TOO_LARGE 11 // Invalid HTTP status. #define FASTLY_HOST_ERROR_HTTP_INVALID_STATUS 12 // Limit exceeded // // This is returned when an attempt to allocate a resource has exceeded the maximum number of // resources permitted. For example, creating too many response handles. #define FASTLY_HOST_ERROR_LIMIT_EXCEEDED 13 typedef uint8_t fastly_host_http_send_error_detail_tag; // The send-error-detail struct has not been populated. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_UNINITIALIZED 0 // There was no send error. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_OK 1 // The system encountered a timeout when trying to find an IP address for the backend // hostname. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_DNS_TIMEOUT 2 // The system encountered a DNS error when trying to find an IP address for the backend // hostname. The fields dns-error-rcode and dns-error-info-code may be set in the // send-error-detail. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_DNS_ERROR 3 // The system cannot determine which backend to use, or the specified backend was invalid. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_DESTINATION_NOT_FOUND 4 // The system considers the backend to be unavailable e.g., recent attempts to communicate // with it may have failed, or a health check may indicate that it is down. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_DESTINATION_UNAVAILABLE 5 // The system cannot find a route to the next-hop IP address. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_DESTINATION_IP_UNROUTABLE 6 // The system's connection to the backend was refused. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_CONNECTION_REFUSED 7 // The system's connection to the backend was closed before a complete response was // received. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_CONNECTION_TERMINATED 8 // The system's attempt to open a connection to the backend timed out. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_CONNECTION_TIMEOUT 9 // The system is configured to limit the number of connections it has to the backend, and // that limit has been exceeded. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_CONNECTION_LIMIT_REACHED 10 // The system encountered an error when verifying the certificate presented by the backend. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_TLS_CERTIFICATE_ERROR 11 // The system encountered an error with the backend TLS configuration. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_TLS_CONFIGURATION_ERROR 12 // The system received an incomplete response to the request from the backend. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_HTTP_INCOMPLETE_RESPONSE 13 // The system received a response to the request whose header section was considered too // large. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_HTTP_RESPONSE_HEADER_SECTION_TOO_LARGE 14 // The system received a response to the request whose body was considered too large. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_HTTP_RESPONSE_BODY_TOO_LARGE 15 // The system reached a configured time limit waiting for the complete response. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_HTTP_RESPONSE_TIMEOUT 16 // The system received a response to the request whose status code or reason phrase was // invalid. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_HTTP_RESPONSE_STATUS_INVALID 17 // The process of negotiating an upgrade of the HTTP version between the system and the // backend failed. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_HTTP_UPGRADE_FAILED 18 // The system encountered an HTTP protocol error when communicating with the backend. This // error will only be used when a more specific one is not defined. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_HTTP_PROTOCOL_ERROR 19 // An invalid cache key was provided for the request. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_HTTP_REQUEST_CACHE_KEY_INVALID 20 // An invalid URI was provided for the request. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_HTTP_REQUEST_URI_INVALID 21 // The system encountered an unexpected internal error. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_INTERNAL_ERROR 22 // The system received a TLS alert from the backend. The field tls-alert-id may be set in // the send-error-detail. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_TLS_ALERT_RECEIVED 23 // The system encountered a TLS error when communicating with the backend, either during // the handshake or afterwards. #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_TAG_TLS_PROTOCOL_ERROR 24 // Mask representing which fields are understood by the guest, and which have been set by the host. // // When the guest calls hostcalls with a mask, it should set every bit in the mask that corresponds // to a defined flag. This signals the host to write only to fields with a set bit, allowing // forward compatibility for existing guest programs even after new fields are added to the struct. typedef uint8_t fastly_host_http_send_error_detail_mask; #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_MASK_RESERVED (1 << 0) #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_MASK_DNS_ERROR_RCODE (1 << 1) #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_MASK_DNS_ERROR_INFO_CODE (1 << 2) #define FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_MASK_TLS_ALERT_ID (1 << 3) typedef struct fastly_host_http_send_error_detail { fastly_host_http_send_error_detail_tag tag; fastly_host_http_send_error_detail_mask mask; uint16_t dns_error_rcode; uint16_t dns_error_info_code; uint8_t tls_alert_id; } fastly_host_http_send_error_detail; typedef uint32_t fastly_kv_error; // The values need to match https://docs.rs/fastly-sys/0.10.5/src/fastly_sys/lib.rs.html#111 #define BACKEND_CONFIG_RESERVED (1u << 0) #define BACKEND_CONFIG_HOST_OVERRIDE (1u << 1) #define BACKEND_CONFIG_CONNECT_TIMEOUT (1u << 2) #define BACKEND_CONFIG_FIRST_BYTE_TIMEOUT (1u << 3) #define BACKEND_CONFIG_BETWEEN_BYTES_TIMEOUT (1u << 4) #define BACKEND_CONFIG_USE_SSL (1u << 5) #define BACKEND_CONFIG_SSL_MIN_VERSION (1u << 6) #define BACKEND_CONFIG_SSL_MAX_VERSION (1u << 7) #define BACKEND_CONFIG_CERT_HOSTNAME (1u << 8) #define BACKEND_CONFIG_CA_CERT (1u << 9) #define BACKEND_CONFIG_CIPHERS (1u << 10) #define BACKEND_CONFIG_SNI_HOSTNAME (1u << 11) #define BACKEND_CONFIG_DONT_POOL (1u << 12) #define BACKEND_CONFIG_CLIENT_CERT (1u << 13) #define BACKEND_CONFIG_GRPC (1u << 14) #define BACKEND_CONFIG_KEEPALIVE (1u << 15) typedef enum BACKEND_HEALTH { UNKNOWN = 0, HEALTHY = 1, UNHEALTHY = 2, } BACKEND_HEALTH; typedef enum TLS { VERSION_1 = 0, VERSION_1_1 = 1, VERSION_1_2 = 2, VERSION_1_3 = 3, } TLS; typedef struct DynamicBackendConfig { const char *host_override; uint32_t host_override_len; uint32_t connect_timeout_ms; uint32_t first_byte_timeout_ms; uint32_t between_bytes_timeout_ms; uint32_t ssl_min_version; uint32_t ssl_max_version; const char *cert_hostname; uint32_t cert_hostname_len; const char *ca_cert; uint32_t ca_cert_len; const char *ciphers; uint32_t ciphers_len; const char *sni_hostname; uint32_t sni_hostname_len; const char *client_certificate; uint32_t client_certificate_len; uint32_t client_key; uint32_t http_keepalive_time_ms; uint32_t tcp_keepalive_enable; uint32_t tcp_keepalive_interval_secs; uint32_t tcp_keepalive_probes; uint32_t tcp_keepalive_time_secs; } DynamicBackendConfig; #define INVALID_HANDLE (UINT32_MAX - 1) typedef enum BodyWriteEnd { BodyWriteEndBack = 0, BodyWriteEndFront = 1, } BodyWriteEnd; #define CACHE_OVERRIDE_NONE (0u) #define CACHE_OVERRIDE_PASS (1u << 0) #define CACHE_OVERRIDE_TTL (1u << 1) #define CACHE_OVERRIDE_STALE_WHILE_REVALIDATE (1u << 2) #define CACHE_OVERRIDE_PCI (1u << 3) typedef uint32_t req_inspect_config_options_mask; #define FASTLY_HOST_HTTP_REQ_INSPECT_CONFIG_OPTIONS_MASK_RESERVED (1 << 0); #define FASTLY_HOST_HTTP_REQ_INSPECT_CONFIG_OPTIONS_MASK_CORP (1 << 1); #define FASTLY_HOST_HTTP_REQ_INSPECT_CONFIG_OPTIONS_MASK_WORKSPACE (1 << 2); #define FASTLY_HOST_HTTP_REQ_INSPECT_CONFIG_OPTIONS_MASK_OVERRIDE_CLIENT_IP (1 << 3); WASM_IMPORT("fastly_abi", "init") int init(uint64_t abi_version); // Module fastly_http_body WASM_IMPORT("fastly_http_body", "append") int body_append(uint32_t dst_handle, uint32_t src_handle); WASM_IMPORT("fastly_http_body", "new") int body_new(uint32_t *handle_out); WASM_IMPORT("fastly_http_body", "read") int body_read(uint32_t body_handle, uint8_t *buf, size_t buf_len, size_t *nread); WASM_IMPORT("fastly_http_body", "write") int body_write(uint32_t body_handle, const uint8_t *buf, size_t buf_len, BodyWriteEnd end, size_t *nwritten); WASM_IMPORT("fastly_http_body", "close") int body_close(uint32_t body_handle); WASM_IMPORT("fastly_http_body", "abandon") int body_abandon(uint32_t body_handle); WASM_IMPORT("fastly_http_body", "trailer_append") int body_trailer_append(uint32_t body_handle, const uint8_t *name, size_t name_len, const uint8_t *value, size_t value_len); WASM_IMPORT("fastly_http_body", "trailer_names_get") int body_trailer_names_get(uint32_t body_handle, char *buf, size_t buf_len, uint32_t cursor, uint32_t *ending_cursor, size_t *nwritten); WASM_IMPORT("fastly_http_body", "trailer_value_get") int body_trailer_value_get(uint32_t body_handle, const uint8_t *name, size_t name_len, char *value, size_t value_max_len, size_t *nwritten); WASM_IMPORT("fastly_http_body", "trailer_values_get") int body_trailer_values_get(uint32_t body_handle, const uint8_t *name, size_t name_len, char *buf, size_t buf_len, uint32_t cursor, uint32_t *ending_cursor, size_t *nwritten); WASM_IMPORT("fastly_http_body", "known_length") int body_known_length(uint32_t body_handle, uint64_t *length); // Module fastly_http_cache // HTTP Cache handle type typedef uint32_t fastly_http_cache_handle; // HTTP Cache specific types typedef uint32_t fastly_is_cacheable; typedef uint32_t fastly_is_sensitive; // HTTP storage action enum typedef uint8_t fastly_http_storage_action; #define FASTLY_HTTP_STORAGE_ACTION_INSERT 0 #define FASTLY_HTTP_STORAGE_ACTION_UPDATE 1 #define FASTLY_HTTP_STORAGE_ACTION_DO_NOT_STORE 2 #define FASTLY_HTTP_STORAGE_ACTION_RECORD_UNCACHEABLE 3 // HTTP Cache lookup options typedef struct __attribute__((aligned(4))) fastly_http_cache_lookup_options { const char *override_key; size_t override_key_len; } fastly_http_cache_lookup_options; // HTTP Cache lookup options mask #define FASTLY_HTTP_CACHE_LOOKUP_OPTIONS_MASK_RESERVED (1 << 0) #define FASTLY_HTTP_CACHE_LOOKUP_OPTIONS_MASK_OVERRIDE_KEY (1 << 1) // HTTP Cache write options typedef struct __attribute__((aligned(8))) fastly_http_cache_write_options { uint64_t max_age_ns; const char *vary_rule; size_t vary_rule_len; uint64_t initial_age_ns; uint64_t stale_while_revalidate_ns; const char *surrogate_keys; size_t surrogate_keys_len; uint64_t length; } fastly_http_cache_write_options; // HTTP Cache write options mask #define FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_RESERVED (1 << 0) #define FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_VARY_RULE (1 << 1) #define FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_INITIAL_AGE_NS (1 << 2) #define FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_STALE_WHILE_REVALIDATE_NS (1 << 3) #define FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_SURROGATE_KEYS (1 << 4) #define FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_LENGTH (1 << 5) #define FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_SENSITIVE_DATA (1 << 6) // HTTP Cache host calls WASM_IMPORT("fastly_http_cache", "is_request_cacheable") int http_cache_is_request_cacheable(uint32_t req_handle, uint32_t *is_cacheable_out); WASM_IMPORT("fastly_http_cache", "get_suggested_cache_key") int http_cache_get_suggested_cache_key(uint32_t req_handle, char *key_out, size_t key_out_len, size_t *nwritten_out); WASM_IMPORT("fastly_http_cache", "transaction_lookup") int http_cache_transaction_lookup(uint32_t req_handle, uint32_t options_mask, fastly_http_cache_lookup_options *options, uint32_t *handle_out); WASM_IMPORT("fastly_http_cache", "transaction_insert") int http_cache_transaction_insert(uint32_t handle, uint32_t resp_handle, uint32_t options_mask, fastly_http_cache_write_options *options, uint32_t *body_handle_out); WASM_IMPORT("fastly_http_cache", "transaction_insert_and_stream_back") int http_cache_transaction_insert_and_stream_back(uint32_t handle, uint32_t resp_handle, uint32_t options_mask, fastly_http_cache_write_options *options, uint32_t *body_handle_out, uint32_t *cache_handle_out); WASM_IMPORT("fastly_http_cache", "transaction_update") int http_cache_transaction_update(uint32_t handle, uint32_t resp_handle, uint32_t options_mask, fastly_http_cache_write_options *options); WASM_IMPORT("fastly_http_cache", "transaction_update_and_return_fresh") int http_cache_transaction_update_and_return_fresh(uint32_t handle, uint32_t resp_handle, uint32_t options_mask, fastly_http_cache_write_options *options, uint32_t *fresh_handle_out); WASM_IMPORT("fastly_http_cache", "transaction_record_not_cacheable") int http_cache_transaction_record_not_cacheable(uint32_t handle, uint32_t options_mask, fastly_http_cache_write_options *options); WASM_IMPORT("fastly_http_cache", "transaction_abandon") int http_cache_transaction_abandon(uint32_t handle); WASM_IMPORT("fastly_http_cache", "close") int http_cache_close(uint32_t handle); WASM_IMPORT("fastly_http_cache", "get_suggested_backend_request") int http_cache_get_suggested_backend_request(uint32_t handle, uint32_t *req_handle_out); WASM_IMPORT("fastly_http_cache", "get_suggested_cache_options") int http_cache_get_suggested_cache_options(uint32_t handle, uint32_t response_handle, uint32_t options_mask, fastly_http_cache_write_options *options, uint32_t *options_mask_out, fastly_http_cache_write_options *options_out); WASM_IMPORT("fastly_http_cache", "prepare_response_for_storage") int http_cache_prepare_response_for_storage(uint32_t handle, uint32_t response_handle, uint8_t *storage_action_out, uint32_t *updated_resp_handle_out); WASM_IMPORT("fastly_http_cache", "get_found_response") int http_cache_get_found_response(uint32_t handle, uint32_t transform_for_client, uint32_t *resp_handle_out, uint32_t *body_handle_out); WASM_IMPORT("fastly_http_cache", "get_state") int http_cache_get_state(uint32_t handle, uint8_t *state_out); WASM_IMPORT("fastly_http_cache", "get_length") int http_cache_get_length(uint32_t handle, uint64_t *length_out); WASM_IMPORT("fastly_http_cache", "get_max_age_ns") int http_cache_get_max_age_ns(uint32_t handle, uint64_t *max_age_ns_out); WASM_IMPORT("fastly_http_cache", "get_stale_while_revalidate_ns") int http_cache_get_stale_while_revalidate_ns(uint32_t handle, uint64_t *swr_ns_out); WASM_IMPORT("fastly_http_cache", "get_age_ns") int http_cache_get_age_ns(uint32_t handle, uint64_t *age_ns_out); WASM_IMPORT("fastly_http_cache", "get_hits") int http_cache_get_hits(uint32_t handle, uint64_t *hits_out); WASM_IMPORT("fastly_http_cache", "get_sensitive_data") int http_cache_get_sensitive_data(uint32_t handle, uint32_t *is_sensitive_out); WASM_IMPORT("fastly_http_cache", "get_surrogate_keys") int http_cache_get_surrogate_keys(uint32_t handle, char *surrogate_keys_out, size_t surrogate_keys_out_len, size_t *nwritten_out); WASM_IMPORT("fastly_http_cache", "get_vary_rule") int http_cache_get_vary_rule(uint32_t handle, char *vary_rule_out, size_t vary_rule_out_len, size_t *nwritten_out); // Module fastly_log WASM_IMPORT("fastly_log", "endpoint_get") int log_endpoint_get(const char *name, size_t name_len, uint32_t *endpoint_handle); WASM_IMPORT("fastly_log", "write") int log_write(uint32_t endpoint_handle, const char *msg, size_t msg_len, size_t *nwritten); // Module fastly_http_downstream typedef struct fastly_http_downstream_next_request_options { uint32_t timeout_ms; } fastly_http_downstream_next_request_options; #define FASTLY_HTTP_DOWNSTREAM_NEXT_REQUEST_OPTIONS_MASK_RESERVED (1 << 0) #define FASTLY_HTTP_DOWNSTREAM_NEXT_REQUEST_OPTIONS_MASK_TIMEOUT (1 << 1) WASM_IMPORT("fastly_http_downstream", "next_request") int downstream_next_request(uint32_t options_mask, fastly_http_downstream_next_request_options *options, uint32_t *req_promise_handle_out); WASM_IMPORT("fastly_http_downstream", "next_request_wait") int downstream_next_request_wait(uint32_t req_promise_handle, uint32_t *req_handle_out, uint32_t *body_handle_out); WASM_IMPORT("fastly_http_downstream", "next_request_abandon") int downstream_next_request_abandon(uint32_t req_promise_handle); // Module fastly_http_req WASM_IMPORT("fastly_http_req", "register_dynamic_backend") int req_register_dynamic_backend(const char *name_prefix, size_t name_prefix_len, const char *target, size_t target_len, uint32_t backend_config_mask, DynamicBackendConfig *backend_configuration); WASM_IMPORT("fastly_http_req", "body_downstream_get") int req_body_downstream_get(uint32_t *req_handle_out, uint32_t *body_handle_out); WASM_IMPORT("fastly_http_req", "redirect_to_grip_proxy_v2") int req_redirect_to_grip_proxy_v2(uint32_t req_handle, const char *backend_name, size_t backend_name_len); WASM_IMPORT("fastly_http_req", "redirect_to_websocket_proxy_v2") int req_redirect_to_websocket_proxy_v2(uint32_t req_handle, const char *backend_name, size_t backend_name_len); /** * Set the cache override behavior for this request. * * The default behavior, equivalent to `CACHE_OVERRIDE_NONE`, respects the cache control headers * from the origin's response. * * Calling this function with `CACHE_OVERRIDE_PASS` will ignore the subsequent arguments and Pass * unconditionally. * * To override, TTL, stale-while-revalidate, or stale-with-error, set the appropriate bits in the * tag using the corresponding constants, and pass the override values in the appropriate arguments. * * fastly_req_cache_override_v2_set also includes an optional Surrogate-Key which will be set or * added to any received from the origin. */ WASM_IMPORT("fastly_http_req", "cache_override_set") int req_cache_override_set(uint32_t req_handle, int tag, uint32_t ttl, uint32_t stale_while_revalidate); WASM_IMPORT("fastly_http_req", "cache_override_v2_set") int req_cache_override_v2_set(uint32_t req_handle, int tag, uint32_t ttl, uint32_t stale_while_revalidate, const char *surrogate_key, size_t surrogate_key_len); #define FASTLY_HOST_CONTENT_ENCODINGS_GZIP (1 << 0) WASM_IMPORT("fastly_http_req", "auto_decompress_response_set") int req_auto_decompress_response_set(uint32_t req_handle, int tag); WASM_IMPORT("fastly_http_downstream", "downstream_client_request_id") int http_downstream_client_request_id(uint32_t req_handle, uint8_t *ret, size_t ret_len, size_t *nwritten); /** * `octets` must be a 16-byte array. * If, after a successful call, `nwritten` == 4, the value in `octets` is an IPv4 address. * Otherwise, if `nwritten` will is `16`, the value in `octets` is an IPv6 address. * Otherwise, `nwritten` will be `0`, and no address is available. */ WASM_IMPORT("fastly_http_downstream", "downstream_client_ip_addr") int http_downstream_client_ip_addr_get(uint32_t req_handle, uint8_t *octets, size_t *nwritten); WASM_IMPORT("fastly_http_downstream", "downstream_server_ip_addr") int http_downstream_server_ip_addr_get(uint32_t req_handle, uint8_t *octets, size_t *nwritten); WASM_IMPORT("fastly_http_downstream", "downstream_tls_cipher_openssl_name") int http_downstream_tls_cipher_openssl_name(uint32_t req_handle, char *ret, size_t ret_len, size_t *nwritten); WASM_IMPORT("fastly_http_downstream", "downstream_tls_protocol") int http_downstream_tls_protocol(uint32_t req_handle, char *ret, size_t ret_len, size_t *nwritten); WASM_IMPORT("fastly_http_downstream", "downstream_tls_client_hello") int http_downstream_tls_client_hello(uint32_t req_handle, uint8_t *ret, size_t ret_len, size_t *nwritten); WASM_IMPORT("fastly_http_downstream", "downstream_tls_raw_client_certificate") int http_downstream_tls_raw_client_certificate(uint32_t req_handle, uint8_t *ret, size_t ret_len, size_t *nwritten); WASM_IMPORT("fastly_http_downstream", "downstream_tls_ja3_md5") int http_downstream_tls_ja3_md5(uint32_t req_handle, uint8_t *ret, size_t *nwritten); WASM_IMPORT("fastly_http_downstream", "downstream_tls_ja4") int http_downstream_tls_ja4(uint32_t req_handle, uint8_t *ret, size_t ret_len, size_t *nwritten); WASM_IMPORT("fastly_http_downstream", "downstream_client_h2_fingerprint") int http_downstream_client_h2_fingerprint(uint32_t req_handle, uint8_t *ret, size_t ret_len, size_t *nwritten); WASM_IMPORT("fastly_http_downstream", "downstream_client_oh_fingerprint") int http_downstream_client_oh_fingerprint(uint32_t req_handle, uint8_t *ret, size_t ret_len, size_t *nwritten); WASM_IMPORT("fastly_http_req", "new") int req_new(uint32_t *req_handle_out); WASM_IMPORT("fastly_http_req", "header_names_get") int req_header_names_get(uint32_t req_handle, uint8_t *buf, size_t buf_len, uint32_t cursor, int64_t *ending_cursor, size_t *nwritten); WASM_IMPORT("fastly_http_req", "original_header_names_get") int req_original_header_names_get(uint8_t *buf, size_t buf_len, uint32_t cursor, int64_t *ending_cursor, size_t *nwritten); WASM_IMPORT("fastly_http_req", "original_header_count") int req_original_header_count(uint32_t *count); WASM_IMPORT("fastly_http_req", "header_value_get") int req_header_value_get(uint32_t req_handle, const char *name, size_t name_len, uint8_t *value, size_t value_max_len, size_t *nwritten); WASM_IMPORT("fastly_http_req", "header_values_get") int req_header_values_get(uint32_t req_handle, const char *name, size_t name_len, uint8_t *buf, size_t buf_len, uint32_t cursor, int64_t *ending_cursor, size_t *nwritten); WASM_IMPORT("fastly_http_req", "header_insert") int req_header_insert(uint32_t req_handle, const char *name, size_t name_len, const uint8_t *value, size_t value_len); WASM_IMPORT("fastly_http_req", "header_append") int req_header_append(uint32_t req_handle, const char *name, size_t name_len, const uint8_t *value, size_t value_len); WASM_IMPORT("fastly_http_req", "header_remove") int req_header_remove(uint32_t req_handle, const char *name, size_t name_len); WASM_IMPORT("fastly_http_req", "method_get") int req_method_get(uint32_t req_handle, char *method, size_t method_max_len, size_t *nwritten); WASM_IMPORT("fastly_http_req", "method_set") int req_method_set(uint32_t req_handle, const char *method, size_t method_len); WASM_IMPORT("fastly_http_req", "uri_get") int req_uri_get(uint32_t req_handle, char *uri, size_t uri_max_len, size_t *nwritten); WASM_IMPORT("fastly_http_req", "uri_set") int req_uri_set(uint32_t req_handle, const char *uri, size_t uri_len); WASM_IMPORT("fastly_http_req", "version_get") int req_version_get(uint32_t req_handle, uint32_t *version); WASM_IMPORT("fastly_http_req", "version_set") int req_version_set(uint32_t req_handle, uint32_t version); WASM_IMPORT("fastly_http_req", "framing_headers_mode_set") int req_framing_headers_mode_set(uint32_t req_handle, uint32_t mode); WASM_IMPORT("fastly_http_req", "send") int req_send(uint32_t req_handle, uint32_t body_handle, const uint8_t *backend, size_t backend_len, uint32_t *resp_handle_out, uint32_t *resp_body_handle_out); WASM_IMPORT("fastly_http_req", "send_async") int req_send_async(uint32_t req_handle, uint32_t body_handle, const char *backend, size_t backend_len, uint32_t *pending_req_out); WASM_IMPORT("fastly_http_req", "send_async_streaming") int req_send_async_streaming(uint32_t req_handle, uint32_t body_handle, const char *backend, size_t backend_len, uint32_t *pending_req_out); WASM_IMPORT("fastly_http_req", "send_async_v2") int req_send_async_v2(uint32_t req_handle, uint32_t body_handle, const char *backend, size_t backend_len, uint32_t streaming, uint32_t *pending_req_out); WASM_IMPORT("fastly_http_req", "pending_req_poll") int req_pending_req_poll(uint32_t req_handle, uint32_t *is_done_out, uint32_t *resp_handle_out, uint32_t *resp_body_handle_out); WASM_IMPORT("fastly_http_req", "pending_req_select") int req_pending_req_select(uint32_t req_handles[], size_t req_handles_len, uint32_t *done_idx_out, uint32_t *resp_handle_out, uint32_t *resp_body_handle_out); WASM_IMPORT("fastly_http_req", "pending_req_wait") int req_pending_req_wait(uint32_t req_handle, uint32_t *resp_handle_out, uint32_t *resp_body_handle_out); WASM_IMPORT("fastly_http_req", "pending_req_wait_v2") int req_pending_req_wait_v2(uint32_t req_handle, fastly_host_http_send_error_detail *send_error_detail, uint32_t *resp_handle_out, uint32_t *resp_body_handle_out); WASM_IMPORT("fastly_http_req", "inspect") int req_inspect(uint32_t req_handle, uint32_t body_handle, req_inspect_config_options_mask config_options_mask, fastly_host_http_inspect_options *config, uint8_t *inspect_res_buf, uint32_t inspect_res_buf_len, size_t *nwritten_out); // Module fastly_http_resp WASM_IMPORT("fastly_http_resp", "new") int resp_new(uint32_t *resp_handle_out); WASM_IMPORT("fastly_http_resp", "header_names_get") int resp_header_names_get(uint32_t resp_handle, uint8_t *buf, size_t buf_len, uint32_t cursor, int64_t *ending_cursor, size_t *nwritten); WASM_IMPORT("fastly_http_resp", "header_values_get") int resp_header_values_get(uint32_t resp_handle, const char *name, size_t name_len, uint8_t *buf, size_t buf_len, uint32_t cursor, int64_t *ending_cursor, size_t *nwritten); WASM_IMPORT("fastly_http_req", "header_values_set") int req_header_values_set(uint32_t req_handle, const char *name, size_t name_len, const uint8_t *values, size_t values_len); WASM_IMPORT("fastly_http_resp", "header_insert") int resp_header_insert(uint32_t resp_handle, const char *name, size_t name_len, const uint8_t *value, size_t value_len); WASM_IMPORT("fastly_http_resp", "header_append") int resp_header_append(uint32_t resp_handle, const char *name, size_t name_len, const uint8_t *value, size_t value_len); WASM_IMPORT("fastly_http_resp", "header_remove") int resp_header_remove(uint32_t resp_handle, const char *name, size_t name_len); WASM_IMPORT("fastly_http_resp", "version_get") int resp_version_get(uint32_t resp_handle, uint32_t *version_out); WASM_IMPORT("fastly_http_resp", "send_downstream") int resp_send_downstream(uint32_t resp_handle, uint32_t body_handle, uint32_t streaming); WASM_IMPORT("fastly_http_resp", "status_get") int resp_status_get(uint32_t resp_handle, uint16_t *status_out); WASM_IMPORT("fastly_http_resp", "status_set") int resp_status_set(uint32_t resp_handle, uint16_t status); WASM_IMPORT("fastly_http_resp", "framing_headers_mode_set") int resp_framing_headers_mode_set(uint32_t resp_handle, uint32_t mode); WASM_IMPORT("fastly_http_resp", "get_addr_dest_ip") int resp_ip_get(uint32_t resp_handle, uint8_t *ip_out, size_t *nwritten); WASM_IMPORT("fastly_http_resp", "get_addr_dest_port") int resp_port_get(uint32_t resp_handle, uint16_t *port_out); // Module fastly_dictionary WASM_IMPORT("fastly_dictionary", "open") int dictionary_open(const char *name, size_t name_len, uint32_t *dict_handle_out); WASM_IMPORT("fastly_dictionary", "get") int dictionary_get(uint32_t dict_handle, const char *key, size_t key_len, char *value, size_t value_max_len, size_t *nwritten); // Module fastly_config_store WASM_IMPORT("fastly_config_store", "open") int config_store_open(const char *name, size_t name_len, uint32_t *dict_handle_out); WASM_IMPORT("fastly_config_store", "get") int config_store_get(uint32_t dict_handle, const char *key, size_t key_len, char *value, size_t value_max_len, size_t *nwritten); // Module fastly_secret_store WASM_IMPORT("fastly_secret_store", "open") int secret_store_open(const char *name, size_t name_len, uint32_t *dict_handle_out); WASM_IMPORT("fastly_secret_store", "get") int secret_store_get(uint32_t dict_handle, const char *key, size_t key_len, uint32_t *opt_secret_handle_out); WASM_IMPORT("fastly_secret_store", "plaintext") int secret_store_plaintext(uint32_t secret_handle, char *buf, size_t buf_len, size_t *nwritten); WASM_IMPORT("fastly_secret_store", "from_bytes") int secret_store_from_bytes(char *buf, size_t buf_len, uint32_t *opt_secret_handle_out); // Module fastly_object_store WASM_IMPORT("fastly_object_store", "open") int object_store_open(const char *name, size_t name_len, uint32_t *object_store_handle_out); WASM_IMPORT("fastly_object_store", "lookup") int object_store_get(uint32_t object_store_handle, const char *key, size_t key_len, uint32_t *opt_body_handle_out); WASM_IMPORT("fastly_object_store", "lookup_async") int object_store_get_async(uint32_t object_store_handle, const char *key, size_t key_len, uint32_t *pending_object_store_lookup_handle_out); WASM_IMPORT("fastly_object_store", "pending_lookup_wait") int object_store_pending_lookup_wait(uint32_t handle, uint32_t *handle_out); WASM_IMPORT("fastly_object_store", "delete_async") int object_store_delete_async(uint32_t object_store_handle, const char *key, size_t key_len, uint32_t *pending_object_store_lookup_handle_out); WASM_IMPORT("fastly_object_store", "pending_delete_wait") int object_store_pending_delete_wait(uint32_t handle); WASM_IMPORT("fastly_object_store", "insert") int object_store_insert(uint32_t object_store_handle, const char *key, size_t key_len, uint32_t body_handle); // Module fastly_kv_store #define KV_LOOKUP_CONFIG_RESERVED (1u << 0) typedef struct __attribute__((aligned(4))) KVLookupOptions { uint32_t reserved; } KVLookupOptions; #define KV_INSERT_CONFIG_RESERVED (1u << 0) #define KV_INSERT_CONFIG_BACKGROUND_FETCH (1u << 1) #define KV_INSERT_CONFIG_RESERVED_2 (1u << 2) #define KV_INSERT_CONFIG_METADATA (1u << 3) #define KV_INSERT_CONFIG_TIME_TO_LIVE_SEC (1u << 4) #define KV_INSERT_CONFIG_IF_GENERATION_MATCH (1u << 5) #define KV_INSERT_MODE_OVERWRITE 0u #define KV_INSERT_MODE_ADD 1u #define KV_INSERT_MODE_APPEND 2u #define KV_INSERT_MODE_PREPEND 3u typedef struct __attribute__((aligned(4))) KVInsertOptions { uint32_t mode; uint32_t reserved; const uint8_t *metadata; uint32_t metadata_len; uint32_t time_to_live_sec; uint64_t if_generation_match; } KVInsertOptions; #define KV_DELETE_CONFIG_RESERVED (1u << 0) typedef struct __attribute__((aligned(4))) KVDeleteOptions { uint32_t reserved; } KVDeleteOptions; #define KV_LIST_CONFIG_RESERVED (1u << 0) #define KV_LIST_CONFIG_CURSOR (1u << 1) #define KV_LIST_CONFIG_LIMIT (1u << 2) #define KV_LIST_CONFIG_PREFIX (1u << 3) #define KV_LIST_MODE_STRONG 0u #define KV_LIST_MODE_EVENTUAL 1u typedef struct __attribute__((aligned(4))) KVListOptions { uint32_t mode; const uint8_t *cursor; uint32_t cursor_len; uint32_t limit; const uint8_t *prefix; uint32_t prefix_len; } KVListOptions; #define KV_ERROR_UNINITIALIZED 0u #define KV_ERROR_OK 1u #define KV_ERROR_BAD_REQUEST 2u #define KV_ERROR_NOT_FOUND 3u #define KV_ERROR_PRECONDITION_FAILED 4u #define KV_ERROR_PAYLOAD_TOO_LARGE 5u #define KV_ERROR_INTERNAL_ERROR 6u #define KV_ERROR_TOO_MANY_REQUESTS 7u WASM_IMPORT("fastly_kv_store", "open") int kv_store_open(const char *name, size_t name_len, uint32_t *kv_store_handle_out); WASM_IMPORT("fastly_kv_store", "lookup") int kv_store_lookup(uint32_t kv_store_handle, const char *key, size_t key_len, uint32_t lookup_options_mask, KVLookupOptions *lookup_options, uint32_t *kv_store_lookup_handle_out); WASM_IMPORT("fastly_kv_store", "lookup_wait") int kv_store_lookup_wait(uint32_t kv_store_handle_lookup_handle, uint32_t *body_handle_out, uint8_t *metadata_buf_out, size_t metadata_buf_len, size_t *nwritten_out, uint32_t *generation_out, uint32_t *kv_error_out); WASM_IMPORT("fastly_kv_store", "lookup_wait_v2") int kv_store_lookup_wait_v2(uint32_t kv_store_handle_lookup_handle, uint32_t *body_handle_out, uint8_t *metadata_buf_out, size_t metadata_buf_len, size_t *nwritten_out, uint64_t *generation_out, uint32_t *kv_error_out); WASM_IMPORT("fastly_kv_store", "insert") int kv_store_insert(uint32_t kv_store_handle, const char *key, size_t key_len, uint32_t body_handle, uint32_t insert_options_mask, KVInsertOptions *insert_options, uint32_t *kv_store_insert_handle_out); WASM_IMPORT("fastly_kv_store", "insert_wait") int kv_store_insert_wait(uint32_t kv_store_insert_handle, uint32_t *kv_error_out); WASM_IMPORT("fastly_kv_store", "delete") int kv_store_delete(uint32_t handle, const char *key, size_t key_len, uint32_t delete_options_mask, KVDeleteOptions *delete_options, uint32_t *kv_store_delete_handle_out); WASM_IMPORT("fastly_kv_store", "delete_wait") int kv_store_delete_wait(uint32_t kv_store_delete_handle, uint32_t *kv_error_out); WASM_IMPORT("fastly_kv_store", "list") int kv_store_list(uint32_t kv_store_handle, uint32_t list_options_mask, KVListOptions *list_options, uint32_t *kv_store_list_handle_out); WASM_IMPORT("fastly_kv_store", "list_wait") int kv_store_list_wait(uint32_t kv_store_list_handle, uint32_t *body_handle_out, uint32_t *kv_error_out); WASM_IMPORT("fastly_geo", "lookup") int geo_lookup(const uint8_t *addr_octets, size_t addr_len, char *buf, size_t buf_len, size_t *nwritten); WASM_IMPORT("wasi_snapshot_preview1", "random_get") int32_t random_get(int32_t arg0, int32_t arg1); // Blocks until one of the given objects is ready for I/O, or the optional timeout expires. // // Valid object handles includes bodies and pending requests. See the `async_item_handle` // definition for more details, including what I/O actions are associated with each handle // type. // // The timeout is specified in milliseconds, or 0 if no timeout is desired. // // Returns the _index_ (not handle!) of the first object that is ready, or u32::MAX if the // timeout expires before any objects are ready for I/O. WASM_IMPORT("fastly_async_io", "select") int async_select(uint32_t handles[], size_t handles_len, uint32_t timeout_ms, uint32_t *ready_idx_out); // Returns 1 if the given async item is "ready" for its associated I/O action, 0 otherwise. // // If an object is ready, the I/O action is guaranteed to complete without blocking. // // Valid object handles includes bodies and pending requests. See the `async_item_handle` // definition for more details, including what I/O actions are associated with each handle // type. WASM_IMPORT("fastly_async_io", "is_ready") int async_is_ready(uint32_t handle, uint32_t *is_ready_out); typedef struct __attribute__((aligned(4))) PurgeOptions { uint8_t *ret_buf_ptr; size_t ret_buf_len; size_t *ret_buf_nwritten_out; } PurgeOptions; #define FASTLY_HOST_PURGE_OPTIONS_MASK_SOFT_PURGE (1 << 0) #define FASTLY_HOST_PURGE_OPTIONS_MASK_RET_BUF (1 << 1) WASM_IMPORT("fastly_purge", "purge_surrogate_key") int purge_surrogate_key(char *surrogate_key, size_t surrogate_key_len, uint32_t options_mask, PurgeOptions *purge_options); #define FASTLY_CACHE_LOOKUP_OPTIONS_MASK_RESERVED (1 << 0) #define FASTLY_CACHE_LOOKUP_OPTIONS_MASK_REQUEST_HEADERS (1 << 1) // Extensible options for cache lookup operations currently used for both `lookup` and // `transaction_lookup`. typedef struct __attribute__((aligned(4))) fastly_host_cache_lookup_options { // * A full request handle, but used only for its headers uint32_t request_headers; } fastly_host_cache_lookup_options; // Configuration for several hostcalls that write to the cache: // - `insert` // - `transaction-insert` // - `transaction-insert-and-stream-back` // - `transaction-update` // // Some options are only allowed for certain of these hostcalls see `cache-write-options-mask`. typedef struct fastly_host_cache_write_options { // this is a required field there's no flag for it uint64_t max_age_ns; // a full request handle, but used only for its headers uint32_t request_headers; // a list of header names separated by spaces fastly_world_string vary_rule; // The initial age of the object in nanoseconds (default: 0). // // This age is used to determine the freshness lifetime of the object as well as to // prioritize which variant to return if a subsequent lookup matches more than one vary rule uint64_t initial_age_ns; uint64_t stale_while_revalidate_ns; // a list of surrogate keys separated by spaces fastly_world_string surrogate_keys; uint64_t length; fastly_world_list_u8 user_metadata; bool sensitive_data; } fastly_host_cache_write_options; // a cached object was found #define FASTLY_HOST_CACHE_LOOKUP_STATE_FOUND (1 << 0) // the cached object is valid to use (implies found) #define FASTLY_HOST_CACHE_LOOKUP_STATE_USABLE (1 << 1) // the cached object is stale (but may or may not be valid to use) #define FASTLY_HOST_CACHE_LOOKUP_STATE_STALE (1 << 2) // this client is requested to insert or revalidate an object #define FASTLY_HOST_CACHE_LOOKUP_STATE_MUST_INSERT_OR_UPDATE (1 << 3) WASM_IMPORT("fastly_cache", "lookup") int cache_lookup(char *cache_key, size_t cache_key_len, uint32_t options_mask, fastly_host_cache_lookup_options *options, uint32_t *ret); typedef struct __attribute__((aligned(8))) { uint64_t max_age_ns; uint32_t request_headers; const uint8_t *vary_rule_ptr; size_t vary_rule_len; uint64_t initial_age_ns; uint64_t stale_while_revalidate_ns; const uint8_t *surrogate_keys_ptr; size_t surrogate_keys_len; uint64_t length; const uint8_t *user_metadata_ptr; size_t user_metadata_len; } CacheWriteOptions; WASM_IMPORT("fastly_cache", "insert") int cache_insert(char *cache_key, size_t cache_key_len, uint32_t options_mask, CacheWriteOptions *options, uint32_t *ret); WASM_IMPORT("fastly_cache", "transaction_lookup") int cache_transaction_lookup(char *cache_key, size_t cache_key_len, uint32_t options_mask, fastly_host_cache_lookup_options *options, uint32_t *ret); WASM_IMPORT("fastly_cache", "transaction_insert") int cache_transaction_insert(uint32_t handle, uint32_t options_mask, CacheWriteOptions *options, uint32_t *ret); WASM_IMPORT("fastly_cache", "transaction_insert_and_stream_back") int cache_transaction_insert_and_stream_back(uint32_t handle, uint32_t options_mask, CacheWriteOptions *options, uint32_t *ret_body, uint32_t *ret_cache); WASM_IMPORT("fastly_cache", "transaction_update") int cache_transaction_update(uint32_t handle, uint32_t options_mask, CacheWriteOptions *options); WASM_IMPORT("fastly_cache", "transaction_cancel") int cache_transaction_cancel(uint32_t handle); WASM_IMPORT("fastly_cache", "close") int cache_close(uint32_t handle); WASM_IMPORT("fastly_cache", "get_state") int cache_get_state(uint32_t handle, uint8_t *ret); WASM_IMPORT("fastly_cache", "get_user_metadata") int cache_get_user_metadata(uint32_t handle, char *buf, size_t buf_len, size_t *nread); #define FASTLY_HOST_CACHE_GET_BODY_OPTIONS_MASK_RESERVED (1 << 0) #define FASTLY_HOST_CACHE_GET_BODY_OPTIONS_MASK_START (1 << 1) #define FASTLY_HOST_CACHE_GET_BODY_OPTIONS_MASK_END (1 << 2) typedef struct fastly_host_cache_get_body_options { uint64_t start; uint64_t end; } fastly_host_cache_get_body_options; WASM_IMPORT("fastly_cache", "get_body") int cache_get_body(uint32_t handle, uint32_t options_mask, fastly_host_cache_get_body_options *options, uint32_t *ret); // Returns 1 if a backend with this name exists. WASM_IMPORT("fastly_backend", "exists") int backend_exists(const char *name, size_t name_len, uint32_t *exists_out); #define FASTLY_HOST_BACKEND_BACKEND_HEALTH_UNKNOWN 0 #define FASTLY_HOST_BACKEND_BACKEND_HEALTH_HEALTHY 1 #define FASTLY_HOST_BACKEND_BACKEND_HEALTH_UNHEALTHY 2 // Returns 1 if a backend is healthy. WASM_IMPORT("fastly_backend", "is_healthy") int backend_is_healthy(const char *name, size_t name_len, uint32_t *is_healthy_out); WASM_IMPORT("fastly_backend", "is_dynamic") int backend_is_dynamic(const char *name, size_t name_len, uint32_t *is_dynamic_out); WASM_IMPORT("fastly_backend", "get_host") int backend_get_host(const char *name, size_t name_len, uint8_t *value, size_t value_max_len, size_t *nwritten); WASM_IMPORT("fastly_backend", "get_override_host") int backend_get_override_host(const char *name, size_t name_len, uint8_t *value, size_t value_max_len, size_t *nwritten); WASM_IMPORT("fastly_backend", "get_port") int backend_get_port(const char *name, size_t name_len, uint16_t *port_out); WASM_IMPORT("fastly_backend", "get_connect_timeout_ms") int backend_get_connect_timeout_ms(const char *name, size_t name_len, uint32_t *timeout_ms); WASM_IMPORT("fastly_backend", "get_first_byte_timeout_ms") int backend_get_first_byte_timeout_ms(const char *name, size_t name_len, uint32_t *timeout_ms); WASM_IMPORT("fastly_backend", "get_between_bytes_timeout_ms") int backend_get_between_bytes_timeout_ms(const char *name, size_t name_len, uint32_t *timeout_ms); WASM_IMPORT("fastly_backend", "get_http_keepalive_time") int backend_get_http_keepalive_time(const char *name, size_t name_len, uint32_t *timeout_ms); WASM_IMPORT("fastly_backend", "get_tcp_keepalive_enable") int backend_get_tcp_keepalive_enable(const char *name, size_t name_len, uint32_t *is_keepalive); WASM_IMPORT("fastly_backend", "get_tcp_keepalive_interval") int backend_get_tcp_keepalive_interval(const char *name, size_t name_len, uint32_t *timeout_ms); WASM_IMPORT("fastly_backend", "get_tcp_keepalive_probes") int backend_get_tcp_keepalive_probes(const char *name, size_t name_len, uint32_t *probe_count); WASM_IMPORT("fastly_backend", "get_tcp_keepalive_time") int backend_get_tcp_keepalive_time(const char *name, size_t name_len, uint32_t *timeout_secs); WASM_IMPORT("fastly_backend", "is_ssl") int backend_is_ssl(const char *name, size_t name_len, uint32_t *is_ssl); WASM_IMPORT("fastly_backend", "get_ssl_min_version") int backend_get_ssl_min_version(const char *name, size_t name_len, uint32_t *ssl_min_version); WASM_IMPORT("fastly_backend", "get_ssl_max_version") int backend_get_ssl_max_version(const char *name, size_t name_len, uint32_t *ssl_max_version); WASM_IMPORT("fastly_cache", "get_length") int cache_get_length(uint32_t handle, uint64_t *ret); WASM_IMPORT("fastly_cache", "get_max_age_ns") int cache_get_max_age_ns(uint32_t handle, uint64_t *ret); WASM_IMPORT("fastly_cache", "get_stale_while_revalidate_ns") int cache_get_stale_while_revalidate_ns(uint32_t handle, uint64_t *ret); WASM_IMPORT("fastly_cache", "get_age_ns") int cache_get_age_ns(uint32_t handle, uint64_t *ret); WASM_IMPORT("fastly_cache", "get_hits") int cache_get_hits(uint32_t handle, uint64_t *ret); WASM_IMPORT("fastly_erl", "check_rate") int check_rate(const char *rc, size_t rc_len, const char *entry, size_t entry_len, uint32_t delta, uint32_t window, uint32_t limit, const char *pb, size_t pb_len, uint32_t ttl, bool *blocked_out); WASM_IMPORT("fastly_erl", "ratecounter_increment") int ratecounter_increment(const char *rc, size_t rc_len, const char *entry, size_t entry_len, uint32_t delta); WASM_IMPORT("fastly_erl", "ratecounter_lookup_rate") int ratecounter_lookup_rate(const char *rc, size_t rc_len, const char *entry, size_t entry_len, uint32_t window, uint32_t *rate_out); WASM_IMPORT("fastly_erl", "ratecounter_lookup_count") int ratecounter_lookup_count(const char *rc, size_t rc_len, const char *entry, size_t entry_len, uint32_t duration, uint32_t *count_out); WASM_IMPORT("fastly_erl", "penaltybox_add") int penaltybox_add(const char *pb, size_t pb_len, const char *entry, size_t entry_len, uint32_t ttl); WASM_IMPORT("fastly_erl", "penaltybox_has") int penaltybox_has(const char *pb, size_t pb_len, const char *entry, size_t entry_len, bool *has_out); WASM_IMPORT("fastly_device_detection", "lookup") int device_detection_lookup(const char *user_agent, size_t user_agent_len, const char *buf, size_t buf_len, size_t *nwritten); WASM_IMPORT("fastly_compute_runtime", "get_vcpu_ms") int compute_get_vcpu_ms(uint64_t *vcpu_ms); WASM_IMPORT("fastly_compute_runtime", "get_heap_mib") int compute_get_heap_mib(uint32_t *heap_mib); // ACL handle type typedef uint32_t fastly_acl_handle; // ACL error enum typedef uint32_t fastly_acl_error; #define FASTLY_ACL_ERROR_UNINITIALIZED 0 #define FASTLY_ACL_ERROR_OK 1 #define FASTLY_ACL_ERROR_NO_CONTENT 2 #define FASTLY_ACL_ERROR_TOO_MANY_REQUESTS 3 // ACL host calls WASM_IMPORT("fastly_acl", "open") int acl_open(const char *name, size_t name_len, uint32_t *acl_handle_out); WASM_IMPORT("fastly_acl", "lookup") int acl_lookup(uint32_t acl_handle, const uint8_t *ip_octets, size_t ip_len, uint32_t *body_handle_out, fastly_acl_error *acl_error_out); typedef struct __attribute__((aligned(8))) fastly_image_optimizer_transform_config { const char *sdk_claims_opts; size_t sdk_claims_opts_len; } fastly_image_optimizer_transform_config; #define FASTLY_IMAGE_OPTIMIZER_RESERVED (1u << 0) #define FASTLY_IMAGE_OPTIMIZER_SDK_CLAIMS_OPTS (1u << 1) #define FASTLY_IMAGE_OPTIMIZER_ERROR_TAG_UNINITIALIZED 0 #define FASTLY_IMAGE_OPTIMIZER_ERROR_TAG_OK 1 #define FASTLY_IMAGE_OPTIMIZER_ERROR_TAG_ERROR 2 #define FASTLY_IMAGE_OPTIMIZER_ERROR_TAG_WARNING 3 typedef struct __attribute__((aligned(8))) fastly_image_optimizer_error_detail { uint32_t tag; const char *message; size_t message_len; } fastly_image_optimizer_error_detail; WASM_IMPORT("fastly_image_optimizer", "transform_image_optimizer_request") int image_optimizer_transform_image_optimizer_request( uint32_t req_handle, uint32_t body_handle, const char *backend, size_t backend_len, int io_transform_config_mask, fastly_image_optimizer_transform_config *io_transform_config, fastly_image_optimizer_error_detail *io_error_detail, uint32_t *resp_handle_out, uint32_t *resp_body_handle_out); #define FASTLY_SHIELDING_SHIELD_BACKEND_OPTIONS_RESERVED (1 << 0) #define FASTLY_SHIELDING_SHIELD_BACKEND_OPTIONS_CACHE_KEY (1 << 1) #define FASTLY_SHIELDING_SHIELD_BACKEND_OPTIONS_FIRST_BYTE_TIMEOUT (1 << 2) struct fastly_shielding_shield_backend_config { const char *cache_key; uint32_t cache_key_len; uint32_t first_byte_timeout_ms; }; WASM_IMPORT("fastly_shielding", "shield_info") int fastly_shielding_shield_info(const char *name, size_t name_len, char *info_block, size_t info_block_len, uint32_t *nwritten_out); WASM_IMPORT("fastly_shielding", "backend_for_shield") int fastly_shielding_backend_for_shield( const char *name, size_t name_len, uint32_t options_mask, const fastly_shielding_shield_backend_config *backend_config, char *backend_name, size_t backend_name_len, uint32_t *nwritten_out); #ifdef __cplusplus } // namespace fastly } // extern C #endif #endif ================================================ FILE: runtime/fastly/host-api/host_api.cmake ================================================ add_library(host_api STATIC ${HOST_API}/host_api.cpp ${HOST_API}/host_call.cpp ) target_link_libraries(host_api PRIVATE spidermonkey) target_include_directories(host_api PRIVATE include) target_include_directories(host_api PRIVATE ${HOST_API}) target_include_directories(host_api PUBLIC ${HOST_API}/include) ================================================ FILE: runtime/fastly/host-api/host_api.cpp ================================================ #include #include #include "../../StarlingMonkey/runtime/allocator.h" #include "../../StarlingMonkey/runtime/encode.h" #include "./fastly.h" #include "./host_api_fastly.h" #include #include #include using api::FastlyResult; using fastly::FastlyAPIError; #if defined(DEBUG) static void log_hostcall(const char *func_name, ...) { std::stringstream ss; ss << "HOSTCALL: " << func_name << "("; va_list args; va_start(args, func_name); const auto *arg = va_arg(args, const std::string_view *); if (arg) { ss << std::string_view(arg->data(), arg->size()); while ((arg = va_arg(args, const std::string_view *))) { ss << ", " << std::string_view(arg->data(), arg->size()); } } ss << ")"; va_end(args); fastly_push_debug_message(ss.str()); } #define TRACE_CALL() log_hostcall(__func__); #define TRACE_CALL_ARGS(...) log_hostcall(__func__, __VA_ARGS__, nullptr); #define TRACE_CALL_RET(...) log_hostcall(__func__, std::string_view("-> "), __VA_ARGS__, nullptr); #define TSV(s) std::string_view(s) #else #define TRACE_CALL() #define TRACE_CALL_ARGS(...) #define TRACE_CALL_RET(...) #endif #define NEVER_HANDLE 0xFFFFFFFD #define MILLISECS_IN_NANOSECS 1000000 #define SECS_IN_NANOSECS 1000000000 static bool convert_result(int res, fastly::fastly_host_error *err) { if (res == 0) return true; switch (res) { case 1: *err = FASTLY_HOST_ERROR_GENERIC_ERROR; break; case 2: *err = FASTLY_HOST_ERROR_INVALID_ARGUMENT; break; case 3: *err = FASTLY_HOST_ERROR_BAD_HANDLE; break; case 4: *err = FASTLY_HOST_ERROR_BUFFER_LEN; break; case 5: *err = FASTLY_HOST_ERROR_UNSUPPORTED; break; case 6: *err = FASTLY_HOST_ERROR_BAD_ALIGN; break; case 7: *err = FASTLY_HOST_ERROR_HTTP_INVALID; break; case 8: *err = FASTLY_HOST_ERROR_HTTP_USER; break; case 9: *err = FASTLY_HOST_ERROR_HTTP_INCOMPLETE; break; case 10: *err = FASTLY_HOST_ERROR_OPTIONAL_NONE; break; case 11: *err = FASTLY_HOST_ERROR_HTTP_HEAD_TOO_LARGE; break; case 12: *err = FASTLY_HOST_ERROR_HTTP_INVALID_STATUS; break; case 13: *err = FASTLY_HOST_ERROR_LIMIT_EXCEEDED; break; case 100: *err = FASTLY_HOST_ERROR_UNKNOWN_ERROR; break; default: *err = FASTLY_HOST_ERROR_UNKNOWN_ERROR; } return false; } void sleep_until(uint64_t time_ns, uint64_t now) { while (time_ns > now) { uint64_t duration = time_ns - now; timespec req{.tv_sec = static_cast(duration / SECS_IN_NANOSECS), .tv_nsec = static_cast(duration % SECS_IN_NANOSECS)}; timespec rem; nanosleep(&req, &rem); now = host_api::MonotonicClock::now(); } } size_t api::AsyncTask::select(std::vector &tasks) { if (tasks.size() == 0) { TRACE_CALL() } else { std::string arg0 = std::to_string(tasks.at(0)->handle_); if (tasks.size() == 1) { TRACE_CALL_ARGS(TSV(arg0)) } else { std::string arg1 = std::to_string(tasks.at(1)->handle_); if (tasks.size() == 2) { TRACE_CALL_ARGS(TSV(arg0), TSV(arg1)) } else { std::string arg2 = std::to_string(tasks.at(2)->handle_); TRACE_CALL_ARGS(TSV(arg0), TSV(arg1), TSV(arg2)) } } } size_t tasks_len = tasks.size(); std::vector handles; handles.reserve(tasks_len); uint64_t now = 0; uint64_t soonest_deadline = 0; size_t soonest_deadline_idx = -1; for (size_t idx = 0; idx < tasks_len; ++idx) { auto *task = tasks.at(idx); uint64_t deadline; if (task->id() == IMMEDIATE_TASK_HANDLE) { if (now == 0) { now = host_api::MonotonicClock::now(); MOZ_ASSERT(now > 0); } deadline = now; } else { deadline = task->deadline(); } if (deadline > 0) { MOZ_ASSERT(task->id() == NEVER_HANDLE || task->id() == IMMEDIATE_TASK_HANDLE); if (now == 0) { now = host_api::MonotonicClock::now(); MOZ_ASSERT(now > 0); } // expired timers treated as immediates if (deadline < now) { deadline = now; } // this check will always only select the first immediate if (soonest_deadline == 0 || deadline < soonest_deadline) { soonest_deadline = deadline; soonest_deadline_idx = idx; } } else { uint32_t handle = task->id(); // Timer and immediate task handles are skipped and never passed to the host. MOZ_ASSERT(handle != NEVER_HANDLE && handle != IMMEDIATE_TASK_HANDLE); handles.push_back(handle); } } // When there are no async tasks, sleep until the deadline if (handles.size() == 0) { MOZ_ASSERT(soonest_deadline >= now); sleep_until(soonest_deadline, now); return soonest_deadline_idx; } uint32_t ret = UINT32_MAX; fastly::fastly_host_error err = 0; // only immediate timers in the task list -> do a ready check against all handles instead of a // select if (now != 0 && soonest_deadline == now) { for (ret = 0; ret < handles.size(); ++ret) { auto handle = handles.at(ret); uint32_t is_ready_out; if (!convert_result(fastly::async_is_ready(handle, &is_ready_out), &err)) { if (host_api::error_is_bad_handle(err)) { fprintf(stderr, "Critical Error: An invalid handle was provided to async_is_ready.\n"); } else { fprintf(stderr, "Critical Error: An unknown error occurred in async_is_ready.\n"); } abort(); }; if (is_ready_out) { size_t task_idx = 0; for (size_t idx = 0; idx < tasks_len; ++idx) { uint32_t handle = tasks.at(idx)->id(); if (handle != NEVER_HANDLE && handle != IMMEDIATE_TASK_HANDLE) { if (ret == task_idx) { return idx; } task_idx++; } } abort(); } } // no tasks ready -> trigger our soonest immediate or timer return soonest_deadline_idx; } while (true) { MOZ_ASSERT(soonest_deadline == 0 || soonest_deadline >= now); // timeout value of 0 means no timeout for async_select uint32_t timeout = soonest_deadline > 0 ? (soonest_deadline - now) / MILLISECS_IN_NANOSECS : 0; if (!convert_result(fastly::async_select(handles.data(), handles.size(), timeout, &ret), &err)) { if (host_api::error_is_bad_handle(err)) { fprintf(stderr, "Critical Error: An invalid handle was provided to async_select.\n"); } else { fprintf(stderr, "Critical Error: An unknown error occurred in async_select.\n"); } abort(); } // The result is only valid if the timeout didn't expire. if (ret != UINT32_MAX) { // The host index will be the index in the list of tasks with the timer tasks filtered out. // We thus need to offset the host index by any timer tasks appearing before the nth // non-timer task. size_t task_idx = 0; for (size_t idx = 0; idx < tasks_len; ++idx) { uint32_t id = tasks.at(idx)->id(); if (id != NEVER_HANDLE && id != IMMEDIATE_TASK_HANDLE) { if (ret == task_idx) { return idx; } task_idx++; } } abort(); } else if (soonest_deadline > 0) { MOZ_ASSERT(soonest_deadline > now); MOZ_ASSERT(soonest_deadline_idx != -1); // Verify that the task definitely is ready from a time perspective, and if not loop the host // call again. now = host_api::MonotonicClock::now(); if (soonest_deadline > now) { err = 0; continue; } return soonest_deadline_idx; } else { abort(); } } } namespace host_api { namespace { fastly::fastly_world_list_u8 span_to_list_u8(std::span span) { return { .ptr = const_cast(span.data()), .len = span.size(), }; } fastly::fastly_world_string string_view_to_world_string(std::string_view str) { return { .ptr = const_cast(reinterpret_cast(str.data())), .len = str.size(), }; } HostString make_host_string(fastly::fastly_world_string str) { return HostString{JS::UniqueChars{reinterpret_cast(str.ptr)}, str.len}; } HostString make_host_string(fastly::fastly_world_list_u8 str) { return HostString{JS::UniqueChars{reinterpret_cast(str.ptr)}, str.len}; } HostBytes make_host_bytes(uint8_t *ptr, size_t len) { return HostBytes{std::unique_ptr{ptr}, len}; } Response make_response(fastly::fastly_host_http_response &resp) { return Response{HttpResp{resp.f0}, HttpBody{resp.f1}}; } template Result> generic_get_header_names(auto handle) { Result> res; fastly::fastly_world_list_string ret; fastly::fastly_host_error err; fastly::fastly_world_string *strs = static_cast( cabi_malloc(LIST_ALLOC_SIZE * sizeof(fastly::fastly_world_string), 1)); size_t str_max = LIST_ALLOC_SIZE; size_t str_cnt = 0; size_t nwritten; uint8_t *buf = static_cast(cabi_malloc(HOSTCALL_BUFFER_LEN, 1)); uint32_t cursor = 0; int64_t next_cursor = 0; while (true) { if (!convert_result( header_names_get(handle, buf, HEADER_MAX_LEN, cursor, &next_cursor, &nwritten), &err)) { cabi_free(buf); cabi_free(strs); res.emplace_err(err); return res; } if (nwritten == 0) { break; } uint32_t offset = 0; for (size_t i = 0; i < nwritten; i++) { if (buf[i] != '\0') continue; if (str_cnt == str_max) { strs = static_cast( cabi_realloc(strs, str_max * sizeof(fastly::fastly_world_string), 1, (str_max + LIST_ALLOC_SIZE) * sizeof(fastly::fastly_world_string))); str_max += LIST_ALLOC_SIZE; } size_t len = i - offset; strs[str_cnt].ptr = static_cast(cabi_malloc(len, 1)); strs[str_cnt].len = len; memcpy(strs[str_cnt].ptr, buf + offset, len); offset = i + 1; str_cnt++; } if (next_cursor < 0) break; cursor = (uint32_t)next_cursor; } cabi_free(buf); if (str_cnt != 0) { strs = static_cast( cabi_realloc(strs, str_max * sizeof(fastly::fastly_world_string), 1, str_cnt * sizeof(fastly::fastly_world_string))); } ret.ptr = strs; ret.len = str_cnt; std::vector names; for (int i = 0; i < ret.len; i++) { names.emplace_back(make_host_string(ret.ptr[i])); } // Free the vector of string pointers, but leave the individual strings alone. cabi_free(ret.ptr); res.emplace(std::move(names)); return res; } struct Chunk { JS::UniqueChars buffer; size_t length; static Chunk make(std::string_view data) { Chunk res{JS::UniqueChars{static_cast(cabi_malloc(data.size(), 1))}, data.size()}; std::copy(data.begin(), data.end(), res.buffer.get()); return res; } }; template Result>> generic_get_header_values(auto handle, std::string_view name) { Result>> res; fastly::fastly_world_string hdr = string_view_to_world_string(name); fastly::fastly_world_option_list_list_u8 ret; fastly::fastly_host_error err; std::vector header_values; JS::UniqueLatin1Chars buffer(static_cast(cabi_malloc(HEADER_MAX_LEN, 1))); uint32_t cursor = 0; while (true) { int64_t ending_cursor = 0; size_t length = 0; if (!convert_result(header_values_get(handle, reinterpret_cast(hdr.ptr), hdr.len, buffer.get(), HEADER_MAX_LEN, cursor, &ending_cursor, &length), &err)) { res.emplace_err(err); return res; } if (length == 0) { break; } std::string_view result{reinterpret_cast(buffer.get()), length}; while (!result.empty()) { auto end = result.find('\0'); header_values.emplace_back(Chunk::make(result.substr(0, end))); if (end == result.npos) { break; } result = result.substr(end + 1); } if (ending_cursor < 0) { break; } } if (header_values.empty()) { ret.is_some = false; } else { ret.is_some = true; ret.val.len = header_values.size(); ret.val.ptr = static_cast( cabi_malloc(header_values.size() * sizeof(fastly::fastly_world_list_u8), alignof(fastly::fastly_world_list_u8))); auto *next = ret.val.ptr; for (auto &chunk : header_values) { next->len = chunk.length; next->ptr = reinterpret_cast(chunk.buffer.release()); ++next; } } if (ret.is_some) { std::vector names; for (int i = 0; i < ret.val.len; i++) { names.emplace_back(make_host_string(ret.val.ptr[i])); } // Free the vector of string pointers, but leave the individual strings alone. cabi_free(ret.val.ptr); res.emplace(std::move(names)); } else { res.emplace(std::nullopt); } return res; } template Result generic_header_op(auto handle, std::string_view name, std::span value) { Result res; fastly::fastly_world_string hdr = string_view_to_world_string(name); fastly::fastly_world_list_u8 val = span_to_list_u8(value); fastly::fastly_host_error err; if (!convert_result( header_op(handle, reinterpret_cast(hdr.ptr), hdr.len, val.ptr, val.len), &err)) { res.emplace_err(err); } return res; } template Result generic_header_remove(auto handle, std::string_view name) { Result res; fastly::fastly_world_string hdr = string_view_to_world_string(name); fastly::fastly_host_error err; if (!convert_result(remove_header(handle, reinterpret_cast(hdr.ptr), hdr.len), &err)) { if (host_api::error_is_invalid_argument(err)) { return Result::ok(); } res.emplace_err(err); } return res; } } // namespace // --- --- Result Random::get_bytes(size_t num_bytes) { TRACE_CALL() Result res; auto ret = HostBytes::with_capacity(num_bytes); auto err = fastly::random_get(reinterpret_cast(static_cast(ret.begin())), num_bytes); if (err != 0) { res.emplace_err(err); } else { res.emplace(std::move(ret)); } return res; } Result Random::get_u32() { TRACE_CALL() Result res; uint32_t storage; auto err = fastly::random_get(reinterpret_cast(static_cast(&storage)), sizeof(storage)); if (err != 0) { res.emplace_err(err); } else { res.emplace(storage); } return res; } uint64_t MonotonicClock::now() { TRACE_CALL() return JS_Now() * 1000; } uint64_t MonotonicClock::resolution() { TRACE_CALL() return 1000; } int32_t MonotonicClock::subscribe(const uint64_t when, const bool absolute) { TRACE_CALL() return NEVER_HANDLE; } void MonotonicClock::unsubscribe(const int32_t handle_id){TRACE_CALL()} // HttpHeaders and HttpHeadersReadOnly extend Resource. // Resource provdes handle_state_ which is a HandleState // which gets to be fully host-defined. Resource::~Resource() { if (handle_state_ != nullptr) { handle_state_ = nullptr; } }; // Fastly handle state is currently just a wrapper around // an arbitrary fastly handle, along with a bit indicating // if it is a request or response. class HandleState { protected: api::FastlyAsyncTask::Handle handle_; bool is_req_; public: explicit HandleState(api::FastlyAsyncTask::Handle handle, bool is_request) { handle_ = handle; is_req_ = is_request; } api::FastlyAsyncTask::Handle handle() { return handle_; } bool is_req() { return is_req_; } bool valid() const { return true; } }; HttpHeaders *HttpHeadersReadOnly::clone() { return new HttpHeaders(*this); } const std::vector forbidden_request_headers = {}; const std::vector forbidden_response_headers = {}; const std::vector &HttpHeaders::get_forbidden_request_headers() { return forbidden_request_headers; } const std::vector &HttpHeaders::get_forbidden_response_headers() { return forbidden_response_headers; } Result>> HttpHeadersReadOnly::entries() const { TRACE_CALL() Result>> res; Result> names_res; if (this->handle_state_.get()->is_req()) { names_res = generic_get_header_names(this->handle_state_.get()->handle()); } else { names_res = generic_get_header_names( this->handle_state_.get()->handle()); } if (const auto err = names_res.to_err()) { return Result>>::err(*err); } vector> entries_vec; for (auto &name : names_res.unwrap()) { auto values_res = HttpHeadersReadOnly::get(name); if (auto err = values_res.to_err()) { return Result>>::err(*err); } auto &values = values_res.unwrap(); if (!values.has_value()) { // original js-compute-runtime also skipped here, but should this be an error or empty entry? continue; } auto last_val = &(*values.value().end()); for (auto &value : values.value()) { if (&value == last_val) { entries_vec.emplace_back(std::move(name), std::move(value)); } else { std::string_view host_name_view(name); entries_vec.emplace_back(host_api::HostString(host_name_view), std::move(value)); } } } res.emplace(std::move(entries_vec)); return res; } Result>> HttpHeadersReadOnly::get(string_view name) const { TRACE_CALL() Result>> res; if (this->handle_state_.get()->is_req()) { return generic_get_header_values( this->handle_state_.get()->handle(), name); } else { return generic_get_header_values( this->handle_state_.get()->handle(), name); } } Result HttpHeadersReadOnly::has(string_view name) const { TRACE_CALL() auto get_res = get(name); if (const auto err = get_res.to_err()) { return Result::err(*err); } return Result::ok(get_res.unwrap().has_value()); } HttpHeaders::HttpHeaders(std::unique_ptr state) : HttpHeadersReadOnly(std::move(state)) {} HttpHeaders::HttpHeaders() { handle_state_ = nullptr; } // TODO(guybedford): ensure this actually clones, or ban it entirely? HttpHeaders::HttpHeaders(const HttpHeadersReadOnly &headers) : HttpHeadersReadOnly(nullptr) { auto handle_state = new HandleState(headers.handle_state_.get()->handle(), headers.handle_state_.get()->is_req()); this->handle_state_ = std::unique_ptr(handle_state); } // This is only used by the HttpHeaders subclass, and immediately assigns the state after. HttpHeadersReadOnly::HttpHeadersReadOnly() { handle_state_ = nullptr; } HttpHeadersReadOnly::HttpHeadersReadOnly(std::unique_ptr state) { handle_state_ = std::move(state); } // This call corresponds to a state transition in switch_mode from Mode::ContentOnly to // Mode::CachedInContent in StarlingMonkey, which occurs when cloning a headers object, which we do // not call. // // That is, we have: // - Desynchronize from host: Mode::CachedInContent -> Mode::ContentOnly (create local mutations) // - Resynchronize to host : Mode::ContentOnly -> Mode::CachedInContent (commit local mutations) // // With these state transitions permitted arbitrarily. // // Fastly's headers implementation ties headers to request and response handles, as opposed to // being able to exist as free handles for headers. We therefore avoid the headers cloning operation // Mode::ContentOnly -> Mode::CachedInContent transition and as a result this FromEntries function // is never called. // // Instead we use a separate RequestOrResponse::commit_headers() implementation for fetch requests // and fetch-event responses, leaving the former Mode::ContentOnly as the cached value to achieve // the exact same result. Result HttpHeaders::FromEntries(vector> &entries) { TRACE_CALL() MOZ_RELEASE_ASSERT(false); } // Instead, we use write_headers to write into an existing headers object. Result write_headers(HttpHeaders *headers, std::vector> &list) { TRACE_CALL() std::vector seen; seen.reserve(list.size()); host_api::Result res; for (const auto &[name, value] : list) { if (std::find(seen.begin(), seen.end(), name) == seen.end()) { // first time seeing a header -> use set in case of existing values on the handle res = headers->set(name, value); seen.push_back(name); } else { // seen before -> use append res = headers->append(name, value); } if (res.is_err()) { return res; } } return Result::ok(); } Result HttpHeaders::remove(string_view name) { TRACE_CALL_ARGS(&name) if (this->handle_state_.get()->is_req()) { return generic_header_remove(this->handle_state_.get()->handle(), name); } else { return generic_header_remove(this->handle_state_.get()->handle(), name); } } Result HttpHeaders::set(string_view name, string_view value) { TRACE_CALL_ARGS(&name, &value) std::span value_span = {reinterpret_cast(const_cast(value.data())), value.size()}; if (this->handle_state_.get()->is_req()) { return generic_header_op(this->handle_state_.get()->handle(), name, value_span); } else { return generic_header_op(this->handle_state_.get()->handle(), name, value_span); } } Result HttpHeaders::append(string_view name, string_view value) { TRACE_CALL_ARGS(&name, &value) std::span value_span = {reinterpret_cast(const_cast(value.data())), value.size()}; if (this->handle_state_.get()->is_req()) { return generic_header_op(this->handle_state_.get()->handle(), name, value_span); } else { return generic_header_op(this->handle_state_.get()->handle(), name, value_span); } } // --- --- // The host interface makes the assumption regularly that uint32_t is sufficient space to store a // pointer. static_assert(sizeof(uint32_t) == sizeof(void *)); namespace { FastlySendError make_fastly_send_error(fastly::fastly_host_http_send_error_detail &send_error_detail) { FastlySendError res; switch (send_error_detail.tag) { case 0: { res.tag = FastlySendError::detail::uninitialized; break; } case 1: { res.tag = FastlySendError::detail::ok; break; } case 2: { res.tag = FastlySendError::detail::dns_timeout; break; } case 3: { res.tag = FastlySendError::detail::dns_error; break; } case 4: { res.tag = FastlySendError::detail::destination_not_found; break; } case 5: { res.tag = FastlySendError::detail::destination_unavailable; break; } case 6: { res.tag = FastlySendError::detail::destination_ip_unroutable; break; } case 7: { res.tag = FastlySendError::detail::connection_refused; break; } case 8: { res.tag = FastlySendError::detail::connection_terminated; break; } case 9: { res.tag = FastlySendError::detail::connection_timeout; break; } case 10: { res.tag = FastlySendError::detail::connection_limit_reached; break; } case 11: { res.tag = FastlySendError::detail::tls_certificate_error; break; } case 12: { res.tag = FastlySendError::detail::tls_configuration_error; break; } case 13: { res.tag = FastlySendError::detail::http_incomplete_response; break; } case 14: { res.tag = FastlySendError::detail::http_response_header_section_too_large; break; } case 15: { res.tag = FastlySendError::detail::http_response_body_too_large; break; } case 16: { res.tag = FastlySendError::detail::http_response_timeout; break; } case 17: { res.tag = FastlySendError::detail::http_response_status_invalid; break; } case 18: { res.tag = FastlySendError::detail::http_upgrade_failed; break; } case 19: { res.tag = FastlySendError::detail::http_protocol_error; break; } case 20: { res.tag = FastlySendError::detail::http_request_cache_key_invalid; break; } case 21: { res.tag = FastlySendError::detail::http_request_uri_invalid; break; } case 22: { res.tag = FastlySendError::detail::internal_error; break; } case 23: { res.tag = FastlySendError::detail::tls_alert_received; break; } case 24: { res.tag = FastlySendError::detail::tls_protocol_error; break; } default: { // If we are here, this is either because the host does not provided send error details // Or a new error detail tag exists and we don't yet have it implemented res.tag = FastlySendError::detail::uninitialized; } } res.dns_error_rcode = send_error_detail.dns_error_rcode; res.dns_error_info_code = send_error_detail.dns_error_info_code; res.tls_alert_id = send_error_detail.tls_alert_id; return res; } FastlyKVError make_fastly_kv_error(fastly::fastly_kv_error kv_error, fastly::fastly_host_error host_err) { FastlyKVError err; // first-priority host_err mapping switch (host_err) { case FASTLY_HOST_ERROR_BAD_HANDLE: { err.detail = FastlyKVError::detail::invalid_store_handle; return err; } case FASTLY_HOST_ERROR_INVALID_ARGUMENT: { err.detail = FastlyKVError::detail::bad_request; return err; } case FASTLY_HOST_ERROR_LIMIT_EXCEEDED: { err.detail = FastlyKVError::detail::too_many_requests; return err; } } switch (kv_error) { case KV_ERROR_BAD_REQUEST: { err.detail = FastlyKVError::detail::bad_request; return err; } case KV_ERROR_NOT_FOUND: { err.detail = FastlyKVError::detail::not_found; return err; } case KV_ERROR_PAYLOAD_TOO_LARGE: { err.detail = FastlyKVError::detail::payload_too_large; return err; } case KV_ERROR_PRECONDITION_FAILED: { err.detail = FastlyKVError::detail::precondition_failed; return err; } case KV_ERROR_TOO_MANY_REQUESTS: { err.detail = FastlyKVError::detail::too_many_requests; return err; } case KV_ERROR_INTERNAL_ERROR: { err.detail = FastlyKVError::detail::internal_error; return err; } case KV_ERROR_OK: case KV_ERROR_UNINITIALIZED: default: { // If the hostcall never initialized `kv_error`, or if it claimed // that it was `OK` but we still failed, then make a host error // based on the `host_err` value. err.detail = FastlyKVError::detail::host_error; err.host_err = host_err; return err; } } } FastlyImageOptimizerError make_fastly_image_optimizer_error(fastly::fastly_image_optimizer_error_detail im_err) { FastlyImageOptimizerError::detail det; switch (im_err.tag) { case FASTLY_IMAGE_OPTIMIZER_ERROR_TAG_UNINITIALIZED: det = FastlyImageOptimizerError::uninitialized; break; case FASTLY_IMAGE_OPTIMIZER_ERROR_TAG_OK: det = FastlyImageOptimizerError::ok; break; case FASTLY_IMAGE_OPTIMIZER_ERROR_TAG_ERROR: det = FastlyImageOptimizerError::error; break; case FASTLY_IMAGE_OPTIMIZER_ERROR_TAG_WARNING: det = FastlyImageOptimizerError::warning; break; } return {det, std::string(im_err.message, im_err.message_len)}; } FastlyImageOptimizerError make_fastly_image_optimizer_error(fastly::fastly_host_error err) { return {err}; } } // namespace Result HttpBody::make() { TRACE_CALL_ARGS(TSV("body")) Result res; HttpBody::Handle handle; fastly::fastly_host_error err; if (!convert_result(fastly::body_new(&handle), &err)) { res.emplace_err(err); } else { TRACE_CALL_RET(TSV(std::to_string(handle))) res.emplace(handle); } return res; } Result HttpBody::read(uint32_t chunk_size) const { TRACE_CALL_ARGS(TSV(std::to_string(handle))) Result res; fastly::fastly_world_list_u8 ret; ret.ptr = static_cast(cabi_malloc(chunk_size, 1)); fastly::fastly_host_error err; if (!convert_result( fastly::body_read(this->handle, ret.ptr, static_cast(chunk_size), &ret.len), &err)) { cabi_free(ret.ptr); res.emplace_err(err); } else { TRACE_CALL_RET(TSV(std::to_string(ret.len))) res.emplace(JS::UniqueChars(reinterpret_cast(ret.ptr)), ret.len); } return res; } Result HttpBody::read_into(uint8_t *ptr, size_t chunk_size) const { TRACE_CALL() Result res; size_t len; fastly::fastly_host_error err; if (!convert_result(fastly::body_read(this->handle, ptr, chunk_size, &len), &err)) { res.emplace_err(err); } else { res.emplace(len); } return res; } constexpr size_t HANDLE_READ_CHUNK_SIZE = 8192; Result HttpBody::read_all() const { Result res; size_t buf_cap = HANDLE_READ_CHUNK_SIZE; size_t buf_len = 0; uint8_t *buf = static_cast(malloc(buf_cap)); if (!buf) { res.emplace_err(FASTLY_HOST_ERROR_GENERIC_ERROR); return res; } do { if (buf_len + HANDLE_READ_CHUNK_SIZE > buf_cap) { buf_cap *= 2; uint8_t *new_buf = static_cast(realloc(buf, buf_cap)); if (!new_buf) { free(buf); res.emplace_err(FASTLY_HOST_ERROR_GENERIC_ERROR); return res; } buf = new_buf; } host_api::Result chunk = this->read_into((buf + buf_len), HANDLE_READ_CHUNK_SIZE); if (auto *err = chunk.to_err()) { free(buf); res.emplace_err(*err); return res; } size_t len = chunk.unwrap(); if (len == 0) { if (buf_len == 0) { free(buf); buf = nullptr; } else { buf = static_cast(realloc(buf, buf_len)); } break; } buf_len += len; } while (true); res.emplace(make_host_bytes(buf, buf_len)); return res; } Result HttpBody::write_front(const uint8_t *ptr, size_t len) const { TRACE_CALL() Result res; // The write call doesn't mutate the buffer; the cast is just for the generated fastly api. fastly::fastly_world_list_u8 chunk{const_cast(ptr), len}; fastly::fastly_host_error err; uint32_t written; if (!convert_result(fastly::body_write(this->handle, chunk.ptr, chunk.len, fastly::BodyWriteEnd::BodyWriteEndFront, reinterpret_cast(&written)), &err)) { res.emplace_err(err); } else { res.emplace(written); } return res; } Result HttpBody::write_back(const uint8_t *ptr, size_t len) const { TRACE_CALL() Result res; // The write call doesn't mutate the buffer; the cast is just for the generated fastly api. fastly::fastly_world_list_u8 chunk{const_cast(ptr), len}; fastly::fastly_host_error err; uint32_t written; if (!convert_result(fastly::body_write(this->handle, chunk.ptr, chunk.len, fastly::BodyWriteEnd::BodyWriteEndBack, reinterpret_cast(&written)), &err)) { res.emplace_err(err); } else { res.emplace(written); } return res; } Result HttpBody::write_all_front(const uint8_t *ptr, size_t len) const { TRACE_CALL() while (len > 0) { auto write_res = this->write_front(ptr, len); if (auto *err = write_res.to_err()) { return Result::err(*err); } auto written = write_res.unwrap(); ptr += written; MOZ_ASSERT(written <= len); len -= static_cast(written); } return Result::ok(); } Result HttpBody::write_all_back(const uint8_t *ptr, size_t len) const { TRACE_CALL() while (len > 0) { auto write_res = this->write_back(ptr, len); if (auto *err = write_res.to_err()) { return Result::err(*err); } auto written = write_res.unwrap(); ptr += written; len -= std::min(len, static_cast(written)); } return Result::ok(); } Result HttpBody::append(HttpBody other) const { TRACE_CALL() Result res; fastly::fastly_host_error err; if (!convert_result(fastly::body_append(this->handle, other.handle), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpBody::close() { TRACE_CALL() Result res; fastly::fastly_host_error err; if (!convert_result(fastly::body_close(this->handle), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpBody::abandon() { TRACE_CALL() Result res; fastly::fastly_host_error err; if (!convert_result(fastly::body_abandon(this->handle), &err)) { res.emplace_err(err); } else { handle = INVALID_HANDLE; res.emplace(); } return res; } Result> HttpBody::known_length() const { TRACE_CALL() Result> res; fastly::fastly_host_error err; uint64_t length; if (!convert_result(fastly::body_known_length(this->handle, &length), &err)) { if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(length); } return res; } FastlyAsyncTask::Handle HttpBody::async_handle() const { return FastlyAsyncTask::Handle{this->handle}; } Result HttpBody::is_ready() const { Result res; uint32_t is_ready; fastly::fastly_host_error err; if (!convert_result(fastly::async_is_ready(this->handle, &is_ready), &err)) { res.emplace_err(err); } else { res.emplace(is_ready); } return res; } FastlyResult HttpPendingReq::wait() { TRACE_CALL_ARGS(TSV(std::to_string(this->handle))) FastlyResult res; fastly::fastly_host_http_send_error_detail s; std::memset(&s, 0, sizeof(s)); s.mask |= FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_MASK_DNS_ERROR_RCODE; s.mask |= FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_MASK_DNS_ERROR_INFO_CODE; s.mask |= FASTLY_HOST_HTTP_SEND_ERROR_DETAIL_MASK_TLS_ALERT_ID; fastly::fastly_host_error err; fastly::fastly_host_http_response ret; if (!convert_result(fastly::req_pending_req_wait_v2(this->handle, &s, &ret.f0, &ret.f1), &err)) { res.emplace_err(make_fastly_send_error(s)); } else { res.emplace(make_response(ret)); TRACE_CALL_RET(TSV(std::to_string(ret.f0)), TSV(std::to_string(ret.f1))) } return res; } FastlyAsyncTask::Handle HttpPendingReq::async_handle() const { return FastlyAsyncTask::Handle{this->handle}; } void CacheOverrideTag::set_pass() { this->value |= CACHE_OVERRIDE_PASS; } void CacheOverrideTag::set_ttl() { this->value |= CACHE_OVERRIDE_TTL; } void CacheOverrideTag::set_stale_while_revalidate() { this->value |= CACHE_OVERRIDE_STALE_WHILE_REVALIDATE; } void CacheOverrideTag::set_pci() { this->value |= CACHE_OVERRIDE_PCI; } TlsVersion::TlsVersion(uint8_t raw) : value{raw} { switch (raw) { case fastly::TLS::VERSION_1: case fastly::TLS::VERSION_1_1: case fastly::TLS::VERSION_1_2: case fastly::TLS::VERSION_1_3: break; default: MOZ_ASSERT(false, "Making a TlsValue from an invalid raw value"); } } uint8_t TlsVersion::get_version() const { return this->value; } double TlsVersion::get_version_number() const { switch (this->value) { case fastly::TLS::VERSION_1: return 1.0; case fastly::TLS::VERSION_1_1: return 1.1; case fastly::TLS::VERSION_1_2: return 1.2; case fastly::TLS::VERSION_1_3: return 1.3; } return 0; } TlsVersion TlsVersion::version_1() { return TlsVersion{fastly::TLS::VERSION_1}; } TlsVersion TlsVersion::version_1_1() { return TlsVersion{fastly::TLS::VERSION_1_1}; } TlsVersion TlsVersion::version_1_2() { return TlsVersion{fastly::TLS::VERSION_1_2}; } TlsVersion TlsVersion::version_1_3() { return TlsVersion{fastly::TLS::VERSION_1_3}; } Result HttpReq::make() { TRACE_CALL_ARGS(TSV("http_req")) Result res; HttpReq::Handle handle; fastly::fastly_host_error err; if (!convert_result(fastly::req_new(&handle), &err)) { res.emplace_err(err); } else { TRACE_CALL_RET(TSV(std::to_string(handle))) res.emplace(handle); } return res; } Result HttpReq::redirect_to_grip_proxy(std::string_view backend) { TRACE_CALL() Result res; fastly::fastly_host_error err; fastly::fastly_world_string backend_str = string_view_to_world_string(backend); if (!convert_result(fastly::req_redirect_to_grip_proxy_v2( this->handle, reinterpret_cast(backend_str.ptr), backend_str.len), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpReq::redirect_to_websocket_proxy(std::string_view backend) { TRACE_CALL() Result res; fastly::fastly_host_error err; fastly::fastly_world_string backend_str = string_view_to_world_string(backend); if (!convert_result(fastly::req_redirect_to_websocket_proxy_v2( this->handle, reinterpret_cast(backend_str.ptr), backend_str.len), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpReq::auto_decompress_gzip() { TRACE_CALL() Result res; fastly::fastly_host_error err; int encodings_to_decompress = 0 | FASTLY_HOST_CONTENT_ENCODINGS_GZIP; if (!convert_result( fastly::req_auto_decompress_response_set(this->handle, encodings_to_decompress), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpReq::register_dynamic_backend(std::string_view name, std::string_view target, const BackendConfig &config) { TRACE_CALL() Result res; fastly::DynamicBackendConfig backend_configuration; memset(&backend_configuration, 0, sizeof(backend_configuration)); uint32_t backend_config_mask = 0; auto target_str = string_view_to_world_string(target); if (auto &val = config.host_override) { backend_config_mask |= BACKEND_CONFIG_HOST_OVERRIDE; auto host_override = string_view_to_world_string(*val); backend_configuration.host_override = reinterpret_cast(host_override.ptr); backend_configuration.host_override_len = host_override.len; } if (config.connect_timeout.has_value()) { backend_config_mask |= BACKEND_CONFIG_CONNECT_TIMEOUT; backend_configuration.connect_timeout_ms = *config.connect_timeout; } if (config.first_byte_timeout.has_value()) { backend_config_mask |= BACKEND_CONFIG_FIRST_BYTE_TIMEOUT; backend_configuration.first_byte_timeout_ms = *config.first_byte_timeout; } if (config.between_bytes_timeout.has_value()) { backend_config_mask |= BACKEND_CONFIG_BETWEEN_BYTES_TIMEOUT; backend_configuration.between_bytes_timeout_ms = *config.between_bytes_timeout; } if (config.use_ssl.value_or(false)) { backend_config_mask |= BACKEND_CONFIG_USE_SSL; } if (config.dont_pool.value_or(false)) { backend_config_mask |= BACKEND_CONFIG_DONT_POOL; } if (config.ssl_min_version.has_value()) { backend_config_mask |= BACKEND_CONFIG_SSL_MIN_VERSION; backend_configuration.ssl_min_version = config.ssl_min_version->get_version(); } if (config.ssl_max_version.has_value()) { backend_config_mask |= BACKEND_CONFIG_SSL_MAX_VERSION; backend_configuration.ssl_max_version = config.ssl_max_version->get_version(); } if (auto &val = config.cert_hostname) { backend_config_mask |= BACKEND_CONFIG_CERT_HOSTNAME; auto cert_hostname = string_view_to_world_string(*val); backend_configuration.cert_hostname = reinterpret_cast(cert_hostname.ptr); backend_configuration.cert_hostname_len = cert_hostname.len; } if (auto &val = config.ca_cert) { backend_config_mask |= BACKEND_CONFIG_CA_CERT; auto ca_cert = string_view_to_world_string(*val); backend_configuration.ca_cert = reinterpret_cast(ca_cert.ptr); backend_configuration.ca_cert_len = ca_cert.len; } if (auto &val = config.ciphers) { backend_config_mask |= BACKEND_CONFIG_CIPHERS; auto ciphers = string_view_to_world_string(*val); backend_configuration.ciphers = reinterpret_cast(ciphers.ptr); backend_configuration.ciphers_len = ciphers.len; } if (auto &val = config.sni_hostname) { backend_config_mask |= BACKEND_CONFIG_SNI_HOSTNAME; auto sni_hostname = string_view_to_world_string(*val); backend_configuration.sni_hostname = reinterpret_cast(sni_hostname.ptr); backend_configuration.sni_hostname_len = sni_hostname.len; } else if (config.use_ssl.value_or(false)) { backend_configuration.sni_hostname = reinterpret_cast(target_str.ptr); backend_configuration.sni_hostname_len = target_str.len; } if (auto &val = config.client_cert) { backend_config_mask |= BACKEND_CONFIG_CLIENT_CERT; auto client_cert = string_view_to_world_string(val->cert); backend_configuration.client_certificate = reinterpret_cast(client_cert.ptr); backend_configuration.client_certificate_len = client_cert.len; backend_configuration.client_key = config.client_cert->key; } if (config.grpc.value_or(false)) { backend_config_mask |= BACKEND_CONFIG_GRPC; } if (config.http_keepalive_time_ms.has_value()) { backend_config_mask |= BACKEND_CONFIG_KEEPALIVE; backend_configuration.tcp_keepalive_enable = 1; backend_configuration.http_keepalive_time_ms = config.http_keepalive_time_ms.value(); } if (config.tcp_keepalive.has_value()) { backend_config_mask |= BACKEND_CONFIG_KEEPALIVE; backend_configuration.tcp_keepalive_enable = 1; auto tcp_keepalive = config.tcp_keepalive.value(); if (tcp_keepalive.interval_secs.has_value()) { backend_configuration.tcp_keepalive_interval_secs = tcp_keepalive.interval_secs.value(); } if (tcp_keepalive.probes.has_value()) { backend_configuration.tcp_keepalive_probes = tcp_keepalive.probes.value(); } if (tcp_keepalive.time_secs.has_value()) { backend_configuration.tcp_keepalive_time_secs = tcp_keepalive.time_secs.value(); } } auto name_str = string_view_to_world_string(name); fastly::fastly_host_error err; if (!convert_result(fastly::req_register_dynamic_backend( reinterpret_cast(name_str.ptr), name_str.len, reinterpret_cast(target_str.ptr), target_str.len, backend_config_mask, &backend_configuration), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpReq::send_async(HttpBody body, std::string_view backend) { TRACE_CALL() Result res; fastly::fastly_host_error err; HttpPendingReq::Handle ret; fastly::fastly_world_string backend_str = string_view_to_world_string(backend); if (!convert_result(fastly::req_send_async(this->handle, body.handle, reinterpret_cast(backend_str.ptr), backend_str.len, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result HttpReq::send_async_streaming(HttpBody body, std::string_view backend) { TRACE_CALL() Result res; fastly::fastly_host_error err; HttpPendingReq::Handle ret; fastly::fastly_world_string backend_str = string_view_to_world_string(backend); if (!convert_result(fastly::req_send_async_streaming(this->handle, body.handle, reinterpret_cast(backend_str.ptr), backend_str.len, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result HttpReq::send_async_without_caching(HttpBody body, std::string_view backend, bool streaming) { TRACE_CALL_ARGS(TSV(std::to_string(body.handle)), streaming ? TSV("streaming") : TSV("not streaming")) Result res; fastly::fastly_host_error err; HttpPendingReq::Handle ret; fastly::fastly_world_string backend_str = string_view_to_world_string(backend); if (!convert_result(fastly::req_send_async_v2(this->handle, body.handle, reinterpret_cast(backend_str.ptr), backend_str.len, streaming ? 1 : 0, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } FastlyResult HttpReq::send_image_optimizer(HttpBody body, std::string_view backend, std::string_view config_str) { TRACE_CALL() FastlyResult res; fastly::fastly_host_error err; HttpReq::Handle orig_req_body_handle = INVALID_HANDLE; fastly::fastly_world_string backend_str = string_view_to_world_string(backend); auto opts = FASTLY_IMAGE_OPTIMIZER_SDK_CLAIMS_OPTS; fastly::fastly_image_optimizer_transform_config config{config_str.data(), config_str.size()}; fastly::fastly_image_optimizer_error_detail io_err_out{}; uint32_t resp_handle_out = INVALID_HANDLE, body_handle_out = INVALID_HANDLE; auto host_call_success = convert_result( fastly::image_optimizer_transform_image_optimizer_request( this->handle, orig_req_body_handle, reinterpret_cast(backend_str.ptr), backend_str.len, opts, &config, &io_err_out, &resp_handle_out, &body_handle_out), &err); if (!host_call_success) { res.emplace_err(make_fastly_image_optimizer_error(err)); } else if (false && io_err_out.tag != FASTLY_IMAGE_OPTIMIZER_ERROR_TAG_OK) { res.emplace_err(make_fastly_image_optimizer_error(io_err_out)); } else { res.emplace(HttpResp(resp_handle_out), HttpBody(body_handle_out)); } return res; } Result HttpReq::set_method(std::string_view method) { TRACE_CALL() Result res; fastly::fastly_host_error err; fastly::fastly_world_string str = string_view_to_world_string(method); if (!convert_result( fastly::req_method_set(this->handle, reinterpret_cast(str.ptr), str.len), &err)) { res.emplace_err(err); } return res; } Result HttpReq::get_method() const { TRACE_CALL_ARGS(TSV(std::to_string(handle))) Result res; fastly::fastly_host_error err; fastly::fastly_world_string method; method.ptr = static_cast(cabi_malloc(METHOD_MAX_LEN, 1)); if (!convert_result(fastly::req_method_get(this->handle, reinterpret_cast(method.ptr), METHOD_MAX_LEN, &method.len), &err)) { cabi_free(method.ptr); res.emplace_err(err); } else { method.ptr = static_cast(cabi_realloc(method.ptr, METHOD_MAX_LEN, 1, method.len)); res.emplace(make_host_string(method)); } return res; } Result HttpReq::set_uri(std::string_view str) { TRACE_CALL_ARGS(TSV(std::to_string(this->handle)), TSV(str)) Result res; fastly::fastly_host_error err; fastly::fastly_world_string uri = string_view_to_world_string(str); if (!convert_result(fastly::req_uri_set(this->handle, reinterpret_cast(uri.ptr), uri.len), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpReq::get_uri() const { TRACE_CALL_ARGS(TSV(std::to_string(handle))) Result res; fastly::fastly_host_error err; fastly::fastly_world_string uri; uri.ptr = static_cast(cabi_malloc(URI_MAX_LEN, 1)); if (!convert_result(fastly::req_uri_get(this->handle, reinterpret_cast(uri.ptr), URI_MAX_LEN, &uri.len), &err)) { cabi_free(uri.ptr); res.emplace_err(err); } else { uri.ptr = static_cast(cabi_realloc(uri.ptr, URI_MAX_LEN, 1, uri.len)); res.emplace(make_host_string(uri)); } return res; } Result HttpReq::cache_override(CacheOverrideTag tag, std::optional opt_ttl, std::optional opt_swr, std::optional opt_sk) { TRACE_CALL() Result res; fastly::fastly_world_string sk; if (opt_sk.has_value()) { sk = string_view_to_world_string(opt_sk.value()); } else { sk.ptr = nullptr; sk.len = 0; } fastly::fastly_host_error err; if (!convert_result(fastly::req_cache_override_v2_set(this->handle, tag.value, opt_ttl.value_or(0), opt_swr.value_or(0), reinterpret_cast(sk.ptr), sk.len), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpReq::set_framing_headers_mode(FramingHeadersMode mode) { TRACE_CALL() Result res; fastly::fastly_host_error err; if (!convert_result( fastly::req_framing_headers_mode_set(this->handle, static_cast(mode)), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } // http-req-downstream-client-request-id: func() -> result, error> Result> HttpReq::http_req_downstream_client_request_id() { TRACE_CALL() Result> res; fastly::fastly_host_error err; fastly::fastly_world_string ret; auto default_size = 128; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::http_downstream_client_request_id(this->handle, ret.ptr, default_size, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::http_downstream_client_request_id(this->handle, ret.ptr, ret.len, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(make_host_string(ret)); } return res; } Result HttpReq::downstream_client_ip_addr() { TRACE_CALL() Result res; fastly::fastly_world_list_u8 octets; octets.ptr = static_cast(cabi_malloc(16, 1)); fastly::fastly_host_error err; if (!convert_result( fastly::http_downstream_client_ip_addr_get(this->handle, octets.ptr, &octets.len), &err)) { cabi_free(octets.ptr); res.emplace_err(err); } else { res.emplace(make_host_bytes(octets.ptr, octets.len)); } return res; } Result HttpReq::downstream_server_ip_addr() { TRACE_CALL() Result res; fastly::fastly_world_list_u8 octets; octets.ptr = static_cast(cabi_malloc(16, 1)); fastly::fastly_host_error err; if (!convert_result( fastly::http_downstream_server_ip_addr_get(this->handle, octets.ptr, &octets.len), &err)) { cabi_free(octets.ptr); res.emplace_err(err); } else { res.emplace(make_host_bytes(octets.ptr, octets.len)); } return res; } // http-req-downstream-tls-cipher-openssl-name: func() -> result Result> HttpReq::http_req_downstream_tls_cipher_openssl_name() { TRACE_CALL() Result> res; fastly::fastly_host_error err; fastly::fastly_world_string ret; auto default_size = 128; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::http_downstream_tls_cipher_openssl_name( this->handle, reinterpret_cast(ret.ptr), default_size, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { // NB(@zkat): ERROR_BUFFER_LEN sets the expected length of the buffer to // &ret.len, so we use that to inform our resize. ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::http_downstream_tls_cipher_openssl_name( this->handle, reinterpret_cast(ret.ptr), ret.len, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(make_host_string(ret)); } return res; } // http-req-downstream-tls-protocol: func() -> result Result> HttpReq::http_req_downstream_tls_protocol() { TRACE_CALL() Result> res; fastly::fastly_host_error err; fastly::fastly_world_string ret; auto default_size = 32; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::http_downstream_tls_protocol( this->handle, reinterpret_cast(ret.ptr), default_size, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { // NB(@zkat): ERROR_BUFFER_LEN sets the expected length of the buffer to // &ret.len, so we use that to inform our resize. ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::http_downstream_tls_protocol(this->handle, reinterpret_cast(ret.ptr), ret.len, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(make_host_string(ret)); } return res; } // http-req-downstream-tls-client-hello: func() -> result, error> Result> HttpReq::http_req_downstream_tls_client_hello() { TRACE_CALL() Result> res; fastly::fastly_world_list_u8 ret; fastly::fastly_host_error err; auto default_size = 512; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::http_downstream_tls_client_hello(this->handle, ret.ptr, default_size, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { // NB(@zkat): ERROR_BUFFER_LEN sets the expected length of the buffer to // &ret.len, so we use that to inform our resize. ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::http_downstream_tls_client_hello(this->handle, ret.ptr, ret.len, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(make_host_bytes(ret.ptr, ret.len)); } return res; } // http-req-downstream-tls-raw-client-certificate: func() -> result, error> Result> HttpReq::http_req_downstream_tls_raw_client_certificate() { TRACE_CALL() Result> res; fastly::fastly_world_list_u8 ret; fastly::fastly_host_error err; auto default_size = 4096; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::http_downstream_tls_raw_client_certificate(this->handle, ret.ptr, default_size, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { // NB(@zkat): ERROR_BUFFER_LEN sets the expected length of the buffer to // &ret.len, so we use that to inform our resize. ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::http_downstream_tls_raw_client_certificate(this->handle, ret.ptr, ret.len, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(make_host_bytes(ret.ptr, ret.len)); } return res; } // http-req-downstream-tls-ja3-md5: func() -> result, error> Result> HttpReq::http_req_downstream_tls_ja3_md5() { TRACE_CALL() Result> res; fastly::fastly_world_list_u8 ret; fastly::fastly_host_error err; auto default_size = 16; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::http_downstream_tls_ja3_md5(this->handle, ret.ptr, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { // NB(@zkat): ERROR_BUFFER_LEN sets the expected length of the buffer to // &ret.len, so we use that to inform our resize. ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::http_downstream_tls_ja3_md5(this->handle, ret.ptr, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(make_host_bytes(ret.ptr, ret.len)); } return res; } // http-req-downstream-tls-ja4: func() -> result, error> Result> HttpReq::http_req_downstream_tls_ja4() { TRACE_CALL() Result> res; fastly::fastly_host_error err; fastly::fastly_world_string ret; auto default_size = 128; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::http_downstream_tls_ja4(this->handle, ret.ptr, default_size, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::http_downstream_tls_ja4(this->handle, ret.ptr, ret.len, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(make_host_string(ret)); } return res; } // http-req-downstream-client-h2-fingerprint: func() -> result, error> Result> HttpReq::http_req_downstream_client_h2_fingerprint() { TRACE_CALL() Result> res; fastly::fastly_host_error err; fastly::fastly_world_string ret; auto default_size = 128; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::http_downstream_client_h2_fingerprint(this->handle, ret.ptr, default_size, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::http_downstream_client_h2_fingerprint(this->handle, ret.ptr, ret.len, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(make_host_string(ret)); } return res; } // http-req-downstream-client-oh-fingerprint: func() -> result, error> Result> HttpReq::http_req_downstream_client_oh_fingerprint() { TRACE_CALL() Result> res; fastly::fastly_host_error err; fastly::fastly_world_string ret; auto default_size = 128; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::http_downstream_client_oh_fingerprint(this->handle, ret.ptr, default_size, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::http_downstream_client_oh_fingerprint(this->handle, ret.ptr, ret.len, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(make_host_string(ret)); } return res; } bool HttpReq::is_valid() const { return this->handle != HttpReq::invalid; } Result HttpReq::get_version() const { TRACE_CALL() Result res; fastly::fastly_host_error err; uint32_t fastly_http_version; if (!convert_result(fastly::req_version_get(this->handle, &fastly_http_version), &err)) { res.emplace_err(err); } else { MOZ_ASSERT(fastly_http_version <= static_cast(std::numeric_limits::max())); res.emplace(fastly_http_version); } return res; } HttpHeadersReadOnly *HttpReq::headers() { return new HttpHeadersReadOnly(std::unique_ptr(new HandleState(this->handle, true))); } HttpHeaders *HttpReq::headers_writable() { return headers()->clone(); } Result HttpReqPromise::downstream_next(HttpReqPromise::DownstreamNextOptions options) { TRACE_CALL() Result res; fastly::fastly_http_downstream_next_request_options opts{}; uint32_t opts_mask = 0; if (options.timeout_ms) { opts_mask |= FASTLY_HTTP_DOWNSTREAM_NEXT_REQUEST_OPTIONS_MASK_TIMEOUT; opts.timeout_ms = options.timeout_ms.value(); } fastly::fastly_host_error err; HttpReqPromise::Handle handle; if (!convert_result(fastly::downstream_next_request(opts_mask, &opts, &handle), &err)) { res.emplace_err(err); } else { res.emplace(handle); } return res; } Result HttpReqPromise::wait() { TRACE_CALL_ARGS(TSV(std::to_string(this->handle))) Result res; fastly::fastly_host_error err; HttpReq::Handle req_handle = HttpReq::invalid; HttpBody::Handle body_handle = HttpBody::invalid; if (!convert_result(fastly::downstream_next_request_wait(this->handle, &req_handle, &body_handle), &err)) { res.emplace_err(err); } else { res.emplace(HttpReq(req_handle), HttpBody(body_handle)); } return res; } Result HttpReqPromise::abandon() { TRACE_CALL_ARGS(TSV(std::to_string(this->handle))) Result res; fastly::fastly_host_error err; if (!convert_result(fastly::downstream_next_request_abandon(this->handle), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpResp::make() { TRACE_CALL_ARGS(TSV("http_resp")) Result res; HttpResp::Handle handle; fastly::fastly_host_error err; if (!convert_result(fastly::resp_new(&handle), &err)) { res.emplace_err(err); } else { TRACE_CALL_RET(TSV(std::to_string(handle))) res.emplace(handle); } return res; } Result HttpResp::get_status() const { TRACE_CALL_ARGS(TSV(std::to_string(this->handle))) Result res; uint16_t ret; fastly::fastly_host_error err; if (!convert_result(fastly::resp_status_get(this->handle, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result HttpResp::set_status(uint16_t status) { TRACE_CALL_ARGS(TSV(std::to_string(status))) Result res; fastly::fastly_host_error err; if (!convert_result(fastly::resp_status_set(this->handle, status), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpResp::send_downstream(HttpBody body, bool streaming) { TRACE_CALL_ARGS(TSV(std::to_string(body.handle)), streaming ? TSV("streaming") : TSV("not streaming")) Result res; fastly::fastly_host_error err; if (!convert_result(fastly::resp_send_downstream(this->handle, body.handle, streaming), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result HttpResp::set_framing_headers_mode(FramingHeadersMode mode) { TRACE_CALL() Result res; fastly::fastly_host_error err; if (!convert_result( fastly::resp_framing_headers_mode_set(this->handle, static_cast(mode)), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } bool HttpResp::is_valid() const { return this->handle != HttpResp::invalid; } Result HttpResp::get_version() const { TRACE_CALL() Result res; fastly::fastly_host_error err; uint32_t fastly_http_version; if (!convert_result(fastly::resp_version_get(this->handle, &fastly_http_version), &err)) { res.emplace_err(err); } else { MOZ_ASSERT(fastly_http_version <= static_cast(std::numeric_limits::max())); res.emplace(fastly_http_version); } return res; } HttpHeadersReadOnly *HttpResp::headers() { return new HttpHeadersReadOnly( std::unique_ptr(new HandleState(this->handle, false))); } HttpHeaders *HttpResp::headers_writable() { return headers()->clone(); } Result> HttpResp::get_ip() const { TRACE_CALL() Result> res; fastly::fastly_host_error err; fastly::fastly_world_list_u8 ret; ret.ptr = static_cast(cabi_malloc(16, 1)); if (!convert_result(fastly::resp_ip_get(this->handle, ret.ptr, &ret.len), &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(make_host_bytes(ret.ptr, ret.len)); } return res; } Result> HttpResp::get_port() const { TRACE_CALL() Result> res; fastly::fastly_host_error err; uint16_t ret; if (!convert_result(fastly::resp_port_get(this->handle, &ret), &err)) { if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(ret); } return res; } Result> GeoIp::lookup(std::span bytes) { TRACE_CALL() Result> res; fastly::fastly_world_list_u8 octets_list{const_cast(bytes.data()), bytes.size()}; fastly::fastly_world_string ret; fastly::fastly_host_error err; ret.ptr = static_cast(cabi_malloc(HOSTCALL_BUFFER_LEN, 1)); if (!convert_result(fastly::geo_lookup(octets_list.ptr, octets_list.len, reinterpret_cast(ret.ptr), HOSTCALL_BUFFER_LEN, &ret.len), &err)) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else if (ret.len == 0) { // Viceroy returns a zero len instead of none for unknown cases for some reason cabi_free(ret.ptr); res.emplace(std::nullopt); } else { ret.ptr = static_cast(cabi_realloc(ret.ptr, HOSTCALL_BUFFER_LEN, 1, ret.len)); res.emplace(make_host_string(ret)); } return res; } namespace { struct FastlyCacheWriteOptionsOwned { std::unique_ptr options; uint32_t mask; // surrogate keys backing store when ' ' joined std::unique_ptr surrogate_keys_owned; }; FastlyCacheWriteOptionsOwned to_fastly_cache_write_options(const HttpCacheWriteOptions *opts) { FastlyCacheWriteOptionsOwned result{}; result.options = std::make_unique(); // Required field, no mask result.options->max_age_ns = opts->max_age_ns.value(); if (opts->vary_rule && *opts->vary_rule) { // Convert HostString to char* and length result.options->vary_rule = opts->vary_rule->ptr.get(); result.options->vary_rule_len = opts->vary_rule->len; result.mask |= FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_VARY_RULE; } if (opts->initial_age_ns) { result.options->initial_age_ns = *opts->initial_age_ns; result.mask |= FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_INITIAL_AGE_NS; } if (opts->stale_while_revalidate_ns) { result.options->stale_while_revalidate_ns = *opts->stale_while_revalidate_ns; result.mask |= FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_STALE_WHILE_REVALIDATE_NS; } if (opts->surrogate_keys.has_value()) { const auto &keys = opts->surrogate_keys.value(); if (keys.size() == 1) { result.options->surrogate_keys = keys[0].ptr.get(); result.options->surrogate_keys_len = keys[0].len; } else if (keys.size() > 1) { // Calculate total length needed including spaces size_t total_len = 0; for (const auto &key : keys) { total_len += key.len + 1; // +1 for space or null } // Allocate array using make_unique auto surrogate_keys = std::make_unique(total_len); size_t pos = 0; // Copy first key memcpy(surrogate_keys.get() + pos, keys[0].ptr.get(), keys[0].len); pos += keys[0].len; // Copy remaining keys with leading space for (size_t i = 1; i < keys.size(); i++) { surrogate_keys[pos++] = ' '; memcpy(surrogate_keys.get() + pos, keys[i].ptr.get(), keys[i].len); pos += keys[i].len; } result.surrogate_keys_owned = std::move(surrogate_keys); result.options->surrogate_keys = result.surrogate_keys_owned.get(); result.options->surrogate_keys_len = total_len - 1; } result.mask |= FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_SURROGATE_KEYS; } if (opts->length) { result.options->length = *opts->length; result.mask |= FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_LENGTH; } if (opts->sensitive_data) { result.mask |= FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_SENSITIVE_DATA; } return result; } HttpCacheWriteOptions * from_fastly_cache_write_options(const fastly::fastly_http_cache_write_options &fastly_opts, uint32_t mask) { HttpCacheWriteOptions *opts = new HttpCacheWriteOptions(); // Required field opts->max_age_ns = fastly_opts.max_age_ns; if (mask & FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_VARY_RULE && fastly_opts.vary_rule && fastly_opts.vary_rule_len > 0) { // Create a new HostString from the data opts->vary_rule.emplace(JS::UniqueChars(static_cast(malloc(fastly_opts.vary_rule_len))), fastly_opts.vary_rule_len); memcpy(opts->vary_rule->ptr.get(), fastly_opts.vary_rule, fastly_opts.vary_rule_len); } if (mask & FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_INITIAL_AGE_NS) { opts->initial_age_ns = fastly_opts.initial_age_ns; } if (mask & FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_STALE_WHILE_REVALIDATE_NS) { opts->stale_while_revalidate_ns = fastly_opts.stale_while_revalidate_ns; } if (mask & FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_SURROGATE_KEYS && fastly_opts.surrogate_keys && fastly_opts.surrogate_keys_len > 0) { opts->surrogate_keys.emplace(); // Split space-separated surrogate keys std::string_view keys_str(fastly_opts.surrogate_keys, fastly_opts.surrogate_keys_len); size_t pos = 0; while (pos < keys_str.size()) { size_t space = keys_str.find(' ', pos); if (space == std::string_view::npos) { size_t key_len = keys_str.size() - pos; JS::UniqueChars key_ptr(static_cast(malloc(key_len))); memcpy(key_ptr.get(), keys_str.data() + pos, key_len); opts->surrogate_keys->push_back(HostString(std::move(key_ptr), key_len)); break; } size_t key_len = space - pos; JS::UniqueChars key_ptr(static_cast(malloc(key_len))); memcpy(key_ptr.get(), keys_str.data() + pos, key_len); opts->surrogate_keys->push_back(HostString(std::move(key_ptr), key_len)); pos = space + 1; } } if (mask & FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_LENGTH) { opts->length = fastly_opts.length; } if (mask & FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_SENSITIVE_DATA) { opts->sensitive_data = true; } return opts; } } // namespace // HttpReq cache-related method implementations Result HttpReq::is_cacheable() const { TRACE_CALL_ARGS(TSV(std::to_string(this->handle))) uint32_t is_cacheable_out; auto res = fastly::http_cache_is_request_cacheable(this->handle, &is_cacheable_out); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(is_cacheable_out != 0); } Result HttpReq::get_suggested_cache_key() const { TRACE_CALL() size_t nwritten; uint8_t *buffer = static_cast(cabi_malloc(32, 4)); // HTTP cache keys must be 32 bytes if (!buffer) { return Result::err(host_api::APIError(FASTLY_HOST_ERROR_GENERIC_ERROR)); } auto res = fastly::http_cache_get_suggested_cache_key( this->handle, reinterpret_cast(buffer), 32, &nwritten); if (res != 0) { cabi_free(buffer); return Result::err(host_api::APIError(res)); } fastly::fastly_world_string str = {.ptr = buffer, .len = nwritten}; return Result::ok(make_host_string(str)); } Result Request::downstream_get() { TRACE_CALL() Result res; fastly::fastly_host_error err; HttpReq::Handle req_handle = HttpReq::invalid; HttpBody::Handle body_handle = HttpBody::invalid; if (!convert_result(fastly::req_body_downstream_get(&req_handle, &body_handle), &err)) { res.emplace_err(err); } else { res.emplace(HttpReq(req_handle), HttpBody(body_handle)); } return res; } Result Request::inspect(const InspectOptions *config) { TRACE_CALL() Result res; uint32_t inspect_opts_mask{0}; fastly::fastly_host_http_inspect_options opts; if (config->corp != nullptr) { inspect_opts_mask |= FASTLY_HOST_HTTP_REQ_INSPECT_CONFIG_OPTIONS_MASK_CORP; opts.corp = config->corp; opts.corp_len = config->corp_len; } if (config->workspace != nullptr) { inspect_opts_mask |= FASTLY_HOST_HTTP_REQ_INSPECT_CONFIG_OPTIONS_MASK_WORKSPACE; opts.workspace = config->workspace; opts.workspace_len = config->workspace_len; } if (config->override_client_ip_ptr != nullptr) { inspect_opts_mask |= FASTLY_HOST_HTTP_REQ_INSPECT_CONFIG_OPTIONS_MASK_OVERRIDE_CLIENT_IP; opts.override_client_ip_ptr = config->override_client_ip_ptr; opts.override_client_ip_len = config->override_client_ip_len; } fastly::fastly_host_error err; fastly::fastly_world_string ret; ret.ptr = static_cast(cabi_malloc(HOSTCALL_BUFFER_LEN, 4)); if (!convert_result(fastly::req_inspect(this->req.handle, this->body.handle, inspect_opts_mask, &opts, ret.ptr, HOSTCALL_BUFFER_LEN, &ret.len), &err)) { res.emplace_err(err); } else { res.emplace(make_host_string(ret)); } return res; } Result HttpCacheEntry::transaction_lookup(const HttpReq &req, std::span override_key) { TRACE_CALL_ARGS(TSV(std::to_string(req.handle))) uint32_t handle_out; fastly::fastly_http_cache_lookup_options opts{}; uint32_t opts_mask = 0; if (!override_key.empty()) { MOZ_ASSERT(override_key.size() == 32); opts.override_key = reinterpret_cast(override_key.data()); opts.override_key_len = override_key.size(); opts_mask |= FASTLY_HTTP_CACHE_LOOKUP_OPTIONS_MASK_OVERRIDE_KEY; } auto res = fastly::http_cache_transaction_lookup( req.handle, opts_mask, override_key.empty() ? nullptr : &opts, &handle_out); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(HttpCacheEntry(handle_out)); } Result HttpCacheEntry::transaction_insert(const HttpResp &resp, const HttpCacheWriteOptions *opts) { TRACE_CALL() uint32_t body_handle_out; auto owned_opts = to_fastly_cache_write_options(opts); auto res = fastly::http_cache_transaction_insert(this->handle, resp.handle, owned_opts.mask, owned_opts.options.get(), &body_handle_out); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(HttpBody(body_handle_out)); } Result> HttpCacheEntry::transaction_insert_and_stream_back(const HttpResp &resp, const HttpCacheWriteOptions *opts) { TRACE_CALL_ARGS(TSV(std::to_string(this->handle)), TSV(std::to_string(resp.handle))) uint32_t body_handle_out; uint32_t cache_handle_out; auto owned_opts = to_fastly_cache_write_options(opts); auto res = fastly::http_cache_transaction_insert_and_stream_back( this->handle, resp.handle, owned_opts.mask, owned_opts.options.get(), &body_handle_out, &cache_handle_out); if (res != 0) { return Result>::err(host_api::APIError(res)); } TRACE_CALL_RET(TSV(std::to_string(body_handle_out)), TSV(std::to_string(cache_handle_out))) return Result>::ok( std::make_tuple(HttpBody(body_handle_out), HttpCacheEntry(cache_handle_out))); } Result HttpCacheEntry::transaction_update(const HttpResp &resp, const HttpCacheWriteOptions *opts) { TRACE_CALL() auto owned_opts = to_fastly_cache_write_options(opts); auto res = fastly::http_cache_transaction_update(this->handle, resp.handle, owned_opts.mask, owned_opts.options.get()); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(Void{}); } Result HttpCacheEntry::transaction_update_and_return_fresh(const HttpResp &resp, const HttpCacheWriteOptions *opts) { TRACE_CALL() uint32_t fresh_handle_out; auto owned_opts = to_fastly_cache_write_options(opts); auto res = fastly::http_cache_transaction_update_and_return_fresh( this->handle, resp.handle, owned_opts.mask, owned_opts.options.get(), &fresh_handle_out); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(HttpCacheEntry(fresh_handle_out)); } Result HttpCacheEntry::transaction_record_not_cacheable(uint64_t max_age_ns, std::optional vary_rule) { TRACE_CALL() HttpCacheWriteOptions write_options{.max_age_ns = max_age_ns}; if (auto &vary_rule_val = vary_rule) { write_options.vary_rule = *vary_rule; } auto owned_opts = to_fastly_cache_write_options(&write_options); auto res = fastly::http_cache_transaction_record_not_cacheable(this->handle, owned_opts.mask, owned_opts.options.get()); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(Void{}); } Result HttpCacheEntry::transaction_abandon() { TRACE_CALL() auto res = fastly::http_cache_transaction_abandon(this->handle); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(Void{}); } Result HttpCacheEntry::close() { TRACE_CALL() auto res = fastly::http_cache_close(this->handle); if (res != 0) { return Result::err(host_api::APIError(res)); } handle = invalid; return Result::ok(Void{}); } Result HttpCacheEntry::get_suggested_backend_request() const { TRACE_CALL_ARGS(TSV(std::to_string(this->handle))) uint32_t req_handle_out; auto res = fastly::http_cache_get_suggested_backend_request(this->handle, &req_handle_out); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(HttpReq(req_handle_out)); } Result HttpCacheEntry::get_suggested_cache_options(const HttpResp &resp) const { TRACE_CALL_ARGS(TSV(std::to_string(this->handle)), TSV(std::to_string(resp.handle))) const uint32_t options_mask = FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_VARY_RULE | FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_INITIAL_AGE_NS | FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_STALE_WHILE_REVALIDATE_NS | FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_SURROGATE_KEYS | FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_LENGTH | FASTLY_HTTP_CACHE_WRITE_OPTIONS_MASK_SENSITIVE_DATA; // Allocate initial buffers uint8_t *vary_buffer = static_cast(cabi_malloc(HOSTCALL_BUFFER_LEN, 4)); uint8_t *surrogate_buffer = static_cast(cabi_malloc(HOSTCALL_BUFFER_LEN, 4)); if (!vary_buffer || !surrogate_buffer) { cabi_free(vary_buffer); cabi_free(surrogate_buffer); return Result::err( host_api::APIError(FASTLY_HOST_ERROR_GENERIC_ERROR)); } fastly::fastly_http_cache_write_options options_in{}; options_in.vary_rule = reinterpret_cast(vary_buffer); options_in.vary_rule_len = HOSTCALL_BUFFER_LEN; options_in.surrogate_keys = reinterpret_cast(surrogate_buffer); options_in.surrogate_keys_len = HOSTCALL_BUFFER_LEN; fastly::fastly_http_cache_write_options options_out{}; uint32_t options_mask_out; auto res = fastly::http_cache_get_suggested_cache_options( this->handle, resp.handle, options_mask, &options_in, &options_mask_out, &options_out); if (res != 0) { cabi_free(vary_buffer); cabi_free(surrogate_buffer); return Result::err(host_api::APIError(res)); } auto result = from_fastly_cache_write_options(options_out, options_mask_out); cabi_free(vary_buffer); cabi_free(surrogate_buffer); return Result::ok(result); } Result> HttpCacheEntry::prepare_response_for_storage(HttpResp resp) const { TRACE_CALL_ARGS(TSV(std::to_string(this->handle)), TSV(std::to_string(resp.handle))) alignas(4) HttpStorageAction storage_action_out; uint32_t updated_resp_handle_out; auto res = fastly::http_cache_prepare_response_for_storage( this->handle, resp.handle, reinterpret_cast(&storage_action_out), &updated_resp_handle_out); if (res != 0) { return Result>::err(host_api::APIError(res)); } return Result>::ok( std::make_tuple(storage_action_out, HttpResp(updated_resp_handle_out))); } Result> HttpCacheEntry::get_found_response(bool transform_for_client) const { TRACE_CALL_ARGS(TSV(std::to_string(this->handle))) uint32_t resp_handle_out; uint32_t body_handle_out; auto res = fastly::http_cache_get_found_response(this->handle, transform_for_client ? 1 : 0, &resp_handle_out, &body_handle_out); if (res != 0) { if (host_api::error_is_optional_none(host_api::APIError(res))) { return Result>::ok(std::nullopt); } return Result>::err(host_api::APIError(res)); } TRACE_CALL_RET(TSV(std::to_string(resp_handle_out)), TSV(std::to_string(body_handle_out))) return Result>::ok( Response(HttpResp(resp_handle_out), HttpBody(body_handle_out))); } Result HttpCacheEntry::get_state() const { TRACE_CALL_ARGS(TSV(std::to_string(this->handle))) Result res; fastly::fastly_host_error err; alignas(4) uint8_t state; if (!convert_result(fastly::http_cache_get_state(this->handle, &state), &err)) { res.emplace_err(err); } else { res.emplace(CacheState{state}); } return res; } Result> HttpCacheEntry::get_length() const { TRACE_CALL() uint64_t length_out; auto res = fastly::http_cache_get_length(this->handle, &length_out); if (res != 0) { if (host_api::error_is_optional_none(host_api::APIError(res))) { return Result>::ok(std::nullopt); } return Result>::err(host_api::APIError(res)); } return Result>::ok(length_out); } Result HttpCacheEntry::get_max_age_ns() const { TRACE_CALL() uint64_t max_age_out; auto res = fastly::http_cache_get_max_age_ns(this->handle, &max_age_out); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(max_age_out); } Result HttpCacheEntry::get_stale_while_revalidate_ns() const { TRACE_CALL() uint64_t swr_out; auto res = fastly::http_cache_get_stale_while_revalidate_ns(this->handle, &swr_out); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(swr_out); } Result HttpCacheEntry::get_age_ns() const { TRACE_CALL() uint64_t age_out; auto res = fastly::http_cache_get_age_ns(this->handle, &age_out); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(age_out); } Result HttpCacheEntry::get_hits() const { TRACE_CALL() uint64_t hits_out; auto res = fastly::http_cache_get_hits(this->handle, &hits_out); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(hits_out); } Result HttpCacheEntry::get_sensitive_data() const { TRACE_CALL() uint32_t is_sensitive_out; auto res = fastly::http_cache_get_sensitive_data(this->handle, &is_sensitive_out); if (res != 0) { return Result::err(host_api::APIError(res)); } return Result::ok(is_sensitive_out != 0); } Result> HttpCacheEntry::get_surrogate_keys() const { TRACE_CALL() // Allocate initial buffer size_t nwritten; uint8_t *buffer = static_cast(cabi_malloc(HOSTCALL_BUFFER_LEN, 4)); if (!buffer) { return Result>::err( host_api::APIError(FASTLY_HOST_ERROR_GENERIC_ERROR)); } auto res = fastly::http_cache_get_surrogate_keys(this->handle, reinterpret_cast(buffer), HOSTCALL_BUFFER_LEN, &nwritten); if (res != 0) { if (host_api::error_is_optional_none(host_api::APIError(res))) { cabi_free(buffer); return Result>::ok(std::vector{}); } if (host_api::error_is_buffer_len(host_api::APIError(res))) { // Resize buffer and try again uint8_t *new_buffer = static_cast(cabi_realloc(buffer, HOSTCALL_BUFFER_LEN, 1, nwritten)); if (!new_buffer) { cabi_free(buffer); return Result>::err( host_api::APIError(FASTLY_HOST_ERROR_GENERIC_ERROR)); } buffer = new_buffer; res = fastly::http_cache_get_surrogate_keys(this->handle, reinterpret_cast(buffer), nwritten, &nwritten); if (res != 0) { cabi_free(buffer); return Result>::err(host_api::APIError(res)); } } else { cabi_free(buffer); return Result>::err(host_api::APIError(res)); } } // Split the buffer into individual keys std::vector keys; const char *start = reinterpret_cast(buffer); const char *end = start + nwritten; const char *key_start = start; for (const char *p = start; p < end; ++p) { if (*p == ' ') { if (p > key_start) { // Skip empty strings from consecutive spaces fastly::fastly_world_string key = { .ptr = static_cast(cabi_malloc(p - key_start, 4)), .len = static_cast(p - key_start)}; if (!key.ptr) { cabi_free(buffer); return Result>::err( host_api::APIError(FASTLY_HOST_ERROR_GENERIC_ERROR)); } std::memcpy(key.ptr, key_start, key.len); keys.push_back(make_host_string(key)); } key_start = p + 1; } } // Handle the last key if there is one if (key_start < end) { fastly::fastly_world_string key = {.ptr = static_cast(cabi_malloc(end - key_start, 4)), .len = static_cast(end - key_start)}; if (!key.ptr) { cabi_free(buffer); return Result>::err( host_api::APIError(FASTLY_HOST_ERROR_GENERIC_ERROR)); } std::memcpy(key.ptr, key_start, key.len); keys.push_back(make_host_string(key)); } cabi_free(buffer); return Result>::ok(std::move(keys)); } Result> HttpCacheEntry::get_vary_rule() const { TRACE_CALL() // Allocate initial buffer size_t nwritten; uint8_t *buffer = static_cast(cabi_malloc(HEADER_MAX_LEN, 4)); if (!buffer) { return Result>::err( host_api::APIError(FASTLY_HOST_ERROR_GENERIC_ERROR)); } auto res = fastly::http_cache_get_vary_rule(this->handle, reinterpret_cast(buffer), HEADER_MAX_LEN, &nwritten); if (res != 0) { if (host_api::error_is_optional_none(host_api::APIError(res))) { cabi_free(buffer); return Result>::ok(std::nullopt); } if (host_api::error_is_buffer_len(host_api::APIError(res))) { // Resize buffer and try again uint8_t *new_buffer = static_cast(cabi_realloc(buffer, HEADER_MAX_LEN, 1, nwritten)); if (!new_buffer) { cabi_free(buffer); return Result>::err( host_api::APIError(FASTLY_HOST_ERROR_GENERIC_ERROR)); } buffer = new_buffer; res = fastly::http_cache_get_vary_rule(this->handle, reinterpret_cast(buffer), nwritten, &nwritten); if (res != 0) { cabi_free(buffer); return Result>::err(host_api::APIError(res)); } } else { cabi_free(buffer); return Result>::err(host_api::APIError(res)); } } fastly::fastly_world_string str = {.ptr = buffer, .len = nwritten}; return Result>::ok(make_host_string(str)); } Result LogEndpoint::get(std::string_view name) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); LogEndpoint::Handle handle; fastly::fastly_host_error err; if (!convert_result( fastly::log_endpoint_get(reinterpret_cast(name_str.ptr), name_str.len, &handle), &err)) { res.emplace_err(err); } else { res.emplace(LogEndpoint{handle}); } return res; } Result LogEndpoint::write(std::string_view msg) { TRACE_CALL() Result res; auto msg_str = string_view_to_world_string(msg); fastly::fastly_host_error err; size_t nwritten = 0; if (!convert_result(fastly::log_write(this->handle, reinterpret_cast(msg_str.ptr), msg_str.len, &nwritten), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result Dict::open(std::string_view name) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); Dict::Handle ret; fastly::fastly_host_error err; if (!convert_result( fastly::dictionary_open(reinterpret_cast(name_str.ptr), name_str.len, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result> Dict::get(std::string_view name) { TRACE_CALL() Result> res; auto name_str = string_view_to_world_string(name); fastly::fastly_world_string ret; fastly::fastly_host_error err; ret.ptr = static_cast(cabi_malloc(DICTIONARY_ENTRY_MAX_LEN, 1)); if (!convert_result(fastly::dictionary_get(this->handle, reinterpret_cast(name_str.ptr), name_str.len, reinterpret_cast(ret.ptr), DICTIONARY_ENTRY_MAX_LEN, &ret.len), &err)) { if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { cabi_free(ret.ptr); res.emplace_err(err); } } else { ret.ptr = static_cast(cabi_realloc(ret.ptr, DICTIONARY_ENTRY_MAX_LEN, 1, ret.len)); res.emplace(make_host_string(ret)); } return res; } Result ConfigStore::open(std::string_view name) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); ConfigStore::Handle ret; fastly::fastly_host_error err; if (!convert_result( fastly::config_store_open(reinterpret_cast(name_str.ptr), name_str.len, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result> ConfigStore::get(std::string_view name) { return this->get(name, CONFIG_STORE_INITIAL_BUF_LEN); } Result> ConfigStore::get(std::string_view name, uint32_t initial_buf_len) { TRACE_CALL() Result> res; uint32_t buf_len{initial_buf_len}; auto name_str = string_view_to_world_string(name); fastly::fastly_world_string ret; fastly::fastly_host_error err; ret.ptr = static_cast(cabi_malloc(buf_len, 1)); bool succeeded{convert_result( fastly::config_store_get(this->handle, reinterpret_cast(name_str.ptr), name_str.len, reinterpret_cast(ret.ptr), buf_len, &ret.len), &err)}; if (!succeeded && err == FASTLY_HOST_ERROR_BUFFER_LEN) { // NB(@zkat): ERROR_BUFFER_LEN sets the expected length of the buffer to // &ret.len, so we use that to inform our resize. buf_len = ret.len; ret.len = 0; ret.ptr = static_cast(cabi_realloc(ret.ptr, initial_buf_len, 1, buf_len)); succeeded = convert_result( fastly::config_store_get(this->handle, reinterpret_cast(name_str.ptr), name_str.len, reinterpret_cast(ret.ptr), buf_len, &ret.len), &err); } if (!succeeded) { cabi_free(ret.ptr); if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { ret.ptr = static_cast(cabi_realloc(ret.ptr, buf_len, 1, ret.len)); res.emplace(make_host_string(ret)); } return res; } Result ObjectStore::open(std::string_view name) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); ObjectStore::Handle ret; fastly::fastly_host_error err; if (!convert_result( fastly::object_store_open(reinterpret_cast(name_str.ptr), name_str.len, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result> ObjectStore::lookup(std::string_view name) { TRACE_CALL() Result> res; auto name_str = string_view_to_world_string(name); ObjectStore::Handle ret; fastly::fastly_host_error err; bool ok = convert_result(fastly::object_store_get(this->handle, reinterpret_cast(name_str.ptr), name_str.len, &ret), &err); if ((!ok && error_is_optional_none(err)) || ret == INVALID_HANDLE) { res.emplace(std::nullopt); } else { res.emplace(ret); } return res; } Result ObjectStore::lookup_async(std::string_view name) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); ObjectStorePendingLookup::Handle ret; fastly::fastly_host_error err; if (!convert_result(fastly::object_store_get_async( this->handle, reinterpret_cast(name_str.ptr), name_str.len, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result ObjectStore::delete_async(std::string_view name) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); ObjectStorePendingDelete::Handle ret; fastly::fastly_host_error err; if (!convert_result(fastly::object_store_delete_async( this->handle, reinterpret_cast(name_str.ptr), name_str.len, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result ObjectStore::insert(std::string_view name, HttpBody body) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); fastly::fastly_host_error err; if (!convert_result(fastly::object_store_insert(this->handle, reinterpret_cast(name_str.ptr), name_str.len, body.handle), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } FastlyResult, FastlyAPIError> ObjectStorePendingLookup::wait() { TRACE_CALL() FastlyResult, FastlyAPIError> res; fastly::fastly_host_error err; HttpBody::Handle ret = INVALID_HANDLE; bool ok = convert_result(fastly::object_store_pending_lookup_wait(this->handle, &ret), &err); if ((!ok && error_is_optional_none(err)) || ret == INVALID_HANDLE) { res.emplace(std::nullopt); } else { res.emplace(ret); } return res; } FastlyAsyncTask::Handle ObjectStorePendingLookup::async_handle() const { return FastlyAsyncTask::Handle{this->handle}; } Result ObjectStorePendingDelete::wait() { TRACE_CALL() Result res; fastly::fastly_host_error err; if (!convert_result(fastly::object_store_pending_delete_wait(this->handle), &err)) { res.emplace_err(err); } else { res.emplace(Void{}); } return res; } FastlyAsyncTask::Handle ObjectStorePendingDelete::async_handle() const { return FastlyAsyncTask::Handle{this->handle}; } Result> Secret::plaintext() const { return this->plaintext(CONFIG_STORE_INITIAL_BUF_LEN); } Result> Secret::plaintext(uint32_t initial_buf_len) const { TRACE_CALL() Result> res; uint32_t buf_len{initial_buf_len}; fastly::fastly_world_list_u8 ret; fastly::fastly_host_error err; ret.ptr = static_cast(JS_malloc(CONTEXT, buf_len)); bool succeeded{ convert_result(fastly::secret_store_plaintext(this->handle, reinterpret_cast(ret.ptr), buf_len, &ret.len), &err)}; if (!succeeded && err == FASTLY_HOST_ERROR_BUFFER_LEN) { // NB(@zkat): ERROR_BUFFER_LEN sets the expected length of the buffer to // &ret.len, so we use that to inform our resize. buf_len = ret.len; ret.len = 0; ret.ptr = static_cast(JS_realloc(CONTEXT, ret.ptr, initial_buf_len, buf_len)); succeeded = convert_result(fastly::secret_store_plaintext( this->handle, reinterpret_cast(ret.ptr), buf_len, &ret.len), &err); } if (!succeeded) { if (error_is_optional_none(err)) { res.emplace(std::nullopt); } else { JS_free(CONTEXT, ret.ptr); res.emplace_err(err); } } else { ret.ptr = static_cast(JS_realloc(CONTEXT, ret.ptr, buf_len, ret.len)); res.emplace(make_host_bytes(ret.ptr, ret.len)); } return res; } Result SecretStore::open(std::string_view name) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); SecretStore::Handle ret; fastly::fastly_host_error err; if (!convert_result( fastly::secret_store_open(reinterpret_cast(name_str.ptr), name_str.len, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result> SecretStore::get(std::string_view name) { TRACE_CALL() Result> res; auto name_str = string_view_to_world_string(name); Secret::Handle ret = INVALID_HANDLE; fastly::fastly_host_error err; bool ok = convert_result(fastly::secret_store_get(this->handle, reinterpret_cast(name_str.ptr), name_str.len, &ret), &err); if ((!ok && error_is_optional_none(err)) || ret == INVALID_HANDLE) { res.emplace(std::nullopt); } else { res.emplace(ret); } return res; } Result SecretStore::from_bytes(const uint8_t *bytes, size_t len) { TRACE_CALL() Result res; fastly::fastly_world_list_u8 bytes_list{const_cast(bytes), len}; Secret::Handle ret = INVALID_HANDLE; fastly::fastly_host_error err; bool ok = convert_result(fastly::secret_store_from_bytes(reinterpret_cast(bytes_list.ptr), bytes_list.len, &ret), &err); if (!ok || ret == INVALID_HANDLE) { res.emplace_err(err); } else { res.emplace(ret); } return res; } bool CacheState::is_found() const { return this->state & FASTLY_HOST_CACHE_LOOKUP_STATE_FOUND; } bool CacheState::is_usable() const { return this->state & FASTLY_HOST_CACHE_LOOKUP_STATE_USABLE; } bool CacheState::is_stale() const { return this->state & FASTLY_HOST_CACHE_LOOKUP_STATE_STALE; } bool CacheState::must_insert_or_update() const { return this->state & FASTLY_HOST_CACHE_LOOKUP_STATE_MUST_INSERT_OR_UPDATE; } Result CacheHandle::lookup(std::string_view key, const CacheLookupOptions &opts) { TRACE_CALL() Result res; auto key_str = string_view_to_world_string(key); fastly::fastly_host_error err; CacheHandle::Handle handle; fastly::fastly_host_cache_lookup_options os; memset(&os, 0, sizeof(os)); alignas(4) uint8_t options_mask = 0; if (opts.request_headers.is_valid()) { os.request_headers = opts.request_headers.handle; options_mask |= FASTLY_CACHE_LOOKUP_OPTIONS_MASK_REQUEST_HEADERS; } if (!convert_result(fastly::cache_lookup(reinterpret_cast(key_str.ptr), key_str.len, options_mask, &os, &handle), &err)) { res.emplace_err(err); } else { res.emplace(handle); } return res; } Result CacheHandle::transaction_lookup(std::string_view key, const CacheLookupOptions &opts) { TRACE_CALL() Result res; auto key_str = string_view_to_world_string(key); fastly::fastly_host_error err; CacheHandle::Handle handle; fastly::fastly_host_cache_lookup_options os; memset(&os, 0, sizeof(os)); uint32_t options_mask = 0; if (opts.request_headers.is_valid()) { os.request_headers = opts.request_headers.handle; options_mask |= FASTLY_CACHE_LOOKUP_OPTIONS_MASK_REQUEST_HEADERS; } if (!convert_result(fastly::cache_transaction_lookup(reinterpret_cast(key_str.ptr), key_str.len, options_mask, &os, &handle), &err)) { res.emplace_err(err); } else { res.emplace(handle); } return res; } namespace { void init_write_options(fastly::fastly_host_cache_write_options &options, const CacheWriteOptions &opts) { memset(&options, 0, sizeof(options)); options.max_age_ns = opts.max_age_ns; options.request_headers = opts.request_headers.handle; if (opts.vary_rule.empty()) { options.vary_rule.ptr = 0; options.vary_rule.len = 0; } else { options.vary_rule = string_view_to_world_string(opts.vary_rule); } options.initial_age_ns = opts.initial_age_ns; options.stale_while_revalidate_ns = opts.stale_while_revalidate_ns; if (opts.surrogate_keys.empty()) { options.surrogate_keys.ptr = 0; options.surrogate_keys.len = 0; } else { options.surrogate_keys = string_view_to_world_string(opts.surrogate_keys); } options.length = opts.length; if (!opts.metadata.len || !opts.metadata.ptr) { options.user_metadata.ptr = 0; options.user_metadata.len = 0; } else { options.user_metadata = span_to_list_u8(opts.metadata); } options.sensitive_data = opts.sensitive; } } // namespace #define FASTLY_CACHE_WRITE_OPTIONS_MASK_RESERVED (1 << 0) #define FASTLY_CACHE_WRITE_OPTIONS_MASK_REQUEST_HEADERS (1 << 1) #define FASTLY_CACHE_WRITE_OPTIONS_MASK_VARY_RULE (1 << 2) #define FASTLY_CACHE_WRITE_OPTIONS_MASK_INITIAL_AGE_NS (1 << 3) #define FASTLY_CACHE_WRITE_OPTIONS_MASK_STALE_WHILE_REVALIDATE_NS (1 << 4) #define FASTLY_CACHE_WRITE_OPTIONS_MASK_SURROGATE_KEYS (1 << 5) #define FASTLY_CACHE_WRITE_OPTIONS_MASK_LENGTH (1 << 6) #define FASTLY_CACHE_WRITE_OPTIONS_MASK_USER_METADATA (1 << 7) #define FASTLY_CACHE_WRITE_OPTIONS_MASK_SENSITIVE_DATA (1 << 8) Result CacheHandle::insert(std::string_view key, const CacheWriteOptions &os) { TRACE_CALL() Result res; fastly::fastly_host_cache_write_options options; init_write_options(options, os); fastly::fastly_host_error err; HttpBody::Handle ret; auto host_key = string_view_to_world_string(key); uint16_t options_mask = 0; fastly::CacheWriteOptions opts; std::memset(&opts, 0, sizeof(opts)); opts.max_age_ns = options.max_age_ns; if (options.request_headers != INVALID_HANDLE && options.request_headers != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_REQUEST_HEADERS; opts.request_headers = options.request_headers; } if (options.vary_rule.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_VARY_RULE; opts.vary_rule_len = options.vary_rule.len; opts.vary_rule_ptr = reinterpret_cast(options.vary_rule.ptr); } if (options.initial_age_ns != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_INITIAL_AGE_NS; opts.initial_age_ns = options.initial_age_ns; } if (options.stale_while_revalidate_ns != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_STALE_WHILE_REVALIDATE_NS; opts.stale_while_revalidate_ns = options.stale_while_revalidate_ns; } if (options.surrogate_keys.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_SURROGATE_KEYS; opts.surrogate_keys_len = options.surrogate_keys.len; opts.surrogate_keys_ptr = reinterpret_cast(options.surrogate_keys.ptr); } if (options.length != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_LENGTH; opts.length = options.length; } if (options.user_metadata.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_USER_METADATA; opts.user_metadata_len = options.user_metadata.len; opts.user_metadata_ptr = options.user_metadata.ptr; } if (options.sensitive_data) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_SENSITIVE_DATA; } if (!convert_result(fastly::cache_insert(reinterpret_cast(host_key.ptr), host_key.len, options_mask, &opts, &ret), &err)) { res.emplace_err(err); } else { res.emplace(HttpBody{ret}); } return res; } Result CacheHandle::transaction_insert(const CacheWriteOptions &os) { TRACE_CALL() Result res; fastly::fastly_host_cache_write_options options; init_write_options(options, os); fastly::fastly_host_error err; HttpBody::Handle ret; uint16_t options_mask = 0; fastly::CacheWriteOptions opts; std::memset(&opts, 0, sizeof(opts)); opts.max_age_ns = options.max_age_ns; if (options.request_headers != INVALID_HANDLE && options.request_headers != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_REQUEST_HEADERS; opts.request_headers = options.request_headers; } if (options.vary_rule.len > 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_VARY_RULE; opts.vary_rule_len = options.vary_rule.len; opts.vary_rule_ptr = reinterpret_cast(options.vary_rule.ptr); } if (options.initial_age_ns != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_INITIAL_AGE_NS; opts.initial_age_ns = options.initial_age_ns; } if (options.stale_while_revalidate_ns != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_STALE_WHILE_REVALIDATE_NS; opts.stale_while_revalidate_ns = options.stale_while_revalidate_ns; } if (options.surrogate_keys.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_SURROGATE_KEYS; opts.surrogate_keys_len = options.surrogate_keys.len; opts.surrogate_keys_ptr = reinterpret_cast(options.surrogate_keys.ptr); } if (options.length != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_LENGTH; opts.length = options.length; } if (options.user_metadata.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_USER_METADATA; opts.user_metadata_len = options.user_metadata.len; opts.user_metadata_ptr = options.user_metadata.ptr; } if (options.sensitive_data) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_SENSITIVE_DATA; } if (!convert_result(fastly::cache_transaction_insert(this->handle, options_mask, &opts, &ret), &err)) { res.emplace_err(err); } else { res.emplace(HttpBody{ret}); } return res; } Result CacheHandle::transaction_update(const CacheWriteOptions &os) { TRACE_CALL() Result res; fastly::fastly_host_cache_write_options options; init_write_options(options, os); fastly::fastly_host_error err; uint16_t options_mask = 0; fastly::CacheWriteOptions opts; std::memset(&opts, 0, sizeof(opts)); opts.max_age_ns = options.max_age_ns; if (options.request_headers != INVALID_HANDLE && options.request_headers != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_REQUEST_HEADERS; opts.request_headers = options.request_headers; } if (options.vary_rule.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_VARY_RULE; opts.vary_rule_len = options.vary_rule.len; opts.vary_rule_ptr = reinterpret_cast(options.vary_rule.ptr); } if (options.initial_age_ns != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_INITIAL_AGE_NS; opts.initial_age_ns = options.initial_age_ns; } if (options.stale_while_revalidate_ns != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_STALE_WHILE_REVALIDATE_NS; opts.stale_while_revalidate_ns = options.stale_while_revalidate_ns; } if (options.surrogate_keys.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_SURROGATE_KEYS; opts.surrogate_keys_len = options.surrogate_keys.len; opts.surrogate_keys_ptr = reinterpret_cast(options.surrogate_keys.ptr); } if (options.length != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_LENGTH; opts.length = options.length; } if (options.user_metadata.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_USER_METADATA; opts.user_metadata_len = options.user_metadata.len; opts.user_metadata_ptr = options.user_metadata.ptr; } if (options.sensitive_data) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_SENSITIVE_DATA; } if (!convert_result(fastly::cache_transaction_update(this->handle, options_mask, &opts), &err)) { res.emplace_err(err); } else { res.emplace(Void{}); } return res; } Result> CacheHandle::transaction_insert_and_stream_back(const CacheWriteOptions &os) { TRACE_CALL_ARGS(TSV(std::to_string(this->handle))) Result> res; fastly::fastly_host_cache_write_options options; init_write_options(options, os); fastly::fastly_host_error err; fastly::fastly_world_tuple2_handle_handle ret; uint16_t options_mask = 0; fastly::CacheWriteOptions opts; std::memset(&opts, 0, sizeof(opts)); opts.max_age_ns = options.max_age_ns; MOZ_ASSERT(options.request_headers == INVALID_HANDLE || options.request_headers == 0); if (options.vary_rule.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_VARY_RULE; opts.vary_rule_len = options.vary_rule.len; opts.vary_rule_ptr = options.vary_rule.ptr; } if (options.initial_age_ns != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_INITIAL_AGE_NS; opts.initial_age_ns = options.initial_age_ns; } if (options.stale_while_revalidate_ns != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_STALE_WHILE_REVALIDATE_NS; opts.stale_while_revalidate_ns = options.stale_while_revalidate_ns; } if (options.surrogate_keys.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_SURROGATE_KEYS; opts.surrogate_keys_len = options.surrogate_keys.len; opts.surrogate_keys_ptr = options.surrogate_keys.ptr; } if (options.length != 0) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_LENGTH; opts.length = options.length; } if (options.user_metadata.ptr != nullptr) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_USER_METADATA; opts.user_metadata_len = options.user_metadata.len; opts.user_metadata_ptr = options.user_metadata.ptr; } if (options.sensitive_data) { options_mask |= FASTLY_CACHE_WRITE_OPTIONS_MASK_SENSITIVE_DATA; } if (!convert_result(fastly::cache_transaction_insert_and_stream_back(this->handle, options_mask, &opts, &ret.f0, &ret.f1), &err)) { res.emplace_err(err); } else { res.emplace(HttpBody{ret.f0}, CacheHandle{ret.f1}); } return res; } Result CacheHandle::transaction_cancel() { TRACE_CALL() Result res; fastly::fastly_host_error err; if (!convert_result(fastly::cache_transaction_cancel(this->handle), &err)) { res.emplace_err(err); } else { res.emplace(); } return res; } Result CacheHandle::get_body(const CacheGetBodyOptions &opts) { TRACE_CALL() Result res; fastly::fastly_host_cache_get_body_options options{}; uint32_t options_mask = 0; if (opts.start.has_value()) { options_mask |= FASTLY_HOST_CACHE_GET_BODY_OPTIONS_MASK_START; options.start = opts.start.value(); } if (opts.end.has_value()) { options_mask |= FASTLY_HOST_CACHE_GET_BODY_OPTIONS_MASK_END; options.end = opts.end.value(); } HttpBody::Handle body = INVALID_HANDLE; fastly::fastly_host_error err; bool ok = convert_result(fastly::cache_get_body(this->handle, options_mask, &options, &body), &err); if (!ok && !error_is_optional_none(err)) { res.emplace_err(err); } else { res.emplace(HttpBody{body}); } return res; } Result CacheHandle::get_state() { TRACE_CALL() Result res; fastly::fastly_host_error err; alignas(4) uint8_t state; if (!convert_result(fastly::cache_get_state(this->handle, &state), &err)) { res.emplace_err(err); } else { res.emplace(CacheState{state}); } return res; } Result CacheHandle::close() { TRACE_CALL() fastly::fastly_host_error err; if (!convert_result(fastly::cache_close(this->handle), &err)) { return Result::err(err); } return Result::ok(); ; } Result CacheHandle::get_user_metadata() { TRACE_CALL() Result res; fastly::fastly_world_list_u8 ret; fastly::fastly_host_error err; size_t default_size = 16 * 1024; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::cache_get_user_metadata(handle, reinterpret_cast(ret.ptr), default_size, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { // NB(@zkat): ERROR_BUFFER_LEN sets the expected length of the buffer to // &ret.len, so we use that to inform our resize. ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::cache_get_user_metadata(handle, reinterpret_cast(ret.ptr), ret.len, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); res.emplace_err(err); } else { res.emplace(make_host_bytes(ret.ptr, ret.len)); } return res; } Result CacheHandle::get_length() { TRACE_CALL() Result res; uint64_t ret; fastly::fastly_host_error err; if (!convert_result(fastly::cache_get_length(this->handle, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result CacheHandle::get_max_age_ns() { TRACE_CALL() Result res; uint64_t ret; fastly::fastly_host_error err; if (!convert_result(fastly::cache_get_max_age_ns(this->handle, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result CacheHandle::get_stale_while_revalidate_ns() { TRACE_CALL() Result res; uint64_t ret; fastly::fastly_host_error err; if (!convert_result(fastly::cache_get_stale_while_revalidate_ns(this->handle, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result CacheHandle::get_age_ns() { TRACE_CALL() Result res; uint64_t ret; fastly::fastly_host_error err; if (!convert_result(fastly::cache_get_age_ns(this->handle, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result CacheHandle::get_hits() { TRACE_CALL() Result res; uint64_t ret; fastly::fastly_host_error err; if (!convert_result(fastly::cache_get_hits(this->handle, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } const std::optional FastlyKVError::message() const { switch (this->detail) { /// The kv-error-detail struct has not been populated. case uninitialized: return "Uninitialized."; /// Host error / no error case ok: case host_error: return std::nullopt; /// Bad request. case bad_request: return "Bad request."; /// KV store entry not found. case not_found: return "Not found."; /// Invalid state for operation. case precondition_failed: return "Precondition failed."; /// Buffer size issues. case payload_too_large: return "Payload too large."; /// Oh no. case internal_error: return "Internal error."; /// Rate limiting case too_many_requests: return "Too many requests."; /// Store handle not recognized case invalid_store_handle: return "Invalid Store handle."; }; } const std::optional FastlySendError::message() const { switch (this->tag) { /// The send-error-detail struct has not been populated. /// We will our generic error message in this situation. case uninitialized: { return "NetworkError when attempting to fetch resource."; } /// There was no send error. case ok: { return std::nullopt; } /// The system encountered a timeout when trying to find an IP address for the backend /// hostname. case dns_timeout: { return "DNS timeout"; } /// The system encountered a DNS error when trying to find an IP address for the backend /// hostname. The fields dns_error_rcode and dns_error_info_code may be set in the /// send_error_detail. case dns_error: { // allocate maximum len of error message char buf[34 + 10 + 1]; int written = snprintf(buf, sizeof(buf), "DNS error (rcode=%d, info_code=%d)", this->dns_error_rcode, this->dns_error_info_code); MOZ_ASSERT(written > 34); return std::string(buf, written); } /// The system cannot determine which backend to use, or the specified backend was invalid. case destination_not_found: { return "Destination not found"; } /// The system considers the backend to be unavailable; e.g., recent attempts to communicate /// with it may have failed, or a health check may indicate that it is down. case destination_unavailable: { return "Destination unavailable"; } /// The system cannot find a route to the next_hop IP address. case destination_ip_unroutable: { return "Destination IP unroutable"; } /// The system's connection to the backend was refused. case connection_refused: { return "Connection refused"; } /// The system's connection to the backend was closed before a complete response was /// received. case connection_terminated: { return "Connection terminated"; } /// The system's attempt to open a connection to the backend timed out. case connection_timeout: { return "Connection timeout"; } /// The system is configured to limit the number of connections it has to the backend, and /// that limit has been exceeded. case connection_limit_reached: { return "Connection limit reached"; } /// The system encountered an error when verifying the certificate presented by the backend. case tls_certificate_error: { return "TLS certificate error"; } /// The system encountered an error with the backend TLS configuration. case tls_configuration_error: { return "TLS configuration error"; } /// The system received an incomplete response to the request from the backend. case http_incomplete_response: { return "Incomplete HTTP response"; } /// The system received a response to the request whose header section was considered too /// large. case http_response_header_section_too_large: { return "HTTP response header section too large"; } /// The system received a response to the request whose body was considered too large. case http_response_body_too_large: { return "HTTP response body too large"; } /// The system reached a configured time limit waiting for the complete response. case http_response_timeout: { return "HTTP response timeout"; } /// The system received a response to the request whose status code or reason phrase was /// invalid. case http_response_status_invalid: { return "HTTP response status invalid"; } /// The process of negotiating an upgrade of the HTTP version between the system and the /// backend failed. case http_upgrade_failed: { return "HTTP upgrade failed"; } /// The system encountered an HTTP protocol error when communicating with the backend. This /// error will only be used when a more specific one is not defined. case http_protocol_error: { return "HTTP protocol error"; } /// An invalid cache key was provided for the request. case http_request_cache_key_invalid: { return "HTTP request cache key invalid"; } /// An invalid URI was provided for the request. case http_request_uri_invalid: { return "HTTP request URI invalid"; } /// The system encountered an unexpected internal error. case internal_error: { return "Internal error"; } /// The system received a TLS alert from the backend. The field tls_alert_id may be set in /// the send_error_detail. case tls_alert_received: { // allocate maximum len of error message char buf[34 + 1]; int written = snprintf(buf, sizeof(buf), "TLS alert received (alert_id=%d)", this->tls_alert_id); MOZ_ASSERT(written > 35); return std::string(buf, written); } /// The system encountered a TLS error when communicating with the backend, either during /// the handshake or afterwards. case tls_protocol_error: { return "TLS protocol error"; } } return "NetworkError when attempting to fetch resource."; } const std::optional FastlyImageOptimizerError::message() const { if (is_host_error) return std::nullopt; switch (err) { case ok: return std::nullopt; case uninitialized: return "Uninitialized: " + msg; case warning: return "Warning: " + msg; case error: return "Error: " + msg; } return std::nullopt; } bool BackendHealth::is_unknown() const { return this->state & FASTLY_HOST_BACKEND_BACKEND_HEALTH_UNKNOWN; } bool BackendHealth::is_healthy() const { return this->state & FASTLY_HOST_BACKEND_BACKEND_HEALTH_HEALTHY; } bool BackendHealth::is_unhealthy() const { return this->state & FASTLY_HOST_BACKEND_BACKEND_HEALTH_UNHEALTHY; } Result Backend::exists(std::string_view name) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); alignas(4) bool ret; fastly::fastly_host_error err; if (!convert_result(fastly::backend_exists(reinterpret_cast(name_str.ptr), name_str.len, (uint32_t *)&ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result Backend::health() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t fastly_backend_health; if (!convert_result(fastly::backend_is_healthy(reinterpret_cast(name_str.ptr), name_str.len, &fastly_backend_health), &err)) { res.emplace_err(err); } else { switch (fastly_backend_health) { case FASTLY_HOST_BACKEND_BACKEND_HEALTH_UNKNOWN: case FASTLY_HOST_BACKEND_BACKEND_HEALTH_HEALTHY: case FASTLY_HOST_BACKEND_BACKEND_HEALTH_UNHEALTHY: { res.emplace(BackendHealth(fastly_backend_health)); break; } default: { MOZ_CRASH("Making a BackendHealth from an invalid value"); } } } return res; } Result Backend::is_dynamic() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t is_dynamic; if (!convert_result(fastly::backend_is_dynamic(reinterpret_cast(name_str.ptr), name_str.len, &is_dynamic), &err)) { res.emplace_err(err); } else { res.emplace(is_dynamic); } return res; } Result Backend::get_host() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; fastly::fastly_world_string ret; ret.ptr = static_cast(cabi_malloc(HOSTCALL_BUFFER_LEN, 4)); if (!convert_result(fastly::backend_get_host(reinterpret_cast(name_str.ptr), name_str.len, ret.ptr, HOSTCALL_BUFFER_LEN, &ret.len), &err)) { res.emplace_err(err); } else { res.emplace(make_host_string(ret)); } return res; } Result Backend::get_override_host() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; fastly::fastly_world_string ret; ret.ptr = static_cast(cabi_malloc(HOSTCALL_BUFFER_LEN, 4)); if (!convert_result(fastly::backend_get_override_host(reinterpret_cast(name_str.ptr), name_str.len, ret.ptr, HOSTCALL_BUFFER_LEN, &ret.len), &err)) { res.emplace_err(err); } else { res.emplace(make_host_string(ret)); } return res; } Result Backend::get_port() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint16_t port; if (!convert_result( fastly::backend_get_port(reinterpret_cast(name_str.ptr), name_str.len, &port), &err)) { res.emplace_err(err); } else { res.emplace(port); } return res; } Result> Backend::get_connect_timeout_ms() const { TRACE_CALL() Result> res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t connect_timeout_ms; if (!convert_result(fastly::backend_get_connect_timeout_ms(reinterpret_cast(name_str.ptr), name_str.len, &connect_timeout_ms), &err)) { if (host_api::error_is_unsupported(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(connect_timeout_ms); } return res; } Result> Backend::get_first_byte_timeout_ms() const { TRACE_CALL() Result> res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t first_byte_timeout_ms; if (!convert_result( fastly::backend_get_first_byte_timeout_ms(reinterpret_cast(name_str.ptr), name_str.len, &first_byte_timeout_ms), &err)) { if (host_api::error_is_unsupported(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(first_byte_timeout_ms); } return res; } Result> Backend::get_between_bytes_timeout_ms() const { TRACE_CALL() Result> res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t between_bytes_timeout_ms; if (!convert_result( fastly::backend_get_between_bytes_timeout_ms(reinterpret_cast(name_str.ptr), name_str.len, &between_bytes_timeout_ms), &err)) { if (host_api::error_is_unsupported(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(between_bytes_timeout_ms); } return res; } Result Backend::get_http_keepalive_time() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t http_keepalive_time; if (!convert_result( fastly::backend_get_http_keepalive_time(reinterpret_cast(name_str.ptr), name_str.len, &http_keepalive_time), &err)) { res.emplace_err(err); } else { res.emplace(http_keepalive_time); } return res; } Result Backend::get_tcp_keepalive_enable() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t tcp_keepalive_enable; if (!convert_result( fastly::backend_get_tcp_keepalive_enable(reinterpret_cast(name_str.ptr), name_str.len, &tcp_keepalive_enable), &err)) { res.emplace_err(err); } else { res.emplace(tcp_keepalive_enable); } return res; } Result Backend::get_tcp_keepalive_interval() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t tcp_keepalive_interval; if (!convert_result( fastly::backend_get_tcp_keepalive_interval(reinterpret_cast(name_str.ptr), name_str.len, &tcp_keepalive_interval), &err)) { res.emplace_err(err); } else { res.emplace(tcp_keepalive_interval); } return res; } Result Backend::get_tcp_keepalive_probes() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t tcp_keepalive_probes; if (!convert_result( fastly::backend_get_tcp_keepalive_probes(reinterpret_cast(name_str.ptr), name_str.len, &tcp_keepalive_probes), &err)) { res.emplace_err(err); } else { res.emplace(tcp_keepalive_probes); } return res; } Result Backend::get_tcp_keepalive_time() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t tcp_keepalive_time; if (!convert_result(fastly::backend_get_tcp_keepalive_time(reinterpret_cast(name_str.ptr), name_str.len, &tcp_keepalive_time), &err)) { res.emplace_err(err); } else { res.emplace(tcp_keepalive_time); } return res; } Result Backend::is_ssl() const { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t fastly_backend_is_ssl; if (!convert_result(fastly::backend_is_ssl(reinterpret_cast(name_str.ptr), name_str.len, &fastly_backend_is_ssl), &err)) { res.emplace_err(err); } else { res.emplace(fastly_backend_is_ssl); } return res; } Result> Backend::ssl_min_version() const { TRACE_CALL() Result> res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t fastly_backend_ssl_min_version; if (!convert_result(fastly::backend_get_ssl_min_version(reinterpret_cast(name_str.ptr), name_str.len, &fastly_backend_ssl_min_version), &err)) { if (host_api::error_is_unsupported(err) || host_api::error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(fastly_backend_ssl_min_version); } return res; } Result> Backend::ssl_max_version() const { TRACE_CALL() Result> res; auto name_str = string_view_to_world_string(this->name_); fastly::fastly_host_error err; uint32_t fastly_backend_ssl_max_version; if (!convert_result(fastly::backend_get_ssl_max_version(reinterpret_cast(name_str.ptr), name_str.len, &fastly_backend_ssl_max_version), &err)) { if (host_api::error_is_unsupported(err) || host_api::error_is_optional_none(err)) { res.emplace(std::nullopt); } else { res.emplace_err(err); } } else { res.emplace(fastly_backend_ssl_max_version); } return res; } Result RateCounter::increment(std::string_view name, std::string_view entry, uint32_t delta) { TRACE_CALL() auto name_str = string_view_to_world_string(name); auto entry_str = string_view_to_world_string(entry); fastly::fastly_host_error err; if (!convert_result(fastly::ratecounter_increment( reinterpret_cast(name_str.ptr), name_str.len, reinterpret_cast(entry_str.ptr), entry_str.len, delta), &err)) { return Result::err(err); } return Result::ok(); } Result RateCounter::lookup_rate(std::string_view name, std::string_view entry, uint32_t window) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); auto entry_str = string_view_to_world_string(entry); uint32_t ret; fastly::fastly_host_error err; if (!convert_result(fastly::ratecounter_lookup_rate( reinterpret_cast(name_str.ptr), name_str.len, reinterpret_cast(entry_str.ptr), entry_str.len, window, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result RateCounter::lookup_count(std::string_view name, std::string_view entry, uint32_t duration) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); auto entry_str = string_view_to_world_string(entry); uint32_t ret; fastly::fastly_host_error err; if (!convert_result(fastly::ratecounter_lookup_count( reinterpret_cast(name_str.ptr), name_str.len, reinterpret_cast(entry_str.ptr), entry_str.len, duration, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result PenaltyBox::add(std::string_view name, std::string_view entry, uint32_t time_to_live) { TRACE_CALL() auto name_str = string_view_to_world_string(name); auto entry_str = string_view_to_world_string(entry); fastly::fastly_host_error err; if (!convert_result(fastly::penaltybox_add(reinterpret_cast(name_str.ptr), name_str.len, reinterpret_cast(entry_str.ptr), entry_str.len, time_to_live), &err)) { return Result::err(err); } return Result::ok(); } Result PenaltyBox::has(std::string_view name, std::string_view entry) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); auto entry_str = string_view_to_world_string(entry); alignas(4) bool ret; fastly::fastly_host_error err; if (!convert_result(fastly::penaltybox_has(reinterpret_cast(name_str.ptr), name_str.len, reinterpret_cast(entry_str.ptr), entry_str.len, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result EdgeRateLimiter::check_rate(std::string_view rate_counter_name, std::string_view entry, uint32_t delta, uint32_t window, uint32_t limit, std::string_view penalty_box_name, uint32_t time_to_live) { TRACE_CALL() Result res; auto rate_counter_name_str = string_view_to_world_string(rate_counter_name); auto entry_str = string_view_to_world_string(entry); auto penalty_box_name_str = string_view_to_world_string(penalty_box_name); alignas(4) bool ret; fastly::fastly_host_error err; if (!convert_result(fastly::check_rate(reinterpret_cast(rate_counter_name_str.ptr), rate_counter_name_str.len, reinterpret_cast(entry_str.ptr), entry_str.len, delta, window, limit, reinterpret_cast(penalty_box_name_str.ptr), penalty_box_name_str.len, time_to_live, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result DeviceDetection::lookup(std::string_view user_agent) { TRACE_CALL() Result res; auto user_agent_str = string_view_to_world_string(user_agent); fastly::fastly_host_error err; fastly::fastly_world_string ret; auto default_size = 1024; ret.ptr = static_cast(cabi_malloc(default_size, 4)); auto status = fastly::device_detection_lookup( reinterpret_cast(user_agent_str.ptr), user_agent_str.len, reinterpret_cast(ret.ptr), default_size, &ret.len); if (status == FASTLY_HOST_ERROR_BUFFER_LEN) { // NB(@zkat): ERROR_BUFFER_LEN sets the expected length of the buffer to // &ret.len, so we use that to inform our resize. ret.ptr = static_cast(cabi_realloc(ret.ptr, default_size, 4, ret.len)); status = fastly::device_detection_lookup(reinterpret_cast(user_agent_str.ptr), user_agent_str.len, reinterpret_cast(ret.ptr), ret.len, &ret.len); } if (!convert_result(status, &err)) { cabi_free(ret.ptr); res.emplace_err(err); } else { res.emplace(make_host_string(ret)); } return res; } Result KVStore::open(std::string_view name) { TRACE_CALL() Result res; auto name_str = string_view_to_world_string(name); KVStore::Handle ret; fastly::fastly_host_error err; if (!convert_result( fastly::kv_store_open(reinterpret_cast(name_str.ptr), name_str.len, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result KVStore::list(std::optional cursor, std::optional limit, std::optional prefix, bool eventual) { TRACE_CALL() Result res; fastly::KVListOptions list_options{eventual ? KV_LIST_MODE_EVENTUAL : KV_LIST_MODE_STRONG}; uint32_t options_mask = 0; if (cursor.has_value()) { options_mask |= KV_LIST_CONFIG_CURSOR; list_options.cursor = reinterpret_cast(cursor.value().data()); list_options.cursor_len = cursor.value().length(); } if (limit.has_value()) { options_mask |= KV_LIST_CONFIG_LIMIT; list_options.limit = limit.value(); } if (prefix.has_value()) { options_mask |= KV_LIST_CONFIG_PREFIX; list_options.prefix = reinterpret_cast(prefix.value().data()); list_options.prefix_len = prefix.value().length(); } KVStore::Handle ret; fastly::fastly_host_error err; if (!convert_result(fastly::kv_store_list(this->handle, options_mask, &list_options, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } FastlyResult KVStorePendingList::wait() { TRACE_CALL() FastlyResult res; fastly::fastly_host_error err; HttpBody body{}; fastly::fastly_kv_error kv_err = KV_ERROR_UNINITIALIZED; if (!convert_result(fastly::kv_store_list_wait(this->handle, &body.handle, &kv_err), &err) || kv_err != KV_ERROR_OK || body.handle == INVALID_HANDLE) { res.emplace_err(make_fastly_kv_error(kv_err, err)); } else { res.emplace(body); } return res; } FastlyAsyncTask::Handle KVStorePendingList::async_handle() const { return FastlyAsyncTask::Handle{this->handle}; } Result KVStore::lookup(std::string_view key) { TRACE_CALL() Result res; fastly::KVLookupOptions lookup_options{}; KVStore::Handle ret; fastly::fastly_host_error err; if (!convert_result( fastly::kv_store_lookup(this->handle, key.data(), key.length(), 0, &lookup_options, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } FastlyResult>, FastlyKVError> KVStorePendingLookup::wait() { TRACE_CALL() FastlyResult>, FastlyKVError> res; fastly::fastly_host_error err; HttpBody body{}; uint64_t gen_out; fastly::fastly_kv_error kv_err = 0; uint8_t *metadata_buf = reinterpret_cast(cabi_malloc(HOSTCALL_BUFFER_LEN, 1)); size_t metadata_nwritten; if (!convert_result(fastly::kv_store_lookup_wait_v2(this->handle, &body.handle, metadata_buf, HOSTCALL_BUFFER_LEN, &metadata_nwritten, &gen_out, &kv_err), &err) || ((kv_err != KV_ERROR_OK || body.handle == INVALID_HANDLE) && kv_err != KV_ERROR_NOT_FOUND)) { cabi_free(metadata_buf); res.emplace_err(make_fastly_kv_error(kv_err, err)); } else if (kv_err == KV_ERROR_NOT_FOUND) { cabi_free(metadata_buf); res.emplace(std::nullopt); } else { if (metadata_nwritten > 0) { cabi_realloc(metadata_buf, HOSTCALL_BUFFER_LEN, 1, metadata_nwritten); res.emplace(std::make_tuple(body, make_host_bytes(metadata_buf, metadata_nwritten), gen_out)); } else { cabi_free(metadata_buf); res.emplace(std::make_tuple(body, HostBytes{}, gen_out)); } } return res; } FastlyAsyncTask::Handle KVStorePendingLookup::async_handle() const { return FastlyAsyncTask::Handle{this->handle}; } Result KVStore::delete_(std::string_view key) { TRACE_CALL() Result res; fastly::KVDeleteOptions delete_options{}; KVStore::Handle ret; fastly::fastly_host_error err; if (!convert_result( fastly::kv_store_delete(this->handle, key.data(), key.length(), 0, &delete_options, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } FastlyResult KVStorePendingDelete::wait() { TRACE_CALL() FastlyResult res; fastly::fastly_host_error err; fastly::fastly_kv_error kv_err = KV_ERROR_UNINITIALIZED; if (!convert_result(fastly::kv_store_delete_wait(this->handle, &kv_err), &err) || kv_err != KV_ERROR_OK) { res.emplace_err(make_fastly_kv_error(kv_err, err)); } return res; } FastlyAsyncTask::Handle KVStorePendingDelete::async_handle() const { return FastlyAsyncTask::Handle{this->handle}; } Result KVStore::insert(std::string_view key, HttpBody body, std::optional mode, std::optional if_generation_match, std::optional> metadata, std::optional ttl) { TRACE_CALL() Result res; fastly::KVInsertOptions insert_options{}; uint32_t options_mask = 0; if (mode.has_value()) { switch (mode.value()) { case InsertMode::add: { insert_options.mode = KV_INSERT_MODE_ADD; break; } case InsertMode::append: { insert_options.mode = KV_INSERT_MODE_APPEND; break; } case InsertMode::overwrite: { insert_options.mode = KV_INSERT_MODE_OVERWRITE; break; } case InsertMode::prepend: { insert_options.mode = KV_INSERT_MODE_PREPEND; break; } } } if (metadata.has_value()) { options_mask |= KV_INSERT_CONFIG_METADATA; insert_options.metadata_len = std::get<1>(metadata.value()); insert_options.metadata = std::get<0>(metadata.value()); } if (if_generation_match.has_value()) { options_mask |= KV_INSERT_CONFIG_IF_GENERATION_MATCH; insert_options.if_generation_match = if_generation_match.value(); } if (ttl.has_value()) { options_mask |= KV_INSERT_CONFIG_TIME_TO_LIVE_SEC; insert_options.time_to_live_sec = ttl.value(); } KVStore::Handle ret; fastly::fastly_host_error err; if (!convert_result(fastly::kv_store_insert(this->handle, key.data(), key.length(), body.handle, options_mask, &insert_options, &ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } FastlyResult KVStorePendingInsert::wait() { TRACE_CALL() FastlyResult res; fastly::fastly_host_error err; fastly::fastly_kv_error kv_err = KV_ERROR_UNINITIALIZED; if (!convert_result(fastly::kv_store_insert_wait(this->handle, &kv_err), &err) || kv_err != KV_ERROR_OK) { res.emplace_err(make_fastly_kv_error(kv_err, err)); } return res; } FastlyAsyncTask::Handle KVStorePendingInsert::async_handle() const { return FastlyAsyncTask::Handle{this->handle}; } Result> Acl::open(std::string_view name) { TRACE_CALL_ARGS(&name) uint32_t handle_out; fastly::fastly_host_error err; if (!convert_result(fastly::acl_open(name.data(), name.size(), &handle_out), &err)) { if (error_is_optional_none(err)) { TRACE_CALL_RET(TSV("")) return Result>::ok(std::nullopt); } else { return Result>::err(host_api::APIError(err)); } } TRACE_CALL_RET(TSV(std::to_string(handle_out))) return Result>::ok(Acl(handle_out)); } Result, Acl::LookupError>> Acl::lookup(std::span ip_octets) const { TRACE_CALL() uint32_t body_handle_out = HttpBody::invalid; fastly::fastly_acl_error acl_error_out = FASTLY_ACL_ERROR_UNINITIALIZED; fastly::fastly_host_error err; if (!convert_result(fastly::acl_lookup(this->handle, ip_octets.data(), ip_octets.size(), &body_handle_out, &acl_error_out), &err)) { if (acl_error_out != FASTLY_ACL_ERROR_OK && acl_error_out != FASTLY_ACL_ERROR_UNINITIALIZED) { return Result, LookupError>>::ok( std::make_tuple(std::nullopt, static_cast(acl_error_out))); } else { return Result, LookupError>>::err(err); } } if (acl_error_out != FASTLY_ACL_ERROR_OK) { return Result, LookupError>>::ok( std::make_tuple(std::nullopt, static_cast(acl_error_out))); } if (body_handle_out == HttpBody::invalid) { return Result, LookupError>>::ok(std::make_tuple( std::nullopt, static_cast(FASTLY_ACL_ERROR_UNINITIALIZED))); } return Result, Acl::LookupError>>::ok(std::make_tuple( HttpBody{body_handle_out}, static_cast(FASTLY_ACL_ERROR_OK))); } Result Compute::get_vcpu_ms() { TRACE_CALL() Result res; uint64_t ret; fastly::fastly_host_error err; if (!convert_result(fastly::compute_get_vcpu_ms(&ret), &err)) { res.emplace_err(err); } else { res.emplace(ret); } return res; } Result> Compute::purge_surrogate_key(std::string_view key, bool soft) { TRACE_CALL() Result> res; auto host_key = string_view_to_world_string(key); fastly::fastly_host_error err; uint32_t options_mask = soft ? FASTLY_HOST_PURGE_OPTIONS_MASK_SOFT_PURGE : 0; fastly::PurgeOptions options{nullptr, 0, nullptr}; MOZ_ASSERT(!(options_mask & FASTLY_HOST_PURGE_OPTIONS_MASK_RET_BUF)); if (!convert_result(fastly::purge_surrogate_key(reinterpret_cast(host_key.ptr), host_key.len, options_mask, &options), &err)) { res.emplace_err(err); } else { res.emplace(std::nullopt); } return res; } } // namespace host_api ================================================ FILE: runtime/fastly/host-api/host_api_fastly.h ================================================ #ifndef FASTLY_HOST_API_H #define FASTLY_HOST_API_H #include #include #include #include #include #include #include #include #include "./fastly.h" #include "extension-api.h" #include "host_api.h" #include "js/TypeDecls.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #include "js/Utility.h" #include "jsapi.h" #pragma clang diagnostic pop struct JSErrorFormatString; void fastly_push_debug_message(std::string msg); // Debug mode debugging logging that logs both into an error response post-data // via fastly.debugMessages, as well as to stderr for flexible debugging. #if defined(DEBUG) #define DEBUG_LOG(msg) fastly_push_debug_message(std::string(msg)); #else #define DEBUG_LOG(msg) #endif namespace fastly { const JSErrorFormatString *FastlyGetErrorMessage(void *userRef, unsigned errorNumber); enum FastlyAPIError { #define MSG_DEF(name, count, exception, format) name, #include "./error_numbers.msg" #undef MSG_DEF JSErrNum_Limit }; const JSErrorFormatString fastly_ErrorFormatString[JSErrNum_Limit] = { #define MSG_DEF(name, count, exception, format) {#name, format, count, exception}, #include "./error_numbers.msg" #undef MSG_DEF }; } // namespace fastly namespace api { template class FastlyResult final { struct Error { E value; explicit Error(E value) : value{value} {} }; std::variant result; public: FastlyResult() = default; /// Explicitly construct an error. static FastlyResult err(E err) { FastlyResult res; res.emplace_err(err); return res; } /// Explicitly construct a successful result. template static FastlyResult ok(Args &&...args) { FastlyResult res; res.emplace(std::forward(args)...); return res; } /// Construct an error in-place. E &emplace_err(E err) & { return this->result.template emplace(err).value; } /// Construct a value of T in-place. template T &emplace(Args &&...args) { return this->result.template emplace(std::forward(args)...); } /// True when the result contains an error. bool is_err() const { return std::holds_alternative(this->result); } /// Return a pointer to the error value of this result, if the call failed. const E *to_err() const { return reinterpret_cast(std::get_if(&this->result)); } /// Assume the call was successful, and return a reference to the result. T &unwrap() { return std::get(this->result); } }; typedef bool ProcessAsyncTask(JSContext *cx, uint32_t handle, JS::HandleObject context, JS::HandleValue extra); class FastlyAsyncTask final : public AsyncTask { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; FastlyAsyncTask(Handle handle, JS::HandleObject context, JS::HandleValue extra, ProcessAsyncTask *process) { if (static_cast(handle) == INVALID_POLLABLE_HANDLE) abort(); handle_ = static_cast(handle); context_ = Heap(context); extra_ = Heap(extra); process_steps_ = process; } [[nodiscard]] bool run(Engine *engine) override { if (process_steps_) { RootedObject context(engine->cx(), context_); RootedValue extra(engine->cx(), extra_); if (!process_steps_(engine->cx(), handle_, context, extra)) { return false; } } return true; } [[nodiscard]] bool cancel(Engine *engine) override { MOZ_ASSERT_UNREACHABLE("Fastly semantics don't allow for cancellation"); return false; } Handle handle() { return handle_; } void trace(JSTracer *trc) override { TraceEdge(trc, &context_, "Async task context"); TraceEdge(trc, &extra_, "Async task extra"); } Heap context_; Heap extra_; ProcessAsyncTask *process_steps_ = nullptr; }; } // namespace api namespace fastly::fetch { class Request; } // namespace fastly::fetch using api::FastlyAsyncTask; using fastly::fetch::Request; namespace host_api { Result write_headers(HttpHeaders *headers, std::vector> &list); class FastlySendError final { public: enum detail { /// The send-error-detail struct has not been populated. uninitialized, /// There was no send error. ok, /// The system encountered a timeout when trying to find an IP address for the backend /// hostname. dns_timeout, /// The system encountered a DNS error when trying to find an IP address for the backend /// hostname. The fields dns_error_rcode and dns_error_info_code may be set in the /// send_error_detail. dns_error, /// The system cannot determine which backend to use, or the specified backend was invalid. destination_not_found, /// The system considers the backend to be unavailable; e.g., recent attempts to communicate /// with it may have failed, or a health check may indicate that it is down. destination_unavailable, /// The system cannot find a route to the next_hop IP address. destination_ip_unroutable, /// The system's connection to the backend was refused. connection_refused, /// The system's connection to the backend was closed before a complete response was /// received. connection_terminated, /// The system's attempt to open a connection to the backend timed out. connection_timeout, /// The system is configured to limit the number of connections it has to the backend, and /// that limit has been exceeded. connection_limit_reached, /// The system encountered an error when verifying the certificate presented by the backend. tls_certificate_error, /// The system encountered an error with the backend TLS configuration. tls_configuration_error, /// The system received an incomplete response to the request from the backend. http_incomplete_response, /// The system received a response to the request whose header section was considered too /// large. http_response_header_section_too_large, /// The system received a response to the request whose body was considered too large. http_response_body_too_large, /// The system reached a configured time limit waiting for the complete response. http_response_timeout, /// The system received a response to the request whose status code or reason phrase was /// invalid. http_response_status_invalid, /// The process of negotiating an upgrade of the HTTP version between the system and the /// backend failed. http_upgrade_failed, /// The system encountered an HTTP protocol error when communicating with the backend. This /// error will only be used when a more specific one is not defined. http_protocol_error, /// An invalid cache key was provided for the request. http_request_cache_key_invalid, /// An invalid URI was provided for the request. http_request_uri_invalid, /// The system encountered an unexpected internal error. internal_error, /// The system received a TLS alert from the backend. The field tls_alert_id may be set in /// the send_error_detail. tls_alert_received, /// The system encountered a TLS error when communicating with the backend, either during /// the handshake or afterwards. tls_protocol_error }; detail tag; uint16_t dns_error_rcode; uint16_t dns_error_info_code; uint8_t tls_alert_id; const std::optional message() const; }; class FastlyKVError final { public: enum detail { /// The kv-error-detail struct has not been populated. uninitialized, /// There was no kv error. ok, /// Bad request. bad_request, /// KV store entry not found. not_found, /// Invalid state for operation. precondition_failed, /// Buffer size issues. payload_too_large, /// Oh no. internal_error, /// Rate limiting too_many_requests, /// Store handle not recognized invalid_store_handle, /// Host error host_error, }; APIError host_err; detail detail; const std::optional message() const; }; /// A convenience wrapper for the host calls involving http bodies. class HttpBody final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; HttpBody() = default; explicit HttpBody(Handle handle) : handle{handle} {} explicit HttpBody(FastlyAsyncTask async) : handle{async.handle()} {} /// Returns true when this body handle is valid. bool valid() const { return this->handle != invalid; } explicit operator bool() const { return valid(); } /// Make a new body handle. static Result make(); /// Read a chunk from this handle. Result read(uint32_t chunk_size) const; /// Read a chunk from this handle in to the specified buffer. Result read_into(uint8_t *ptr, size_t chunk_size) const; /// Read all chunks. Result read_all() const; /// Write a chunk to the front of this handle. Result write_front(const uint8_t *bytes, size_t len) const; /// Write a chunk to the back of this handle. Result write_back(const uint8_t *bytes, size_t len) const; /// Writes the given number of bytes from the given buffer to the front of the given handle. /// /// The host doesn't necessarily write all bytes in any particular call to /// `write`, so to ensure all bytes are written, we call it in a loop. Result write_all_front(const uint8_t *bytes, size_t len) const; /// Writes the given number of bytes from the given buffer to the back of the given handle. /// /// The host doesn't necessarily write all bytes in any particular call to /// `write`, so to ensure all bytes are written, we call it in a loop. Result write_all_back(const uint8_t *bytes, size_t len) const; /// Append another HttpBody to this one. Result append(HttpBody other) const; /// Close this handle, and reset internal state to invalid. Result close(); /// Abandon this handle (close unsuccessfully) and reset internal state Result abandon(); /// Get the length of the body if known Result> known_length() const; FastlyAsyncTask::Handle async_handle() const; Result is_ready() const; }; struct Response; class HttpPendingReq final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; HttpPendingReq() = default; explicit HttpPendingReq(Handle handle) : handle{handle} {} explicit HttpPendingReq(FastlyAsyncTask async) : handle{async.handle()} {} /// Poll for the response to this request. Result> poll(); /// Block until the response is ready. api::FastlyResult wait(); /// Fetch the FastlyAsyncTask for this pending request. FastlyAsyncTask::Handle async_handle() const; }; using HttpVersion = uint8_t; class HttpBase { public: virtual ~HttpBase() = default; virtual bool is_valid() const = 0; /// Get the http version used for this request. virtual Result get_version() const = 0; virtual HttpHeadersReadOnly *headers() = 0; virtual HttpHeaders *headers_writable() = 0; }; struct TlsVersion { uint8_t value = 0; explicit TlsVersion(uint8_t raw); explicit TlsVersion(){}; uint8_t get_version() const; double get_version_number() const; static TlsVersion version_1(); static TlsVersion version_1_1(); static TlsVersion version_1_2(); static TlsVersion version_1_3(); }; typedef uint32_t CertKey; struct ClientCert { HostString cert; CertKey key; }; struct TcpKeepalive { std::optional interval_secs; std::optional probes; std::optional time_secs; }; struct BackendConfig { std::optional host_override; std::optional connect_timeout; std::optional first_byte_timeout; std::optional between_bytes_timeout; std::optional use_ssl; std::optional dont_pool; std::optional ssl_min_version; std::optional ssl_max_version; std::optional cert_hostname; std::optional ca_cert; std::optional ciphers; std::optional sni_hostname; std::optional client_cert; std::optional grpc; std::optional http_keepalive_time_ms; std::optional tcp_keepalive; BackendConfig clone() { std::optional out_host_override{}; std::optional out_connect_timeout{}; std::optional out_first_byte_timeout{}; std::optional out_between_bytes_timeout{}; std::optional out_use_ssl{}; std::optional out_dont_pool{}; std::optional out_ssl_min_version{}; std::optional out_ssl_max_version{}; std::optional out_cert_hostname{}; std::optional out_ca_cert{}; std::optional out_ciphers{}; std::optional out_sni_hostname{}; std::optional out_client_cert{}; std::optional out_grpc{}; std::optional out_http_keepalive_time_ms{}; std::optional out_tcp_keepalive{}; if (host_override.has_value()) { out_host_override = host_api::HostString(std::string_view(host_override.value())); } if (connect_timeout.has_value()) { out_connect_timeout = connect_timeout.value(); } if (first_byte_timeout.has_value()) { out_first_byte_timeout = first_byte_timeout.value(); } if (between_bytes_timeout.has_value()) { out_between_bytes_timeout = between_bytes_timeout.value(); } if (use_ssl.has_value()) { out_use_ssl = use_ssl.value(); } if (dont_pool.has_value()) { out_dont_pool = dont_pool.value(); } if (ssl_min_version.has_value()) { out_ssl_min_version = TlsVersion(ssl_min_version.value().value); } if (ssl_max_version.has_value()) { out_ssl_max_version = TlsVersion(ssl_max_version.value().value); } if (cert_hostname.has_value()) { out_cert_hostname = host_api::HostString(std::string_view(cert_hostname.value())); } if (ca_cert.has_value()) { out_ca_cert = host_api::HostString(std::string_view(ca_cert.value())); } if (ciphers.has_value()) { out_ciphers = host_api::HostString(std::string_view(ciphers.value())); } if (sni_hostname.has_value()) { out_sni_hostname = host_api::HostString(std::string_view(sni_hostname.value())); } if (client_cert.has_value()) { host_api::HostString client_cert_cloned = host_api::HostString(std::string_view(client_cert.value().cert)); out_client_cert = ClientCert{std::move(client_cert_cloned), client_cert.value().key}; } if (grpc.has_value()) { out_grpc = grpc.value(); } if (http_keepalive_time_ms.has_value()) { out_http_keepalive_time_ms = http_keepalive_time_ms.value(); } if (tcp_keepalive.has_value()) { out_tcp_keepalive = tcp_keepalive.value(); } return BackendConfig{std::move(out_host_override), std::move(out_connect_timeout), std::move(out_first_byte_timeout), std::move(out_between_bytes_timeout), std::move(out_use_ssl), std::move(out_dont_pool), std::move(out_ssl_min_version), std::move(out_ssl_max_version), std::move(out_cert_hostname), std::move(out_ca_cert), std::move(out_ciphers), std::move(out_sni_hostname), std::move(out_client_cert), std::move(out_grpc), std::move(out_http_keepalive_time_ms), std::move(out_tcp_keepalive)}; } }; struct CacheOverrideTag final { uint8_t value = 0; void set_pass(); void set_ttl(); void set_stale_while_revalidate(); void set_pci(); }; enum class FramingHeadersMode : uint8_t { Automatic, ManuallyFromHeaders, }; class FastlyImageOptimizerError final { public: enum detail { uninitialized, ok, error, warning }; FastlyImageOptimizerError(detail err, std::string msg) : err(err), is_host_error(false), msg(std::move(msg)) {} FastlyImageOptimizerError(APIError host_err) : host_err(host_err), is_host_error(true) {} union { APIError host_err; detail err; }; bool is_host_error; const std::optional message() const; private: std::string msg; }; class InspectOptions final { public: const char *corp = nullptr; uint32_t corp_len = 0; const char *workspace = nullptr; uint32_t workspace_len = 0; const char *override_client_ip_ptr = nullptr; uint32_t override_client_ip_len = 0; uint32_t req_handle; uint32_t body_handle; InspectOptions() = default; explicit InspectOptions(uint32_t req, uint32_t body) : req_handle{req}, body_handle{body} {} }; class HttpReq final : public HttpBase { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; HttpReq() = default; explicit HttpReq(Handle handle) : handle{handle} {} static Result make(); Result redirect_to_grip_proxy(std::string_view backend); Result redirect_to_websocket_proxy(std::string_view backend); static Result register_dynamic_backend(std::string_view name, std::string_view target, const BackendConfig &config); Result> http_req_downstream_client_request_id(); /// Get the downstream ip address. Result downstream_client_ip_addr(); Result downstream_server_ip_addr(); Result> http_req_downstream_tls_cipher_openssl_name(); Result> http_req_downstream_tls_protocol(); Result> http_req_downstream_tls_client_hello(); Result> http_req_downstream_tls_raw_client_certificate(); Result> http_req_downstream_tls_ja3_md5(); Result> http_req_downstream_tls_ja4(); Result> http_req_downstream_client_h2_fingerprint(); Result> http_req_downstream_client_oh_fingerprint(); Result auto_decompress_gzip(); /// Send this request synchronously, and wait for the response. Result send(HttpBody body, std::string_view backend); /// Send this request asynchronously. Result send_async(HttpBody body, std::string_view backend); /// Send this request asynchronously, and allow sending additional data through the body. Result send_async_streaming(HttpBody body, std::string_view backend); /// Send this request asynchronously without any caching. Result send_async_without_caching(HttpBody body, std::string_view backend, bool streaming = false); /// Send this request synchronously to the Image Optimizer and wait for the response. api::FastlyResult send_image_optimizer(HttpBody body, std::string_view backend, std::string_view config_str); /// Get the http version used for this request. /// Set the request method. Result set_method(std::string_view method); /// Get the request method. Result get_method() const; /// Set the request uri. Result set_uri(std::string_view str); /// Get the request uri. Result get_uri() const; /// Configure cache-override settings. Result cache_override(CacheOverrideTag tag, std::optional ttl, std::optional stale_while_revalidate, std::optional surrogate_key); /// Set the framing headers mode for this request. Result set_framing_headers_mode(FramingHeadersMode mode); bool is_valid() const override; Result get_version() const override; HttpHeadersReadOnly *headers() override; HttpHeaders *headers_writable() override; /// Check if request is cacheable Result is_cacheable() const; /// Get suggested cache key Result get_suggested_cache_key() const; }; class HttpResp final : public HttpBase { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; HttpResp() = default; explicit HttpResp(Handle handle) : handle{handle} {} static Result make(); /// Get the http status for the response. Result get_status() const; /// Set the http status for the response. Result set_status(uint16_t status); /// Immediately begin sending this response to the downstream client. Result send_downstream(HttpBody body, bool streaming); /// Set the framing headers mode for this response. Result set_framing_headers_mode(FramingHeadersMode mode); bool is_valid() const override; Result get_version() const override; /// Get the IP address associated with the response Result> get_ip() const; /// Get the port associated with the response Result> get_port() const; HttpHeadersReadOnly *headers() override; HttpHeaders *headers_writable() override; }; /// The pair of a response and its body. struct Response { HttpResp resp; HttpBody body; Response() = default; Response(HttpResp resp, HttpBody body) : resp{resp}, body{body} {} }; /// The pair of a request and its body. struct Request { HttpReq req; HttpBody body; Request() = default; Request(HttpReq req, HttpBody body) : req{req}, body{body} {} /// Fetch the downstream request/body pair static Result downstream_get(); Result inspect(const InspectOptions *config); }; class HttpReqPromise final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; HttpReqPromise() = default; explicit HttpReqPromise(Handle handle) : handle{handle} {} struct DownstreamNextOptions final { std::optional timeout_ms; }; static Result downstream_next(DownstreamNextOptions options); Result wait(); Result abandon(); }; class GeoIp final { ~GeoIp() = delete; public: /// Lookup information about the ip address provided. static Result> lookup(std::span bytes); }; struct HttpCacheLookupOptions { const char *override_key_ptr; size_t override_key_len; }; struct HttpCacheWriteOptions final { // Required max age of the response before considered stale // (This is only optional when used for overrides) std::optional max_age_ns; // Optional vary rule - header names separated by spaces std::optional vary_rule; // Optional initial age of the response in nanoseconds std::optional initial_age_ns; // Optional stale-while-revalidate duration in nanoseconds std::optional stale_while_revalidate_ns; // Optional surrogate keys separated by spaces std::optional> surrogate_keys; // Optional length of the response body std::optional length; // Optional flag indicating if this contains sensitive data std::optional sensitive_data; }; struct CacheState final { uint8_t state = 0; CacheState() = default; CacheState(uint8_t state) : state{state} {} bool is_found() const; bool is_usable() const; bool is_stale() const; bool must_insert_or_update() const; }; enum class HttpStorageAction : uint8_t { Insert = 0, Update = 1, DoNotStore = 2, RecordUncacheable = 3 }; class HttpCacheEntry final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; HttpCacheEntry() = default; explicit HttpCacheEntry(Handle handle) : handle{handle} {} bool is_valid() const { return handle != invalid; } /// Lookup a cached object, participating in request collapsing static Result transaction_lookup(const HttpReq &req, std::span override_key = {}); /// Insert a response into cache Result transaction_insert(const HttpResp &resp, const HttpCacheWriteOptions *opts); /// Insert a response and get back a stream Result> transaction_insert_and_stream_back(const HttpResp &resp, const HttpCacheWriteOptions *opts); /// Update a response's headers and metadata without changing body Result transaction_update(const HttpResp &resp, const HttpCacheWriteOptions *opts); /// Update response and get back a fresh handle Result transaction_update_and_return_fresh(const HttpResp &resp, const HttpCacheWriteOptions *opts); /// Record that this entry should not be cached Result transaction_record_not_cacheable(uint64_t max_age_ns, std::optional vary_rule = std::nullopt); /// Abandon the transaction Result transaction_abandon(); /// Close the cache entry Result close(); /// Get suggested backend request Result get_suggested_backend_request() const; /// Get suggested cache options Result get_suggested_cache_options(const HttpResp &resp) const; /// Prepare response for storage Result> prepare_response_for_storage(HttpResp resp) const; /// Get found response Result> get_found_response(bool transform_for_client = true) const; /// Get cache entry state Result get_state() const; /// Get content length Result> get_length() const; /// Get max age in nanoseconds Result get_max_age_ns() const; /// Get stale while revalidate time in nanoseconds Result get_stale_while_revalidate_ns() const; /// Get age in nanoseconds Result get_age_ns() const; /// Get hit count Result get_hits() const; /// Check if contains sensitive data Result get_sensitive_data() const; /// Get surrogate keys Result> get_surrogate_keys() const; /// Get vary rule Result> get_vary_rule() const; }; class LogEndpoint final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; LogEndpoint() = default; explicit LogEndpoint(Handle handle) : handle{handle} {} static Result get(std::string_view name); Result write(std::string_view msg); }; class Dict final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; Dict() = default; explicit Dict(Handle handle) : handle{handle} {} static Result open(std::string_view name); Result> get(std::string_view name); }; class ConfigStore final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; ConfigStore() = default; explicit ConfigStore(Handle handle) : handle{handle} {} static Result open(std::string_view name); Result> get(std::string_view name); Result> get(std::string_view name, uint32_t initial_buf_len); }; class ObjectStorePendingLookup final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; ObjectStorePendingLookup() = default; explicit ObjectStorePendingLookup(Handle handle) : handle{handle} {} explicit ObjectStorePendingLookup(FastlyAsyncTask async) : handle{async.handle()} {} /// Block until the response is ready. api::FastlyResult, fastly::FastlyAPIError> wait(); /// Fetch the handle for this pending request. FastlyAsyncTask::Handle async_handle() const; }; class ObjectStorePendingDelete final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; ObjectStorePendingDelete() = default; explicit ObjectStorePendingDelete(Handle handle) : handle{handle} {} explicit ObjectStorePendingDelete(FastlyAsyncTask async) : handle{async.handle()} {} /// Block until the response is ready. Result wait(); /// Fetch the handle for this pending request. FastlyAsyncTask::Handle async_handle() const; }; class ObjectStore final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; ObjectStore() = default; explicit ObjectStore(Handle handle) : handle{handle} {} static Result open(std::string_view name); Result> lookup(std::string_view name); Result lookup_async(std::string_view name); Result delete_async(std::string_view name); Result insert(std::string_view name, HttpBody body); }; class Secret final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; Secret() = default; explicit Secret(Handle handle) : handle{handle} {} Result> plaintext() const; Result> plaintext(uint32_t initial_buf_len) const; }; class SecretStore final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; SecretStore() = default; explicit SecretStore(Handle handle) : handle{handle} {} static Result open(std::string_view name); Result> get(std::string_view name); static Result from_bytes(const uint8_t *bytes, size_t len); }; struct CacheLookupOptions final { /// A full request handle, used only for its headers. HttpReq request_headers; }; struct CacheGetBodyOptions final { std::optional start; std::optional end; }; struct CacheWriteOptions final { uint64_t max_age_ns = 0; HttpReq request_headers; std::string vary_rule; uint64_t initial_age_ns = 0; uint64_t stale_while_revalidate_ns = 0; std::string surrogate_keys; uint64_t length = 0; HostBytes metadata; bool sensitive = false; }; class CacheHandle final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; CacheHandle() = default; explicit CacheHandle(Handle handle) : handle{handle} {} /// Lookup a cached object. static Result lookup(std::string_view key, const CacheLookupOptions &opts); static Result transaction_lookup(std::string_view key, const CacheLookupOptions &opts); /// Insert a cache object. static Result insert(std::string_view key, const CacheWriteOptions &opts); Result transaction_insert(const CacheWriteOptions &opts); Result transaction_update(const CacheWriteOptions &opts); /// Insert this cached object and stream it back. Result> transaction_insert_and_stream_back(const CacheWriteOptions &opts); bool is_valid() const { return this->handle != invalid; } /// Cancel a transaction. Result transaction_cancel(); /// Fetch the body handle for the cached data. Result get_body(const CacheGetBodyOptions &opts); /// Fetch the state for this cache handle. Result get_state(); Result close(); Result get_user_metadata(); Result get_length(); Result get_max_age_ns(); Result get_stale_while_revalidate_ns(); Result get_age_ns(); Result get_hits(); }; struct BackendHealth final { public: uint8_t state = 0; BackendHealth() = default; BackendHealth(uint8_t state) : state{state} {} bool is_unknown() const; bool is_healthy() const; bool is_unhealthy() const; }; class Backend final { HostString name_; public: Backend() = default; explicit Backend(const std::string_view &name) : name_{name} {} explicit Backend(HostString name) : name_{std::move(name)} {} const HostString &name() const { return name_; }; Result health() const; Result is_dynamic() const; Result get_host() const; Result get_override_host() const; Result get_port() const; Result> get_connect_timeout_ms() const; Result> get_first_byte_timeout_ms() const; Result> get_between_bytes_timeout_ms() const; Result get_http_keepalive_time() const; Result get_tcp_keepalive_enable() const; Result get_tcp_keepalive_interval() const; Result get_tcp_keepalive_probes() const; Result get_tcp_keepalive_time() const; Result is_ssl() const; Result> ssl_min_version() const; Result> ssl_max_version() const; public: static Result exists(std::string_view name); }; class PenaltyBox final { public: static Result add(std::string_view name, std::string_view entry, uint32_t time_to_live); static Result has(std::string_view name, std::string_view entry); }; class RateCounter final { public: static Result increment(std::string_view name, std::string_view entry, uint32_t delta); static Result lookup_rate(std::string_view name, std::string_view entry, uint32_t window); static Result lookup_count(std::string_view name, std::string_view entry, uint32_t duration); }; class EdgeRateLimiter final { public: static Result check_rate(std::string_view rate_counter_name, std::string_view entry, uint32_t delta, uint32_t window, uint32_t limit, std::string_view penalty_box_name, uint32_t time_to_live); }; class DeviceDetection final { public: static Result lookup(std::string_view user_agent); }; class KVStorePendingLookup final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; KVStorePendingLookup() = default; explicit KVStorePendingLookup(Handle handle) : handle{handle} {} explicit KVStorePendingLookup(FastlyAsyncTask async) : handle{async.handle()} {} /// Block until the response is ready. api::FastlyResult>, FastlyKVError> wait(); /// Fetch the handle for this pending request. FastlyAsyncTask::Handle async_handle() const; }; class KVStorePendingInsert final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; KVStorePendingInsert() = default; explicit KVStorePendingInsert(Handle handle) : handle{handle} {} explicit KVStorePendingInsert(FastlyAsyncTask async) : handle{async.handle()} {} /// Block until the response is ready. api::FastlyResult wait(); /// Fetch the handle for this pending request. FastlyAsyncTask::Handle async_handle() const; }; class KVStorePendingDelete final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; KVStorePendingDelete() = default; explicit KVStorePendingDelete(Handle handle) : handle{handle} {} explicit KVStorePendingDelete(FastlyAsyncTask async) : handle{async.handle()} {} /// Block until the response is ready. api::FastlyResult wait(); /// Fetch the handle for this pending request. FastlyAsyncTask::Handle async_handle() const; }; class KVStorePendingList final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; KVStorePendingList() = default; explicit KVStorePendingList(Handle handle) : handle{handle} {} explicit KVStorePendingList(FastlyAsyncTask async) : handle{async.handle()} {} /// Block until the response is ready. api::FastlyResult wait(); /// Fetch the handle for this pending request. FastlyAsyncTask::Handle async_handle() const; }; class KVStore final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; Handle handle = invalid; KVStore() = default; explicit KVStore(Handle handle) : handle{handle} {} static Result open(std::string_view name); enum InsertMode : uint32_t { overwrite, add, append, prepend, }; Result lookup(std::string_view key); Result insert(std::string_view key, HttpBody body, std::optional mode, std::optional if_generation_match, std::optional> metadata, std::optional ttl); Result delete_(std::string_view key); // cursor is base64 encoding of the last key Result list(std::optional cursor, std::optional limit, std::optional prefix, bool eventual); }; class Acl final { public: using Handle = uint32_t; static constexpr Handle invalid = UINT32_MAX - 1; // Acl error type enum class LookupError : uint32_t { Uninitialized = FASTLY_ACL_ERROR_UNINITIALIZED, Ok = FASTLY_ACL_ERROR_OK, NoContent = FASTLY_ACL_ERROR_NO_CONTENT, TooManyRequests = FASTLY_ACL_ERROR_TOO_MANY_REQUESTS }; Handle handle = invalid; Acl() = default; explicit Acl(Handle handle) : handle{handle} {} bool is_valid() const { return handle != invalid; } static Result> open(std::string_view name); /// Lookup an IP address in the ACL Result, LookupError>> lookup(std::span ip_octets) const; }; class Compute final { public: static Result get_vcpu_ms(); /// Purge the given surrogate key. static Result> purge_surrogate_key(std::string_view key, bool soft); }; void handle_api_error(JSContext *cx, uint8_t err, int line, const char *func); void handle_kv_error(JSContext *cx, host_api::FastlyKVError err, const unsigned int err_type, int line, const char *func); void handle_image_optimizer_error(JSContext *cx, const host_api::FastlyImageOptimizerError &err, int line, const char *func); bool error_is_generic(APIError e); bool error_is_invalid_argument(APIError e); bool error_is_optional_none(APIError e); bool error_is_bad_handle(APIError e); bool error_is_unsupported(APIError e); bool error_is_buffer_len(APIError e); bool error_is_limit_exceeded(APIError e); void handle_fastly_error(JSContext *cx, APIError err, int line, const char *func); } // namespace host_api #endif ================================================ FILE: runtime/fastly/host-api/host_call.cpp ================================================ #include #include "./fastly.h" #include "./host_api_fastly.h" using api::AsyncTask; namespace fastly { const JSErrorFormatString *FastlyGetErrorMessage(void *userRef, unsigned errorNumber) { if (errorNumber > 0 && errorNumber < JSErrNum_Limit) { return &fastly_ErrorFormatString[errorNumber]; } return nullptr; } } // namespace fastly namespace host_api { static_assert(std::is_same_v); bool error_is_generic(APIError e) { return e == FASTLY_HOST_ERROR_GENERIC_ERROR; } bool error_is_invalid_argument(APIError e) { return e == FASTLY_HOST_ERROR_INVALID_ARGUMENT; } bool error_is_optional_none(APIError e) { return e == FASTLY_HOST_ERROR_OPTIONAL_NONE; } bool error_is_bad_handle(APIError e) { return e == FASTLY_HOST_ERROR_BAD_HANDLE; } bool error_is_unsupported(APIError e) { return e == FASTLY_HOST_ERROR_UNSUPPORTED; } bool error_is_buffer_len(APIError e) { return e == FASTLY_HOST_ERROR_BUFFER_LEN; } bool error_is_limit_exceeded(APIError e) { return e == FASTLY_HOST_ERROR_LIMIT_EXCEEDED; } void handle_kv_error(JSContext *cx, FastlyKVError err, const unsigned int err_type, int line, const char *func) { // kv error was a host call error -> report as host error if (err.detail == FastlyKVError::detail::host_error) { return handle_api_error(cx, err.host_error, line, func); } // kv error is a normal kv error -> report as KV error std::string message = std::move(err.message()).value_or("when attempting to fetch resource."); JS_ReportErrorNumberASCII(cx, fastly::FastlyGetErrorMessage, nullptr, err_type, message.c_str()); } void handle_image_optimizer_error(JSContext *cx, const FastlyImageOptimizerError &err, int line, const char *func) { if (err.is_host_error) { return handle_api_error(cx, err.host_err, line, func); } std::string message = err.message().value(); JS_ReportErrorUTF8(cx, "[Image Optimizer] %s", message.c_str()); } /* Returns false if an exception is set on `cx` and the caller should immediately return to propagate the exception. */ void handle_api_error(JSContext *cx, APIError err, int line, const char *func) { switch (err) { case FASTLY_HOST_ERROR_GENERIC_ERROR: JS_ReportErrorUTF8(cx, "%s: Generic error value. This means that some unexpected error " "occurred during a hostcall.\n", func); break; case FASTLY_HOST_ERROR_INVALID_ARGUMENT: JS_ReportErrorUTF8(cx, "%s: Invalid argument.\n", func); break; case FASTLY_HOST_ERROR_BAD_HANDLE: JS_ReportErrorUTF8(cx, "%s: Invalid handle. Thrown when a request, response, dictionary, or " "body handle is not valid.\n", func); break; case FASTLY_HOST_ERROR_BUFFER_LEN: JS_ReportErrorUTF8(cx, "%s: Buffer length error. Buffer is too long.\n", func); break; case FASTLY_HOST_ERROR_UNSUPPORTED: JS_ReportErrorUTF8(cx, "%s: Unsupported operation error. This error is thrown " "when some operation cannot be performed, because it is " "not supported.\n", func); break; case FASTLY_HOST_ERROR_BAD_ALIGN: JS_ReportErrorUTF8(cx, "%s: Alignment error. This is thrown when a pointer does not point to " "a properly aligned slice of memory.\n", func); break; case FASTLY_HOST_ERROR_HTTP_INVALID: JS_ReportErrorUTF8(cx, "%s: HTTP parse error. This can be thrown when a method, URI, header, " "or status is not valid. This can also be thrown if a message head is " "too large.\n", func); break; case FASTLY_HOST_ERROR_HTTP_USER: JS_ReportErrorUTF8(cx, "%s: HTTP user error. This is thrown in cases where user code caused " "an HTTP error. For example, attempt to send a 1xx response code, or a " "request with a non-absolute URI. This can also be caused by an " "unexpected header: both `content-length` and `transfer-encoding`, for " "example.\n", func); break; case FASTLY_HOST_ERROR_HTTP_INCOMPLETE: JS_ReportErrorUTF8(cx, "%s: HTTP incomplete message error. A stream ended " "unexpectedly.\n", func); break; case FASTLY_HOST_ERROR_OPTIONAL_NONE: JS_ReportErrorUTF8(cx, "%s: A `None` error. This status code is used to " "indicate when an optional value did not exist, as " "opposed to an empty value.\n", func); break; case FASTLY_HOST_ERROR_HTTP_HEAD_TOO_LARGE: JS_ReportErrorUTF8(cx, "%s: HTTP head too large error. This error will be thrown when the " "message head is too large.\n", func); break; case FASTLY_HOST_ERROR_HTTP_INVALID_STATUS: JS_ReportErrorUTF8(cx, "%s: HTTP invalid status error. This error will be " "thrown when the HTTP message contains an invalid " "status code.\n", func); break; case FASTLY_HOST_ERROR_LIMIT_EXCEEDED: JS_ReportErrorUTF8(cx, "%s: Limit exceeded error. This error will be thrown when an attempt " "to allocate a resource has exceeded the maximum number of resources " "permitted. For example, creating too many response handles.\n", func); break; default: fprintf(stdout, __FILE__ ":%d (%s)\n", line, func); JS_ReportErrorUTF8(cx, "Fastly error code %d", err); } } } // namespace host_api ================================================ FILE: runtime/fastly/patches/starlingmonkey-builtin-trace-finalize.patch ================================================ diff --git a/builtins/web/event/event-target.cpp b/builtins/web/event/event-target.cpp index 610708a..be7e45e 100644 --- a/builtins/web/event/event-target.cpp +++ b/builtins/web/event/event-target.cpp @@ -537,6 +537,13 @@ void EventTarget::finalize(JS::GCContext *gcx, JSObject *self) { void EventTarget::trace(JSTracer *trc, JSObject *self) { MOZ_ASSERT(is_instance(self)); + + const JS::Value val = JS::GetReservedSlot(self, static_cast(Slots::Listeners)); + if (val.isNullOrUndefined()) { + // Nothing to trace + return; + } + auto list = listeners(self); list->trace(trc); } diff --git a/builtins/web/form-data/form-data.cpp b/builtins/web/form-data/form-data.cpp index d6f4892..4c59df2 100644 --- a/builtins/web/form-data/form-data.cpp +++ b/builtins/web/form-data/form-data.cpp @@ -447,6 +447,13 @@ void FormData::finalize(JS::GCContext *gcx, JSObject *self) { void FormData::trace(JSTracer *trc, JSObject *self) { MOZ_ASSERT(is_instance(self)); + + const JS::Value val = JS::GetReservedSlot(self, static_cast(Slots::Entries)); + if (val.isNullOrUndefined()) { + // Nothing to trace + return; + } + auto entries = entry_list(self); entries->trace(trc); } diff --git a/builtins/web/url.cpp b/builtins/web/url.cpp index 6f716b6..402c8c0 100644 --- a/builtins/web/url.cpp +++ b/builtins/web/url.cpp @@ -726,8 +726,12 @@ JSObject *URL::create(JSContext *cx, JS::HandleObject self, JS::HandleValue url_ } void URL::finalize(JS::GCContext *gcx, JSObject *self) { + auto url_val = JS::GetReservedSlot(self, Slots::Url); + if (url_val.isUndefined()) + return; + jsurl::JSUrl *url = - static_cast(JS::GetReservedSlot(self, Slots::Url).toPrivate()); + static_cast(url_val.toPrivate()); jsurl::free_jsurl(url); } diff --git a/include/builtin.h b/include/builtin.h index ac04a2e..bf7719c 100644 --- a/include/builtin.h +++ b/include/builtin.h @@ -177,17 +177,20 @@ inline bool ThrowIfNotConstructing(JSContext *cx, const CallArgs &args, const ch namespace builtins { template class BuiltinImpl { - static constexpr JSClassOps class_ops{}; - static constexpr uint32_t class_flags = 0; - // A runtime registry for subclass JSClass pointers. static inline std::vector registry; public: + // Default class ops and flags. TraceableBuiltinImpl and FinalizableBuiltinImpl shadow these + // with versions that wire up finalize/trace. BuiltinImpl::class_ uses Impl:: lookup so that + // the most-derived definition in the inheritance chain is picked up. + static constexpr JSClassOps class_ops{}; + static constexpr uint32_t class_flags = 0; + static constexpr JSClass class_{ Impl::class_name, - JSCLASS_HAS_RESERVED_SLOTS(static_cast(Impl::Slots::Count)) | class_flags, - &class_ops, + JSCLASS_HAS_RESERVED_SLOTS(static_cast(Impl::Slots::Count)) | Impl::class_flags, + &Impl::class_ops, }; static JS::Result> @@ -246,6 +249,7 @@ public: }; template class FinalizableBuiltinImpl : public BuiltinImpl { +public: static constexpr JSClassOps class_ops{ nullptr, // addProperty nullptr, // delProperty @@ -262,6 +266,7 @@ template class FinalizableBuiltinImpl : public BuiltinImpl }; template class TraceableBuiltinImpl : public BuiltinImpl { +public: static constexpr JSClassOps class_ops{ nullptr, // addProperty nullptr, // delProperty ================================================ FILE: runtime/fastly/patches/starlingmonkey-reset.patch ================================================ diff --git a/include/extension-api.h b/include/extension-api.h index 44935f7..79f13e5 100644 --- a/include/extension-api.h +++ b/include/extension-api.h @@ -163,6 +163,7 @@ public: void report_unhandled_promise_rejections(); void clear_unhandled_promise_rejections(); + void reset(); void abort(const char *reason); bool debug_logging_enabled(); diff --git a/runtime/engine.cpp b/runtime/engine.cpp index e748f93..1b3280d 100644 --- a/runtime/engine.cpp +++ b/runtime/engine.cpp @@ -689,3 +689,9 @@ void Engine::report_unhandled_promise_rejections() { void Engine::clear_unhandled_promise_rejections() { JS::SetClear(CONTEXT, unhandledRejectedPromises); } +void Engine::reset() { + clear_unhandled_promise_rejections(); + core::EventLoop::reset(this); + JS::PrepareForFullGC(cx()); + JS::NonIncrementalGC(cx(), JS::GCOptions::Normal, JS::GCReason::API); +} diff --git a/runtime/event_loop.cpp b/runtime/event_loop.cpp index eb4909b..2412813 100644 --- a/runtime/event_loop.cpp +++ b/runtime/event_loop.cpp @@ -98,4 +98,13 @@ bool EventLoop::run_event_loop(api::Engine *engine, double total_compute) { void EventLoop::init(JSContext *cx) { queue.init(cx); } +void EventLoop::reset(api::Engine *engine) { + auto &q = queue.get(); + for (auto *task : q.tasks) { + task->cancel(engine); + } + q.tasks.clear(); + q.interest_cnt = 0; +} + } // namespace core diff --git a/runtime/event_loop.h b/runtime/event_loop.h index 40b3696..5bf1ea3 100644 --- a/runtime/event_loop.h +++ b/runtime/event_loop.h @@ -47,6 +47,12 @@ public: * Remove a queued async task. */ static bool cancel_async_task(api::Engine *engine, api::AsyncTask *task); + + /** + * Reset the event loop state, cancelling all pending tasks and clearing interest count. + * Used between requests in reusable sandboxes. + */ + static void reset(api::Engine *engine); }; } // namespace core ================================================ FILE: runtime/rust-toolchain.toml ================================================ [toolchain] channel = "1.81.0" targets = ["wasm32-wasip1"] profile = "minimal" ================================================ FILE: src/addSdkMetadataField.ts ================================================ import { metadataAdd } from '@bytecodealliance/jco'; import { readFile, writeFile } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; const __dirname = dirname(fileURLToPath(import.meta.url)); export async function addSdkMetadataField(wasmPath: string, usingAOT: boolean) { const packageJson = await readFile(join(__dirname, '../package.json'), { encoding: 'utf-8', }); const { name, version } = JSON.parse(packageJson) as { name: string; version: string; }; let sdkName: string; if (usingAOT) { sdkName = name + ' (StarlingMonkey with Weval)'; } else { sdkName = name + ' (StarlingMonkey)'; } const metadata = [['sdk', [[sdkName, version]]]]; const wasm = await readFile(wasmPath); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const newWasm: Uint8Array = await metadataAdd(wasm, metadata); await writeFile(wasmPath, newWasm); } ================================================ FILE: src/cli/js-compute-runtime-cli.ts ================================================ #!/usr/bin/env node import { parseInputs } from '../parseInputs.js'; import { printHelp, printVersion } from '../printHelp.js'; import { addSdkMetadataField } from '../addSdkMetadataField.js'; import { readConfigFileAndCliArguments } from '../config.js'; const argv = await readConfigFileAndCliArguments(process.argv.slice(2)); const parsedInputs = await parseInputs(argv); if (parsedInputs === 'version') { await printVersion(); } else if (parsedInputs === 'help') { await printHelp(); } else { const { enableAOT, aotCache, enableHttpCache, enableExperimentalHighResolutionTimeMethods, moduleMode, bundle, enableStackTraces, excludeSources, debugIntermediateFilesDir, wasmEngine, wevalBin, input, output, env, } = parsedInputs; // This is a dynamic import because this import will throw an error // if it does not have a pre-compiled version of Wizer available in the platform // running the CLI. In that situation, we would still like the // js-compute-runtime cli's --version and --help flags to work as // it could be that the user is using an older version of js-compute-runtime // and a newer version does not support the platform they are using. const { compileApplicationToWasm } = await import( '../compileApplicationToWasm.js' ); await compileApplicationToWasm({ input, output, wasmEngine, enableHttpCache, enableExperimentalHighResolutionTimeMethods, enableAOT, aotCache, enableStackTraces, excludeSources, debugIntermediateFilesDir, wevalBin, moduleMode, doBundle: bundle, env, }); await addSdkMetadataField(output, enableAOT); } ================================================ FILE: src/compileApplicationToWasm.ts ================================================ import { dirname, sep, normalize } from 'node:path'; import { tmpdir, freemem } from 'node:os'; import { spawnSync, type SpawnSyncOptionsWithStringEncoding, } from 'node:child_process'; import { mkdir, readFile, mkdtemp } from 'node:fs/promises'; import { rmSync } from 'node:fs'; import weval from '@bytecodealliance/weval'; import wizer from '@bytecodealliance/wizer'; import { isDirectory, isFile } from './files.js'; import { CompilerContext } from './compilerPipeline.js'; import { bundleStep } from './compiler-steps/bundle.js'; import { precompileRegexesStep } from './compiler-steps/precompileRegexes.js'; import { addStackMappingHelpersStep } from './compiler-steps/addStackMappingHelpers.js'; import { addFastlyHelpersStep } from './compiler-steps/addFastlyHelpers.js'; import { composeSourcemapsStep } from './compiler-steps/composeSourcemaps.js'; const maybeWindowsPath = process.platform === 'win32' ? (path: string) => { return '//?/' + path.replace(/\\/g, '/'); } : (path: string) => path; async function getTmpDir() { return await mkdtemp(normalize(tmpdir() + sep)); } export type CompileApplicationToWasmParams = { input: string; output: string; wasmEngine: string; enableHttpCache: boolean; enableExperimentalHighResolutionTimeMethods: boolean; enableAOT: boolean; aotCache: string; enableStackTraces: boolean; excludeSources: boolean; debugIntermediateFilesDir: string | undefined; wevalBin: string | undefined; moduleMode: boolean; doBundle: boolean; env: Record; }; export async function compileApplicationToWasm( params: CompileApplicationToWasmParams, ) { const { output, wasmEngine, enableHttpCache = false, enableExperimentalHighResolutionTimeMethods = false, enableAOT = false, aotCache = '', enableStackTraces, excludeSources, debugIntermediateFilesDir, wevalBin, moduleMode = false, doBundle = false, env, } = params; let input = params.input; try { if (!(await isFile(input))) { console.error( `Error: The \`input\` path does not point to a file: ${input}`, ); process.exit(1); } } catch { console.error( `Error: The \`input\` path points to a non-existent file: ${input}`, ); process.exit(1); } try { await readFile(input, { encoding: 'utf-8' }); } catch (maybeError: unknown) { const error = maybeError instanceof Error ? maybeError : new Error(String(maybeError)); console.error( `Error: Failed to open the \`input\` (${input})`, error.message, ); process.exit(1); } try { if (!(await isFile(wasmEngine))) { console.error( `Error: The \`wasmEngine\` path does not point to a file: ${wasmEngine}`, ); process.exit(1); } } catch { console.error( `Error: The \`wasmEngine\` path points to a non-existent file: ${wasmEngine}`, ); process.exit(1); } // If output exists already, make sure it's not a directory // (we'll try to overwrite it if it's a file) try { if (await isDirectory(output)) { console.error( `Error: The \`output\` path points to a directory: ${output}`, ); process.exit(1); } } catch { // Output doesn't exist } try { await mkdir(dirname(output), { recursive: true, }); } catch (maybeError: unknown) { const error = maybeError instanceof Error ? maybeError : new Error(String(maybeError)); console.error( `Error: Failed to create the \`output\` (${dirname(output)}) directory: ${output}`, error.message, ); process.exit(1); } if (debugIntermediateFilesDir != null) { try { console.log( `Preparing \`debug-intermediate-files\` directory: ${debugIntermediateFilesDir}`, ); await mkdir(debugIntermediateFilesDir, { recursive: true, }); } catch (maybeError: unknown) { const error = maybeError instanceof Error ? maybeError : new Error(String(maybeError)); console.error( `Error: Failed to create the \`debug-intermediate-files\` (${debugIntermediateFilesDir}) directory`, error.message, ); process.exit(1); } } const tmpDir = await getTmpDir(); try { if (doBundle) { const ctx = new CompilerContext( input, tmpDir, debugIntermediateFilesDir, moduleMode, enableStackTraces, excludeSources, ); // bundle input -> apply esbuild (bundle package imports, apply Fastly Plugin) ctx.addCompilerPipelineStep(bundleStep); // precompile regexes ctx.addCompilerPipelineStep(precompileRegexesStep); // add stack mapping helpers if (enableStackTraces) { ctx.addCompilerPipelineStep(addStackMappingHelpersStep); } // add Fastly helpers ctx.addCompilerPipelineStep(addFastlyHelpersStep); // compile sourcemaps up to this point and inject into bundle if (enableStackTraces) { ctx.addCompilerPipelineStep(composeSourcemapsStep); } await ctx.applyCompilerPipeline(); await ctx.maybeWriteDebugIntermediateFile('fastly_bundle.js'); // the output of the pipeline is the Wizer/Weval input input = ctx.outFilepath; } const spawnOpts = { stdio: [null, process.stdout, process.stderr], input: maybeWindowsPath(input), shell: true, encoding: 'utf-8', env: { ...env, ENABLE_EXPERIMENTAL_HIGH_RESOLUTION_TIME_METHODS: enableExperimentalHighResolutionTimeMethods ? '1' : '0', ENABLE_EXPERIMENTAL_HTTP_CACHE: enableHttpCache ? '1' : '0', RUST_MIN_STACK: String( Math.max(8 * 1024 * 1024, Math.floor(freemem() * 0.1)), ), }, } satisfies SpawnSyncOptionsWithStringEncoding; try { if (!doBundle) { if (enableAOT) { const wevalPath = wevalBin ?? (await weval()); const wevalProcess = spawnSync( `"${wevalPath}"`, [ 'weval', '-v', ...(aotCache ? [`--cache-ro ${aotCache}`] : []), `--dir="${maybeWindowsPath(process.cwd())}"`, '-w', `-i "${wasmEngine}"`, `-o "${output}"`, ], spawnOpts, ); if (wevalProcess.status !== 0) { throw new Error(`Weval initialization failure`); } process.exitCode = wevalProcess.status; } else { const wizerProcess = spawnSync( `"${wizer}"`, [ '--allow-wasi', `--wasm-bulk-memory=true`, `--dir="${maybeWindowsPath(process.cwd())}"`, '--inherit-env=true', '-r _start=wizer.resume', `-o="${output}"`, `"${wasmEngine}"`, ], spawnOpts, ); if (wizerProcess.status !== 0) { throw new Error(`Wizer initialization failure`); } process.exitCode = wizerProcess.status; } } else { spawnOpts.input = `${maybeWindowsPath(input)}${moduleMode ? '' : ' --legacy-script'}`; if (enableAOT) { const wevalPath = wevalBin ?? (await weval()); const wevalProcess = spawnSync( `"${wevalPath}"`, [ 'weval', '-v', ...(aotCache ? [`--cache-ro ${aotCache}`] : []), '--dir .', `--dir ${maybeWindowsPath(dirname(input))}`, '-w', `-i "${wasmEngine}"`, `-o "${output}"`, ], spawnOpts, ); if (wevalProcess.status !== 0) { throw new Error(`Weval initialization failure`); } process.exitCode = wevalProcess.status; } else { const wizerProcess = spawnSync( `"${wizer}"`, [ '--inherit-env=true', '--allow-wasi', '--dir=.', `--dir=${maybeWindowsPath(dirname(input))}`, '-r _start=wizer.resume', `--wasm-bulk-memory=true`, `-o="${output}"`, `"${wasmEngine}"`, ], spawnOpts, ); if (wizerProcess.status !== 0) { throw new Error(`Wizer initialization failure`); } process.exitCode = wizerProcess.status; } } } catch (maybeError: unknown) { const error = maybeError instanceof Error ? maybeError : new Error(String(maybeError)); throw new Error( `Error: Failed to compile JavaScript to Wasm:\n${error.message}`, ); } } finally { rmSync(tmpDir, { recursive: true }); } } ================================================ FILE: src/compiler-steps/addFastlyHelpers.ts ================================================ import { CompilerPipelineStep } from '../compilerPipeline.js'; // Compiler Step - Add Fastly Helpers // This step usually runs last before composing sourcemaps. export const addFastlyHelpersStep: CompilerPipelineStep = { outFilename: '__fastly_helpers.js', async fn(ctx, index) { await ctx.magicStringWriter(this.outFilename, async (magicString) => { // MISC HEADER const SOURCE_FILE_NAME = 'fastly:app.js'; const STACK_MAPPING_HEADER = `\ //# sourceURL=${SOURCE_FILE_NAME} globalThis.__FASTLY_GEN_FILE = "${SOURCE_FILE_NAME}"; globalThis.__orig_console_error = console.error.bind(console); globalThis.__fastlyMapAndLogError = (e) => { for (const line of globalThis.__fastlyMapError(e)) { globalThis.__orig_console_error(line); } }; globalThis.__fastlyMapError = (e) => { return [ '(Raw error) - build with --enable-stack-traces for mapped stack information.', e, ]; }; `; magicString.prepend(STACK_MAPPING_HEADER); }); await ctx.maybeWriteDebugIntermediateFiles( `__${index + 1}_fastly_helpers.js`, ); }, }; ================================================ FILE: src/compiler-steps/addStackMappingHelpers.ts ================================================ import { CompilerPipelineStep } from '../compilerPipeline.js'; // Compiler Step - Add Stack Mapping Helpers // This step runs only when stack tracing is enabled, and // any time after bundling export const addStackMappingHelpersStep: CompilerPipelineStep = { outFilename: '__stack_mapping_helpers.js', async fn(ctx, index) { await ctx.magicStringWriter(this.outFilename, async (magicString) => { // INSERT init guard let initGuardPre, initGuardPost; if (ctx.moduleMode) { initGuardPre = `\ await(async function __fastly_init_guard__() { `; initGuardPost = `\ })().catch(e => { console.error('Unhandled error while running top level module code'); try { globalThis.__fastlyMapAndLogError(e); } catch { /* swallow */ } console.error('Raw error below:'); throw e; }); `; } else { initGuardPre = `\ (function __fastly_init_guard__() { try { `; initGuardPost = `\ } catch (e) { console.error('Unhandled error while running top level script'); try { globalThis.__fastlyMapAndLogError(e); } catch { /* swallow */ } console.error('Raw error below:'); throw e; } })(); `; } magicString.prepend(initGuardPre); magicString.append(initGuardPost); // SOURCE MAPPING HEADER const STACK_MAPPING_HEADER = `\ globalThis.__FASTLY_SOURCE_MAP = JSON.parse(__FINAL_SOURCE_MAP__); `; magicString.prepend(STACK_MAPPING_HEADER); }); await ctx.maybeWriteDebugIntermediateFiles( `__${index + 1}_stack_mapping_helpers.js`, ); }, }; ================================================ FILE: src/compiler-steps/bundle.ts ================================================ import { dirname, basename, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { build } from 'esbuild'; import { moveFile } from '../files.js'; import { CompilerPipelineStep } from '../compilerPipeline.js'; import { fastlyPlugin } from '../esbuild-plugins/fastlyPlugin.js'; import { swallowTopLevelExportsPlugin } from '../esbuild-plugins/swallowTopLevelExportsPlugin.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); // Compiler Step - bundle // This step usually runs first. // Runs esbuild: // - bundles imported modules // - applies the Fastly plugin, which resolves fastly:* imports // - applies the Top level exports plugin, allowing top level file to contain any exports. // - sets the named condition 'fastly' // If stack traces are enabled: // - injects 'trace-mapping.inject.js', which contains error mapping code // - enables source maps and writes it as an external file export const bundleStep: CompilerPipelineStep = { outFilename: '__input_bundled.js', async fn(ctx, index) { // esbuild respects input source map, works if it's linked via sourceMappingURL // either inline or as separate file try { const bundleFilename = basename(ctx.outFilepath); // Put build() output in cwd to build bundle and sourcemap with correct paths const outfile = resolve(bundleFilename); const plugins = [fastlyPlugin]; if (ctx.moduleMode) { plugins.push(swallowTopLevelExportsPlugin({ entry: ctx.inFilepath })); } const inject = []; if (ctx.enableStackTraces) { inject.push(resolve(__dirname, '../../rsrc/trace-mapping.inject.js')); } await build({ conditions: ['fastly'], entryPoints: [ctx.inFilepath], bundle: true, write: true, outfile, sourcemap: ctx.enableStackTraces ? 'external' : undefined, sourcesContent: ctx.enableStackTraces ? true : undefined, format: ctx.moduleMode ? 'esm' : 'iife', tsconfig: undefined, plugins, inject, }); // Move build() output to outFilepath await moveFile(outfile, ctx.outFilepath); if (ctx.enableStackTraces) { await moveFile(outfile + '.map', ctx.outFilepath + '.map'); ctx.sourceMaps.push({ f: this.outFilename, s: ctx.outFilepath + '.map', }); } } catch (maybeError: unknown) { const error = maybeError instanceof Error ? maybeError : new Error(String(maybeError)); console.error(`Error:`, error.message); process.exit(1); } await ctx.maybeWriteDebugIntermediateFiles(`__${index + 1}_bundled.js`); }, }; ================================================ FILE: src/compiler-steps/composeSourcemaps.ts ================================================ import { readFile, writeFile } from 'node:fs/promises'; import { resolve } from 'node:path'; import remapping, { SourceMap, type SourceMapInput, type SourceMapLoader, } from '@jridgewell/remapping'; import { TraceMap } from '@jridgewell/trace-mapping'; import picomatch from 'picomatch'; import { CompilerPipelineStep, SourceMapInfo } from '../compilerPipeline.js'; export type ExcludePattern = string | ((file: string) => boolean); // Compiler Step - Compose Sourcemaps // This step usually runs at the end. // This step composes all the source maps up to this point into a single // source map, and injects it into the bundle. // Be careful: Do not run any steps after this step. Such steps will not be // reflected in downstream source maps. export const composeSourcemapsStep: CompilerPipelineStep = { outFilename: '__fastly_bundle_with_sourcemaps.js', async fn(ctx) { // Compose source maps const replaceSourceMapToken = '__FINAL_SOURCE_MAP__'; let excludePatterns: ExcludePattern[] = [ 'forbid-entry:/**', 'node_modules/**', ]; if (ctx.excludeSources) { excludePatterns = [() => true]; } const composed = await composeSourcemaps(ctx.sourceMaps, excludePatterns); const postBundleContent = await readFile(ctx.inFilepath, { encoding: 'utf-8', }); const outputWithSourcemapsContent = postBundleContent.replace( replaceSourceMapToken, () => JSON.stringify(composed), ); await writeFile(ctx.outFilepath, outputWithSourcemapsContent); if (ctx.debugIntermediateFilesDir != null) { await writeFile( resolve(ctx.debugIntermediateFilesDir, 'fastly_sourcemaps.json'), composed, ); } }, }; async function readSourcemap(e: SourceMapInfo) { const sourceMapJson = await readFile(e.s, { encoding: 'utf-8' }); return JSON.parse(sourceMapJson) as SourceMapInput; } export async function composeSourcemaps( sourceMaps: SourceMapInfo[], excludePatterns: ExcludePattern[] = [], ) { const topSourceMap = sourceMaps.pop(); if (topSourceMap == null) { throw new Error( 'Unexpected: composeSourcemaps received empty sourceMaps array.', ); } const top = new TraceMap(await readSourcemap(topSourceMap)); const priors: Record = {}; for (const sourceMap of sourceMaps) { priors[sourceMap.f] = await readSourcemap(sourceMap); } // Loader: given a source name from mapXZ, return a TraceMap for that source (if any). const loader: SourceMapLoader = (source) => { const m = priors[source]; if (!m) return null; // no earlier map for this source return new TraceMap(m); }; const raw = JSON.parse(remapping(top, loader, false).toString()) as SourceMap; return JSON.stringify(stripSourcesContent(raw, excludePatterns)); } function stripSourcesContent(map: SourceMap, excludes: ExcludePattern[]) { if (map.sourcesContent == null) { return map; } const matchers = excludes.map((p) => typeof p === 'string' ? picomatch(p) : p, ); for (let i = 0; i < map.sources.length; i++) { const src = map.sources[i]; // [Windows] normalize slashes const normalized = src?.replace(/\\/g, '/'); if (normalized == null || matchers.some((fn) => fn(normalized))) { map.sourcesContent[i] = null; } } return map; } ================================================ FILE: src/compiler-steps/precompileRegexes.ts ================================================ import { parse } from 'acorn'; import { simple as simpleWalk } from 'acorn-walk'; import regexpuc from 'regexpu-core'; import { CompilerPipelineStep } from '../compilerPipeline.js'; // Compiler Step - Precompile regexes // This step runs any time after bundling export const precompileRegexesStep: CompilerPipelineStep = { outFilename: '__fastly_precompiled_regexes.js', async fn(ctx, index) { await ctx.magicStringWriter( this.outFilename, async (magicString, source) => { // PRECOMPILE REGEXES // Emit a block of JavaScript that will pre-compile the regular expressions given. // As SpiderMonkey will intern regular expressions, duplicating them at the top // level and testing them with both an ascii and utf8 string should ensure that // they won't be re-compiled when run in the fetch handler. const PREAMBLE = `(function(){ // Precompiled regular expressions const precompile = (r) => { r.exec('a'); r.exec('\\u1000'); };`; const POSTAMBLE = '})();'; const ast = parse(source, { ecmaVersion: 'latest', sourceType: ctx.moduleMode ? 'module' : 'script', }); const precompileCalls: string[] = []; simpleWalk(ast, { Literal(node) { if (!node.regex) return; let transpiledPattern; try { transpiledPattern = regexpuc( node.regex.pattern, node.regex.flags, { unicodePropertyEscapes: 'transform', }, ); } catch { // swallow regex parse errors here to instead throw them at the engine level // this then also avoids regex parser bugs being thrown unnecessarily transpiledPattern = node.regex.pattern; } const transpiledRegex = `/${transpiledPattern}/${node.regex.flags}`; precompileCalls.push(`precompile(${transpiledRegex});`); magicString.overwrite(node.start, node.end, transpiledRegex); }, }); if (precompileCalls.length) { magicString.prepend( `${PREAMBLE}${precompileCalls.join('')}${POSTAMBLE}\n`, ); } }, ); await ctx.maybeWriteDebugIntermediateFiles( `__${index + 1}_precompiled_regexes.js`, ); }, }; ================================================ FILE: src/compilerPipeline.ts ================================================ import { copyFile, readFile, writeFile } from 'node:fs/promises'; import { basename, resolve } from 'node:path'; import MagicString from 'magic-string'; import { pipeline } from './pipeline.js'; export type SourceMapInfo = { f: string; // Filename s: string; // Sourcemap filename }; export class CompilerContext { inFilepath: string; outFilepath: string; tmpDir: string; debugIntermediateFilesDir: string | undefined; sourceMaps: SourceMapInfo[]; moduleMode: boolean; enableStackTraces: boolean; excludeSources: boolean; compilerPipelineSteps: CompilerPipelineStep[]; constructor( input: string, tmpDir: string, debugIntermediateFilesDir: string | undefined, moduleMode: boolean, enableStackTraces: boolean, excludeSources: boolean, ) { this.inFilepath = input; this.outFilepath = ''; // This is filled in by the eventual steps of the compiler this.tmpDir = tmpDir; this.debugIntermediateFilesDir = debugIntermediateFilesDir; this.sourceMaps = []; this.moduleMode = moduleMode; this.enableStackTraces = enableStackTraces; this.excludeSources = excludeSources; this.compilerPipelineSteps = []; } addCompilerPipelineStep(step: CompilerPipelineStep) { this.compilerPipelineSteps.push(step); } async applyCompilerPipeline() { await pipeline( this.compilerPipelineSteps.map( (step) => async (args: CompilerContext, index) => { await step.fn.call(step, args, index); return args; }, ), this, { beforeStep: (args: CompilerContext, index: number) => { const step = this.compilerPipelineSteps[index]; args.outFilepath = resolve(this.tmpDir, step.outFilename); }, afterStep: (args: CompilerContext) => { args.inFilepath = args.outFilepath; }, }, ); } async magicStringWriter( filename: string, fn: (magicString: MagicString, source: string) => void | Promise, ) { const source = await readFile(this.inFilepath, { encoding: 'utf8' }); const magicString = new MagicString(source); await fn(magicString, source); await writeFile(this.outFilepath, magicString.toString()); if (this.enableStackTraces != null) { const map = magicString.generateMap({ source: basename(this.inFilepath), hires: true, includeContent: true, }); await writeFile(this.outFilepath + '.map', map.toString()); this.sourceMaps.push({ f: filename, s: this.outFilepath + '.map' }); } } async maybeWriteDebugIntermediateFile(outFilename: string) { if (this.debugIntermediateFilesDir != null) { await copyFile( this.outFilepath, resolve(this.debugIntermediateFilesDir, outFilename), ); } } async maybeWriteDebugIntermediateSourceMapFile(outFilename: string) { if (this.enableStackTraces && this.debugIntermediateFilesDir != null) { await copyFile( this.outFilepath + '.map', resolve(this.debugIntermediateFilesDir, outFilename), ); } } async maybeWriteDebugIntermediateFiles(outFilename: string) { await this.maybeWriteDebugIntermediateFile(outFilename); await this.maybeWriteDebugIntermediateSourceMapFile(outFilename + '.map'); } } export type CompilerPipelineStep = { outFilename: string; fn: ( this: CompilerPipelineStep, args: CompilerContext, index: number, ) => void | PromiseLike; }; ================================================ FILE: src/config.ts ================================================ import { cosmiconfig } from 'cosmiconfig'; const additiveOptionsMap = { env: '--env', }; const strictOptionsMap = { enableAOT: '--enable-aot', aotCache: '--aot-cache', enableHttpCache: '--enable-http-cache', enableExperimentalHighResolutionTimeMethods: '--enable-experimental-high-resolution-time-methods', enableExperimentalTopLevelAwait: '--enable-experimental-top-level-await', enableStackTraces: '--enable-stack-traces', excludeSources: '--exclude-sources', debugIntermediateFiles: '--debug-intermediate-files', debugBuild: '--debug-build', engineWasm: '--engine-wasm', wevalBin: '--weval-bin', }; export async function readConfigFileAndCliArguments(cliArgs: string[]) { const explorer = cosmiconfig('fastlycompute'); const result = await explorer.search(); if (!result?.config) { return cliArgs; } const config = result.config as Record< string, string | boolean | object | (string | boolean | object)[] >; const synthesizedArgs: string[] = []; // --- Loop 1: Additive Options (Array-Normalized) --- for (const [configKey, flag] of Object.entries(additiveOptionsMap)) { const val = config[configKey]; if (val === undefined || val === null) continue; // Wrap in an array if it isn't one already const items = (Array.isArray(val) ? val : [val]) as ( | string | boolean | object )[]; for (const item of items) { if (typeof item === 'object' && item !== null) { // Handle: { "FOO": "bar" } -> --env FOO=bar for (const [k, v] of Object.entries(item)) { synthesizedArgs.push(flag, `${k}=${v}`); } } else { // Handle: "A,B" -> --env A,B synthesizedArgs.push(flag, String(item)); } } } // --- Loop 2: Strict Options (Override Check) --- for (const [configKey, flag] of Object.entries(strictOptionsMap)) { const val = config[configKey]; if (val === undefined || val === null) continue; const isOverridden = cliArgs.some( (arg) => arg === flag || arg.startsWith(`${flag}=`), ); if (!isOverridden) { if (typeof val === 'boolean' && val) { synthesizedArgs.push(flag); } else if (typeof val === 'string' || typeof val === 'number') { synthesizedArgs.push(flag, String(val)); } } } return [...synthesizedArgs, ...cliArgs]; } ================================================ FILE: src/env.ts ================================================ // env.js function parseEnvPair(pair: string) { const trimmedPair = pair.trim(); // If no '=', treat as a variable to inherit if (!trimmedPair.includes('=')) { const value = process.env[trimmedPair]; if (value === undefined) { return undefined; } console.warn( `Writing ${trimmedPair} environment variable into the runtime from the current process environment`, ); return [trimmedPair, value]; } const matches = /^([^=]+)=(.*)$/.exec(trimmedPair); if (!matches) { throw new Error( `Invalid environment variable format: ${trimmedPair}\nMust be in format KEY=VALUE or an existing environment variable name`, ); } const key = matches[1].trim(); const value = matches[2]; if (!key) { throw new Error( `Invalid environment variable format: ${trimmedPair}\nMust be in format KEY=VALUE or an existing environment variable name`, ); } return [key, value]; } function parseEnvString(envString: string) { const result: Record = {}; // Split on unescaped commas and filter out empty strings const pairs = envString .split(/(? s.replace(/\\,/g, ',')) // Replace escaped commas with regular commas .filter(Boolean); // Parse each pair into the result object for (const pair of pairs) { const res = parseEnvPair(pair); if (res === undefined) { continue; } const [key, value] = res; result[key] = value; } return result; } export class EnvParser { env: Record; constructor() { this.env = {}; } /** * Parse environment variables string, which can be either KEY=VALUE pairs * or names of environment variables to inherit * @param {string} value - The environment variable string to parse */ parse(value: string) { if (!value) { throw new Error( 'Invalid environment variable format: \nMust be in format KEY=VALUE or an existing environment variable name', ); } const newEnv = parseEnvString(value); this.env = { ...this.env, ...newEnv }; } /** * Get the parsed environment variables * @returns {Object} The environment variables object */ getEnv() { return this.env; } } ================================================ FILE: src/esbuild-plugins/fastlyPlugin.ts ================================================ import { type Plugin } from 'esbuild'; export const fastlyPlugin: Plugin = { name: 'fastly', setup(build) { build.onResolve({ filter: /^fastly:.*/ }, (args) => { return { path: args.path.replace('fastly:', ''), namespace: 'fastly', }; }); build.onLoad({ filter: /^.*/, namespace: 'fastly' }, async (args) => { switch (args.path) { case 'acl': { return { contents: `export const Acl = globalThis.Acl;`, }; } case 'backend': { return { contents: ` export const Backend = globalThis.Backend; export const setDefaultDynamicBackendConfig = Object.getOwnPropertyDescriptor(globalThis.fastly, 'allowDynamicBackends').set; const allowDynamicBackends = Object.getOwnPropertyDescriptor(globalThis.fastly, 'allowDynamicBackends').set; export const setDefaultBackend = Object.getOwnPropertyDescriptor(globalThis.fastly, 'defaultBackend').set; export function enforceExplicitBackends (defaultBackend) { allowDynamicBackends(false); if (defaultBackend) setDefaultBackend(defaultBackend); } `, }; } case 'body': { return { contents: `export const FastlyBody = globalThis.FastlyBody;`, }; } case 'cache-override': { return { contents: `export const CacheOverride = globalThis.CacheOverride;`, }; } case 'config-store': { return { contents: `export const ConfigStore = globalThis.ConfigStore;`, }; } case 'dictionary': { return { contents: `export const Dictionary = globalThis.Dictionary;`, }; } case 'device': { return { contents: `export const Device = globalThis.Device;` }; } case 'edge-rate-limiter': { return { contents: ` export const RateCounter = globalThis.RateCounter; export const PenaltyBox = globalThis.PenaltyBox; export const EdgeRateLimiter = globalThis.EdgeRateLimiter; `, }; } case 'env': { return { contents: `export const env = globalThis.fastly.env.get;` }; } case 'experimental': { return { contents: ` export const includeBytes = globalThis.fastly.includeBytes; export const enableDebugLogging = globalThis.fastly.enableDebugLogging; export const setBaseURL = Object.getOwnPropertyDescriptor(globalThis.fastly, 'baseURL').set; export const setDefaultBackend = Object.getOwnPropertyDescriptor(globalThis.fastly, 'defaultBackend').set; export const allowDynamicBackends = Object.getOwnPropertyDescriptor(globalThis.fastly, 'allowDynamicBackends').set; export const sdkVersion = globalThis.fastly.sdkVersion; export const mapAndLogError = (e) => globalThis.__fastlyMapAndLogError(e); export const mapError = (e) => globalThis.__fastlyMapError(e); export const setReusableSandboxOptions = globalThis.fastly.setReusableSandboxOptions; `, }; } case 'fanout': { return { contents: `export const createFanoutHandoff = globalThis.fastly.createFanoutHandoff;`, }; } case 'websocket': { return { contents: `export const createWebsocketHandoff = globalThis.fastly.createWebsocketHandoff;`, }; } case 'geolocation': { return { contents: `export const getGeolocationForIpAddress = globalThis.fastly.getGeolocationForIpAddress;`, }; } case 'logger': { return { contents: `export const Logger = globalThis.Logger; export const configureConsole = Logger.configureConsole; delete globalThis.Logger.configureConsole; `, }; } case 'kv-store': { return { contents: `export const KVStore = globalThis.KVStore;` }; } case 'secret-store': { return { contents: `export const SecretStore = globalThis.SecretStore;export const SecretStoreEntry = globalThis.SecretStoreEntry;`, }; } case 'cache': { return { contents: ` export const CacheEntry = globalThis.CacheEntry; export const CacheState = globalThis.CacheState; export const CoreCache = globalThis.CoreCache; export const SimpleCache = globalThis.SimpleCache; export const SimpleCacheEntry = globalThis.SimpleCacheEntry; export const TransactionCacheEntry = globalThis.TransactionCacheEntry; `, }; } case 'compute': { return { contents: `export const { purgeSurrogateKey, vCpuTime } = globalThis.fastly;`, }; } case 'html-rewriter': { return { contents: `export const HTMLRewritingStream = globalThis.HTMLRewritingStream;`, }; } case 'image-optimizer': { return { contents: `export const { Region, Auto, Format, BWAlgorithm, Disable, Enable, Fit, Metadata, Optimize, Orient, Profile, ResizeFilter, CropMode, optionsToQueryString } = globalThis.fastly.imageOptimizer;`, }; } case 'shielding': { return { contents: `export const { Shield } = globalThis.fastly.shielding;`, }; } case 'security': { return { contents: `export const inspect = globalThis.fastly.inspect;`, }; } } }); }, }; ================================================ FILE: src/esbuild-plugins/swallowTopLevelExportsPlugin.ts ================================================ import { dirname, isAbsolute, resolve } from 'node:path'; import { type Plugin } from 'esbuild'; export type SwallowTopLevelExportsPluginParams = { entry?: string; }; export function swallowTopLevelExportsPlugin( opts?: SwallowTopLevelExportsPluginParams, ): Plugin { const { entry } = opts ?? {}; const name = 'swallow-top-level-exports'; const namespace = 'swallow-top-level'; if (!entry) throw new Error(`[${name}] You must provide opts.entry`); // Normalize once so our onResolve comparison is exact. const normalizedEntry = resolve(entry); return { name, setup(build) { build.onResolve({ filter: /.*/ }, (args) => { const maybeEntry = isAbsolute(args.path) ? args.path : resolve(args.resolveDir || process.cwd(), args.path); if (args.kind === 'entry-point' && maybeEntry === normalizedEntry) { return { path: normalizedEntry, namespace }; } return null; }); build.onLoad({ filter: /.*/, namespace }, (args) => { // Generate a JS wrapper that imports the real entry // This swallows the top level exports for the entry file // and runs any side effects, such as addEventListener(). return { contents: `import ${JSON.stringify(args.path)};`, loader: 'js', resolveDir: dirname(args.path), }; }); }, }; } ================================================ FILE: src/files.ts ================================================ import { stat, rename, copyFile, unlink } from 'node:fs/promises'; import { resolve } from 'node:path'; export async function isFile(path: string) { const stats = await stat(path); return stats.isFile(); } export async function isDirectory(path: string) { const stats = await stat(path); return stats.isDirectory(); } export async function moveFile(src: string, dest: string): Promise { try { await rename(src, dest); } catch (err: unknown) { if (!isErrnoException(err) || err.code !== 'EXDEV') { throw err; } // Cross-device move: copy + delete await copyFile(src, dest); await unlink(src); } } function isErrnoException(err: unknown): err is NodeJS.ErrnoException { return ( typeof err === 'object' && err !== null && 'code' in err && typeof err.code === 'string' ); } ================================================ FILE: src/index.ts ================================================ export {}; ================================================ FILE: src/parseInputs.ts ================================================ import { fileURLToPath } from 'node:url'; import { dirname, join, isAbsolute } from 'node:path'; import { tooManyEngines, unknownArgument } from './printHelp.js'; import { EnvParser } from './env.js'; export type ParsedInputs = | 'help' | 'version' | { enableAOT: boolean; aotCache: string; enableHttpCache: boolean; enableExperimentalHighResolutionTimeMethods: boolean; moduleMode: boolean; bundle: boolean; enableStackTraces: boolean; excludeSources: boolean; debugIntermediateFilesDir: string | undefined; wasmEngine: string; wevalBin: string | undefined; input: string; output: string; env: Record; }; export async function parseInputs(cliInputs: string[]): Promise { const __dirname = dirname(fileURLToPath(import.meta.url)); let enableHttpCache = false; let enableExperimentalHighResolutionTimeMethods = false; let enableAOT = false; let customEngineSet = false; let moduleMode = false; let bundle = true; let wasmEngine = join(__dirname, '../fastly.wasm'); let aotCache = join(__dirname, '../fastly-ics.wevalcache'); let customInputSet = false; let input = join(process.cwd(), 'bin/index.js'); let customOutputSet = false; let output = join(process.cwd(), 'bin/main.wasm'); let enableStackTraces = false; let excludeSources = false; let debugIntermediateFilesDir = undefined; let wevalBin = undefined; let cliInput; const envParser = new EnvParser(); loop: while ((cliInput = cliInputs.shift())) { switch (cliInput) { case '--': { break loop; } case '--env': { let value = cliInputs.shift(); if (!value) { console.error('Error: --env requires a KEY=VALUE pair'); process.exit(1); } // If value ends with comma, it's a continuation while ( value.endsWith(',') && cliInputs.length > 0 && !cliInputs[0].startsWith('-') ) { value = value + cliInputs.shift(); } envParser.parse(value); break; } case '--enable-experimental-high-resolution-time-methods': { enableExperimentalHighResolutionTimeMethods = true; break; } case '--module-mode': { moduleMode = true; bundle = false; break; } case '--enable-http-cache': { enableHttpCache = true; break; } case '--enable-experimental-top-level-await': { moduleMode = true; bundle = true; break; } case '--enable-aot': { enableAOT = true; break; } case '--enable-experimental-aot': { console.error( 'Warning: --enable-experimental-aot flag is now --enable-aot. The old flag continues\n' + 'to work for now, but please update your build invocation!', ); enableAOT = true; break; } case '-V': case '--version': { return 'version'; } case '-h': case '--help': { return 'help'; } case '--starlingmonkey': { break; } case '--debug-build': { wasmEngine = join(__dirname, '../fastly.debug.wasm'); console.log('Building with the debug engine'); break; } case '--disable-starlingmonkey': { console.error( 'The legacy js-compute-runtime.wasm engine requires an older version of the JS SDK', ); process.exit(1); } case '--engine-wasm': { if (customEngineSet) { tooManyEngines(); } const value = cliInputs.shift(); if (value == null) { console.error('Error: --engine-wasm requires a value'); process.exit(1); } customEngineSet = true; if (isAbsolute(value)) { wasmEngine = value; } else { wasmEngine = join(process.cwd(), value); } break; } case '--weval-bin': { const value = cliInputs.shift(); if (value == null) { console.error('Error: --weval-bin requires a value'); process.exit(1); } if (isAbsolute(value)) { wevalBin = value; } else { wevalBin = join(process.cwd(), value); } break; } case '--aot-cache': { const value = cliInputs.shift(); if (value == null) { console.error('Error: --aot-cache requires a value'); process.exit(1); } if (isAbsolute(value)) { aotCache = value; } else { aotCache = join(process.cwd(), value); } break; } case '--enable-stack-traces': { enableStackTraces = true; break; } case '--exclude-sources': { excludeSources = true; break; } case '--debug-intermediate-files': { const value = cliInputs.shift(); if (value == null) { console.error('Error: --debug-intermediate-files requires a value'); process.exit(1); } if (isAbsolute(value)) { debugIntermediateFilesDir = value; } else { debugIntermediateFilesDir = join(process.cwd(), value); } break; } default: { if (cliInput.startsWith('--engine-wasm=')) { if (customEngineSet) { tooManyEngines(); } const value = cliInput.replace(/--engine-wasm=+/, ''); customEngineSet = true; if (isAbsolute(value)) { wasmEngine = value; } else { wasmEngine = join(process.cwd(), value); } break; } else if (cliInput.startsWith('--env=')) { const value = cliInput.replace(/--env=/, ''); envParser.parse(value); break; } else if (cliInput.startsWith('--weval-bin=')) { const value = cliInput.replace(/--weval-bin=/, ''); if (isAbsolute(value)) { wevalBin = value; } else { wevalBin = join(process.cwd(), value); } break; } else if (cliInput.startsWith('--aot-cache=')) { const value = cliInput.replace(/--aot-cache=/, ''); if (isAbsolute(value)) { aotCache = value; } else { aotCache = join(process.cwd(), value); } break; } else if (cliInput.startsWith('--debug-intermediate-files=')) { const value = cliInput.replace(/--debug-intermediate-files=/, ''); if (isAbsolute(value)) { debugIntermediateFilesDir = value; } else { debugIntermediateFilesDir = join(process.cwd(), value); } break; } else if (cliInput.startsWith('-')) { unknownArgument(cliInput); } else { if (!customInputSet) { customInputSet = true; if (isAbsolute(cliInput)) { input = cliInput; } else { input = join(process.cwd(), cliInput); } } else if (!customOutputSet) { customOutputSet = true; if (isAbsolute(cliInput)) { output = cliInput; } else { output = join(process.cwd(), cliInput); } } else { unknownArgument(cliInput); } } } } } if (!customEngineSet && enableAOT) { wasmEngine = join(__dirname, '../fastly-weval.wasm'); } if (wevalBin && !enableAOT) { console.error( 'Warning: --weval-bin has no effect without --enable-aot, as weval is only used for AOT compilation', ); } return { enableExperimentalHighResolutionTimeMethods, enableHttpCache, moduleMode, bundle, enableAOT, aotCache, enableStackTraces, excludeSources, debugIntermediateFilesDir, input, output, wasmEngine, wevalBin, env: envParser.getEnv(), }; } ================================================ FILE: src/pipeline.ts ================================================ // From https://github.com/harmony7/js-async-pipeline import { resolve } from 'node:path'; export type PipelineOpts = { beforeStep?: ( args: TValue, index: number, arr: PipelineStep[], ) => void | PromiseLike; afterStep?: ( args: TValue, index: number, arr: PipelineStep[], ) => void | PromiseLike; }; export type PipelineStep = ( acc: TValue, index: number, arr: PipelineStep[], ) => TValue | PromiseLike; export async function pipeline( steps: PipelineStep[], initialValue: TValue, opts?: PipelineOpts, ): Promise { let val = initialValue; for (const [index, step] of steps.entries()) { await opts?.beforeStep?.call(opts, val, index, steps); val = await step(val, index, steps); await opts?.afterStep?.call(opts, val, index, steps); } return val; } ================================================ FILE: src/printHelp.ts ================================================ import { readFile } from 'node:fs/promises'; import { basename, dirname, join } from 'node:path'; import { argv } from 'node:process'; import { fileURLToPath } from 'node:url'; const __dirname = dirname(fileURLToPath(import.meta.url)); export async function printHelp() { await printVersion(); console.log(` USAGE: ${basename(argv[1])} [FLAGS] [OPTIONS] [ARGS] FLAGS: -h, --help Prints help information -V, --version Prints version information OPTIONS: --env Set environment variables, possibly inheriting from the current environment. Multiple variables can be comma-separated (e.g., --env ENV_VAR,OVERRIDE=val) --module-mode [experimental] Run all sources as native modules, with full error stack support. --engine-wasm The JS engine Wasm file path with full error stack support --enable-http-cache Enable the HTTP cache hook API --enable-aot Enable AOT compilation for performance --enable-experimental-high-resolution-time-methods Enable experimental fastly.now() method --enable-experimental-top-level-await Enable experimental top level await --enable-stack-traces Enable stack traces --exclude-sources Don't include sources in stack traces --debug-intermediate-files Output intermediate files in directory --weval-bin Path to the weval binary to use for AOT compilation ARGS: The input JS script's file path [default: bin/index.js] The file path to write the output Wasm module to [default: bin/main.wasm] `); } export async function printVersion() { const packageJson = await readFile(join(__dirname, '../package.json'), { encoding: 'utf-8', }); const version = (JSON.parse(packageJson) as { version: string }).version; console.log(`${basename(argv[1])} ${version}`); } export function tooManyEngines() { console.error(`error: The argument '--engine-wasm ' was provided more than once, but cannot be used multiple times USAGE: js-compute-runtime --engine-wasm For more information try --help`); process.exit(1); } export function unknownArgument(cliInput: string) { console.error(`error: Found argument '${cliInput}' which wasn't expected, or isn't valid in this context USAGE: js-compute-runtime [FLAGS] [OPTIONS] [ARGS] For more information try --help`); process.exit(1); } ================================================ FILE: src/types/modules.d.ts ================================================ declare module '@bytecodealliance/wizer' { const wizer: string; export default wizer; } declare module '@bytecodealliance/weval' { function getWeval(): Promise; export default getWeval; } ================================================ FILE: target/rust-analyzer/flycheck0/stderr ================================================ warning: only one of `license` or `license-file` is necessary `license` should be used if the package license can be expressed with a standard SPDX expression. `license-file` should be used if the package uses a non-standard license. See https://doc.rust-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields for more information. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.24s ================================================ FILE: target/rust-analyzer/flycheck0/stdout ================================================ {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#libc@0.2.135","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/libc-0.2.135/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/libc-0.2.135/build.rs","edition":"2015","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/libc-339e46fc48e380a6/build-script-build"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#libc@0.2.135","linked_libs":[],"linked_paths":[],"cfgs":["freebsd11","libc_priv_mod_use","libc_union","libc_const_size_of","libc_align","libc_int128","libc_core_cvoid","libc_packedN","libc_cfg_target_vendor","libc_non_exhaustive","libc_ptr_addr_of","libc_underscore_const_names","libc_const_extern_fn"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/libc-c9520a982e130a31/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#autocfg@1.1.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/autocfg-1.1.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"autocfg","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/autocfg-1.1.0/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libautocfg-d60d3d7f96968932.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libautocfg-d60d3d7f96968932.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.93","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.93/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.93/build.rs","edition":"2021","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","proc-macro"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/proc-macro2-5f3a33774ff8bf70/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.5","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicode-ident-1.0.5/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"unicode_ident","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicode-ident-1.0.5/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libunicode_ident-4ab9377362aafc46.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libunicode_ident-4ab9377362aafc46.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/cfg-if-1.0.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"cfg_if","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/cfg-if-1.0.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libcfg_if-f063294a1a369ae9.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#syn@1.0.102","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/syn-1.0.102/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/syn-1.0.102/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["clone-impls","default","derive","full","parsing","printing","proc-macro","quote"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/syn-27641e2e3de11e10/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.4","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/version_check-0.9.4/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"version_check","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/version_check-0.9.4/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libversion_check-9f8b8f950a57558c.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libversion_check-9f8b8f950a57558c.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#memchr@2.5.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/memchr-2.5.0/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/memchr-2.5.0/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/memchr-c714af3b4baacdc4/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.9","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pin-project-lite-0.2.9/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"pin_project_lite","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pin-project-lite-0.2.9/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libpin_project_lite-674186df2f8de93e.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-core-0.3.24/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-core-0.3.24/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/futures-core-a83619a12a98e279/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#bytes@1.2.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bytes-1.2.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"bytes","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bytes-1.2.1/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libbytes-406ce56f79513e76.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#log@0.4.17","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.17/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.17/build.rs","edition":"2015","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/log-873e797bfc091865/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#parking_lot_core@0.9.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/parking_lot_core-0.9.3/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/parking_lot_core-0.9.3/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/parking_lot_core-a5ddf60e654d6982/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-task-0.3.24/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-task-0.3.24/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/futures-task-b7fece059ff477c3/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#libc@0.2.135","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/libc-0.2.135/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"libc","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/libc-0.2.135/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/liblibc-cf7ae6aaa70202b9.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.93","linked_libs":[],"linked_paths":[],"cfgs":["wrap_proc_macro"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/proc-macro2-d651853fa23396e3/out"} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#syn@1.0.102","linked_libs":[],"linked_paths":[],"cfgs":["syn_disable_nightly_tests"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/syn-26acf9469c711d72/out"} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#memchr@2.5.0","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/memchr-200f7bf1a6fbf597/out"} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.24","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/futures-core-6a545f8d2aaaa0d9/out"} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#log@0.4.17","linked_libs":[],"linked_paths":[],"cfgs":["atomic_cas","has_atomics"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/log-ae026b7ad9087e1c/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#lock_api@0.4.9","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/lock_api-0.4.9/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/lock_api-0.4.9/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/lock_api-4e8df7dd5fab4dca/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#slab@0.4.7","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/slab-0.4.7/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/slab-0.4.7/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/slab-ebae6161c5fb9572/build-script-build"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#parking_lot_core@0.9.3","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/parking_lot_core-d12d972cd7ec1f37/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#scopeguard@1.1.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/scopeguard-1.1.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"scopeguard","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/scopeguard-1.1.0/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libscopeguard-7bbec343904ba2e4.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-channel-0.3.24/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-channel-0.3.24/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","default","futures-sink","sink","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/futures-channel-113cf5c051ccc904/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#smallvec@1.10.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/smallvec-1.10.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"smallvec","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/smallvec-1.10.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsmallvec-a3f258c82875f629.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#core-foundation-sys@0.8.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/core-foundation-sys-0.8.3/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/core-foundation-sys-0.8.3/build.rs","edition":"2015","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/core-foundation-sys-c09b5b3d0c20022e/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-sink-0.3.24/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"futures_sink","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-sink-0.3.24/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfutures_sink-db6db87b953f1e2c.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.93","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.93/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"proc_macro2","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.93/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","proc-macro"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libproc_macro2-dcc78d1642ab9fcd.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libproc_macro2-dcc78d1642ab9fcd.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#memchr@2.5.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/memchr-2.5.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"memchr","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/memchr-2.5.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libmemchr-1f131721245bcc5b.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#lock_api@0.4.9","linked_libs":[],"linked_paths":[],"cfgs":["has_const_fn_trait_bound"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/lock_api-f7d6ec7efbf7565c/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#log@0.4.17","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.17/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"log","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.17/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/liblog-c3a943f500f56506.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-core-0.3.24/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"futures_core","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-core-0.3.24/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfutures_core-f9ecb257b9627941.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#core-foundation-sys@0.8.3","linked_libs":["framework=CoreFoundation"],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/core-foundation-sys-4094ed832391849c/out"} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#slab@0.4.7","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/slab-5667d6f336e59b08/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#parking_lot_core@0.9.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/parking_lot_core-0.9.3/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"parking_lot_core","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/parking_lot_core-0.9.3/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libparking_lot_core-2a0db7a2644563ee.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.24","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/futures-channel-f73393bcb0cb2401/out"} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.24","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/futures-task-674bce2f9912ca57/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tokio@1.24.2","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.24.2/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.24.2/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["bytes","default","fs","full","io-std","io-util","libc","macros","memchr","mio","net","num_cpus","parking_lot","process","rt","rt-multi-thread","signal","signal-hook-registry","socket2","sync","time","tokio-macros"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/tokio-ebdaf98c3ce3473c/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.4","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/itoa-1.0.4/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"itoa","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/itoa-1.0.4/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libitoa-3983822e1402c741.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-util-0.3.24/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-util-0.3.24/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","async-await","async-await-macro","channel","futures-channel","futures-io","futures-macro","futures-sink","io","memchr","sink","slab","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/futures-util-d37eefec798067ec/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#once_cell@1.15.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/once_cell-1.15.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"once_cell","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/once_cell-1.15.0/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","default","race","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libonce_cell-e3869f9a77b4802f.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#quote@1.0.38","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/quote-1.0.38/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"quote","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/quote-1.0.38/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","proc-macro"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libquote-9ae777020386aa13.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libquote-9ae777020386aa13.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#lock_api@0.4.9","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/lock_api-0.4.9/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"lock_api","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/lock_api-0.4.9/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/liblock_api-9d5d6ab442b53f6f.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#tokio@1.24.2","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/tokio-ba2c291c5b5cd8a2/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-task-0.3.24/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"futures_task","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-task-0.3.24/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfutures_task-7a2c67f37ab9eba4.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#mio@0.8.4","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.4/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"mio","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.4/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","net","os-ext","os-poll"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libmio-14d6aa114fd4c545.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#core-foundation-sys@0.8.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/core-foundation-sys-0.8.3/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"core_foundation_sys","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/core-foundation-sys-0.8.3/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libcore_foundation_sys-3fd606f180036d1a.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-channel-0.3.24/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"futures_channel","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-channel-0.3.24/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","default","futures-sink","sink","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfutures_channel-4461d3193d0b31d5.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#slab@0.4.7","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/slab-0.4.7/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"slab","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/slab-0.4.7/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libslab-958e14509fcb14b9.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.24","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/futures-util-111e2701d25739a7/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#socket2@0.4.7","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/socket2-0.4.7/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"socket2","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/socket2-0.4.7/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["all"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsocket2-c0e59ae489d5af14.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#num_cpus@1.13.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/num_cpus-1.13.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"num_cpus","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/num_cpus-1.13.1/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libnum_cpus-48fd7f3e7c55b580.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#signal-hook-registry@1.4.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/signal-hook-registry-1.4.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"signal_hook_registry","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/signal-hook-registry-1.4.0/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsignal_hook_registry-678fe1d817e524c2.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#unicase@2.6.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicase-2.6.0/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicase-2.6.0/build.rs","edition":"2015","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/unicase-92c9dd1c8da6f1ae/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#indexmap@1.9.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/indexmap-1.9.1/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/indexmap-1.9.1/build.rs","edition":"2021","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/indexmap-3f25abd69fc43f89/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#syn@1.0.102","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/syn-1.0.102/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"syn","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/syn-1.0.102/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["clone-impls","default","derive","full","parsing","printing","proc-macro","quote"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsyn-cb4c11802518e3d5.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsyn-cb4c11802518e3d5.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/parking_lot-0.12.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"parking_lot","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/parking_lot-0.12.1/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libparking_lot-64a9578aedeb1525.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#pin-utils@0.1.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pin-utils-0.1.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"pin_utils","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pin-utils-0.1.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libpin_utils-92de88d007e616b8.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-io@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-io-0.3.24/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"futures_io","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-io-0.3.24/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfutures_io-896774505226f473.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#unicase@2.6.0","linked_libs":[],"linked_paths":[],"cfgs":["__unicase__iter_cmp","__unicase__default_hasher","__unicase__const_fns","__unicase__core_and_alloc"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/unicase-b89ea1d0cfbddab9/out"} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#indexmap@1.9.1","linked_libs":[],"linked_paths":[],"cfgs":["has_std"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/indexmap-cbf938b8e51d938a/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tracing-core@0.1.30","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tracing-core-0.1.30/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"tracing_core","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tracing-core-0.1.30/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["once_cell","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtracing_core-2ee4989823912581.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/shlex-1.3.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"shlex","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/shlex-1.3.0/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libshlex-8683314999dfd5a8.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libshlex-8683314999dfd5a8.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#lazy_static@1.4.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/lazy_static-1.4.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"lazy_static","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/lazy_static-1.4.0/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/liblazy_static-b27d32fa506d233a.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#bitflags@1.3.2","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bitflags-1.3.2/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"bitflags","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bitflags-1.3.2/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libbitflags-55faf151d3a8e80b.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/fnv-1.0.7/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"fnv","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/fnv-1.0.7/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfnv-1f26e4524fd9ffc0.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.12.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/hashbrown-0.12.3/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"hashbrown","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/hashbrown-0.12.3/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["raw"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libhashbrown-d42b0a1fd196487a.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#typenum@1.15.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/typenum-1.15.0/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-main","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/typenum-1.15.0/build/main.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/typenum-2a4aabb423d62ea0/build-script-main"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#core-foundation@0.9.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/core-foundation-0.9.3/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"core_foundation","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/core-foundation-0.9.3/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libcore_foundation-289207a437d06525.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tokio-macros@1.8.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-macros-1.8.0/Cargo.toml","target":{"kind":["proc-macro"],"crate_types":["proc-macro"],"name":"tokio_macros","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-macros-1.8.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtokio_macros-bbbf231dee3783f9.dylib"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-macro@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-macro-0.3.24/Cargo.toml","target":{"kind":["proc-macro"],"crate_types":["proc-macro"],"name":"futures_macro","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-macro-0.3.24/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfutures_macro-edb5279068644088.dylib"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#http@0.2.8","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/http-0.2.8/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"http","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/http-0.2.8/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libhttp-966c1f0f3a0fbb0b.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#indexmap@1.9.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/indexmap-1.9.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"indexmap","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/indexmap-1.9.1/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libindexmap-c212ed9a585c93ea.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.37","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tracing-0.1.37/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"tracing","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tracing-0.1.37/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtracing-273912a3c3dff670.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#typenum@1.15.0","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[["TYPENUM_BUILD_CONSTS","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/typenum-f2380115c5a3539c/out/consts.rs"],["TYPENUM_BUILD_OP","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/typenum-f2380115c5a3539c/out/op.rs"]],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/typenum-f2380115c5a3539c/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#cc@1.2.11","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/cc-1.2.11/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"cc","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/cc-1.2.11/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libcc-a6a82632781e467a.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libcc-a6a82632781e467a.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#security-framework-sys@2.6.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/security-framework-sys-2.6.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"security_framework_sys","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/security-framework-sys-2.6.1/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["OSX_10_9","default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsecurity_framework_sys-7251db3f95734f55.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.6","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/generic-array-0.14.6/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/generic-array-0.14.6/build.rs","edition":"2015","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["more_lengths"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/generic-array-0c2d363290ab86a8/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#serde@1.0.145","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde-1.0.145/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde-1.0.145/build.rs","edition":"2015","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/serde-a34d5f2515b5f918/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#remove_dir_all@0.5.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/remove_dir_all-0.5.3/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"remove_dir_all","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/remove_dir_all-0.5.3/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libremove_dir_all-939a0eb23a5ddde6.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#native-tls@0.2.10","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/native-tls-0.2.10/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/native-tls-0.2.10/build.rs","edition":"2015","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/native-tls-afd9e8e75691e667/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tinyvec_macros@0.1.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tinyvec_macros-0.1.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"tinyvec_macros","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tinyvec_macros-0.1.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtinyvec_macros-aa0ad83d54e35740.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#fastrand@1.8.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/fastrand-1.8.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"fastrand","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/fastrand-1.8.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfastrand-1aa1de4f7c920d15.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-util-0.3.24/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"futures_util","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-util-0.3.24/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","async-await","async-await-macro","channel","futures-channel","futures-io","futures-macro","futures-sink","io","memchr","sink","slab","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfutures_util-b338ac678229cb6f.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tokio@1.24.2","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.24.2/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"tokio","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.24.2/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["bytes","default","fs","full","io-std","io-util","libc","macros","memchr","mio","net","num_cpus","parking_lot","process","rt","rt-multi-thread","signal","signal-hook-registry","socket2","sync","time","tokio-macros"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtokio-1416b74877eb740c.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#httparse@1.8.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/httparse-1.8.0/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/httparse-1.8.0/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/httparse-dbf6f6b4230b80cc/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tinyvec@1.6.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tinyvec-1.6.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"tinyvec","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tinyvec-1.6.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","default","tinyvec_macros"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtinyvec-d5552827c4f69bf9.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#native-tls@0.2.10","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/native-tls-51e41408421f3e99/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tempfile@3.3.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tempfile-3.3.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"tempfile","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tempfile-3.3.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtempfile-03c3bdc8d2e00595.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.6","linked_libs":[],"linked_paths":[],"cfgs":["relaxed_coherence"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/generic-array-351fb3b13c51d4bb/out"} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#serde@1.0.145","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/serde-0dd8d28f4238267a/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#typenum@1.15.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/typenum-1.15.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"typenum","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/typenum-1.15.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtypenum-1f5ac9f7ceccc491.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#security-framework@2.7.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/security-framework-2.7.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"security_framework","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/security-framework-2.7.0/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["OSX_10_9","default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsecurity_framework-6b8cceb3ba310c99.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#openssl-src@300.4.1+3.4.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-src-300.4.1+3.4.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"openssl_src","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-src-300.4.1+3.4.0/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","legacy"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libopenssl_src-4c44d86109dbc880.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libopenssl_src-4c44d86109dbc880.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#unicase@2.6.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicase-2.6.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"unicase","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicase-2.6.0/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libunicase-5029c78322567a92.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libunicase-5029c78322567a92.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.2.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/percent-encoding-2.2.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"percent_encoding","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/percent-encoding-2.2.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libpercent_encoding-86341883ed6efd0e.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.25","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pkg-config-0.3.25/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"pkg_config","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pkg-config-0.3.25/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libpkg_config-638f71ef8a8340cd.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libpkg_config-638f71ef8a8340cd.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.4","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-util-0.7.4/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"tokio_util","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-util-0.7.4/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["codec","default","io","tracing"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtokio_util-bf0b2d861fa180c1.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#httparse@1.8.0","linked_libs":[],"linked_paths":[],"cfgs":["httparse_simd"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/httparse-76658a3a49066b02/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#vcpkg@0.2.15","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/vcpkg-0.2.15/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"vcpkg","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/vcpkg-0.2.15/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libvcpkg-6db20e6761ed8cc8.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libvcpkg-6db20e6761ed8cc8.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#try-lock@0.2.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/try-lock-0.2.3/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"try_lock","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/try-lock-0.2.3/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtry_lock-611183c770850547.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#native-tls@0.2.10","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/native-tls-0.2.10/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"native_tls","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/native-tls-0.2.10/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libnative_tls-80df3962f140b589.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.6","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/generic-array-0.14.6/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"generic_array","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/generic-array-0.14.6/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["more_lengths"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libgeneric_array-155e14b3cb36db88.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.1.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/form_urlencoded-1.1.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"form_urlencoded","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/form_urlencoded-1.1.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":false},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libform_urlencoded-a407d382e15044d6.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#unicode-normalization@0.1.22","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicode-normalization-0.1.22/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"unicode_normalization","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicode-normalization-0.1.22/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libunicode_normalization-cd3c33b54894b16a.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#serde@1.0.145","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde-1.0.145/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"serde","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde-1.0.145/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libserde-610c97213cf6cf0d.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#mime_guess@2.0.4","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mime_guess-2.0.4/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mime_guess-2.0.4/build.rs","edition":"2015","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/mime_guess-281019fcf3dfeddd/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.5","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/http-body-0.4.5/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"http_body","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/http-body-0.4.5/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libhttp_body-66f6331ec8a05ac5.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.11","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/ryu-1.0.11/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"ryu","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/ryu-1.0.11/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libryu-872095f6f721c953.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.2","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tower-service-0.3.2/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"tower_service","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tower-service-0.3.2/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtower_service-e2709496d8907d01.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.31","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/encoding_rs-0.8.31/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/encoding_rs-0.8.31/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/encoding_rs-3b4397d31ef47316/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#httparse@1.8.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/httparse-1.8.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"httparse","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/httparse-1.8.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libhttparse-c1f512f7a4e7e083.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.105","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-sys-0.9.105/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-main","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-sys-0.9.105/build/main.rs","edition":"2021","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["openssl-src","vendored"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/openssl-sys-a977df21ab5fbf89/build-script-main"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#h2@0.3.14","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/h2-0.3.14/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"h2","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/h2-0.3.14/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libh2-9271a9839adeb833.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#want@0.3.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/want-0.3.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"want","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/want-0.3.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libwant-0f14e802048a5c5c.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#httpdate@1.0.2","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/httpdate-1.0.2/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"httpdate","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/httpdate-1.0.2/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libhttpdate-313e7880436abe21.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/rand_core-0.6.4/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"rand_core","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/rand_core-0.6.4/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/librand_core-51ef06cb37a6a770.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/librand_core-51ef06cb37a6a770.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.86","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_json-1.0.86/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_json-1.0.86/build.rs","edition":"2018","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/serde_json-b84b7d007d33b14f/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#unicode-bidi@0.3.8","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicode-bidi-0.3.8/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"unicode_bidi","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicode-bidi-0.3.8/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","hardcoded-data","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libunicode_bidi-71fe5acf4a2bc77a.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#siphasher@0.3.10","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/siphasher-0.3.10/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"siphasher","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/siphasher-0.3.10/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsiphasher-b147283699de14e0.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsiphasher-b147283699de14e0.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.31","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/encoding_rs-13904bf6c37c11b2/out"} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#mime_guess@2.0.4","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/mime_guess-2e2b91ba7dc22a59/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#tokio-native-tls@0.3.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-native-tls-0.3.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"tokio_native_tls","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-native-tls-0.3.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtokio_native_tls-e3d1a2731361732b.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#unicase@2.6.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicase-2.6.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"unicase","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicase-2.6.0/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libunicase-907dabdbe393c89e.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.145","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_derive-1.0.145/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_derive-1.0.145/build.rs","edition":"2015","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/serde_derive-2abc8641717bd685/build-script-build"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.86","linked_libs":[],"linked_paths":[],"cfgs":["limb_width_64"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/serde_json-ef01d75326ef1254/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#hyper@0.14.20","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/hyper-0.14.20/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"hyper","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/hyper-0.14.20/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["client","h2","http1","http2","runtime","socket2","tcp"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libhyper-918fd40e9487d8f9.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.105","linked_libs":["static=ssl","static=crypto"],"linked_paths":["native=/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/openssl-sys-cc2c55a10b0b4458/out/openssl-build/install/lib"],"cfgs":["osslconf=\"OPENSSL_NO_IDEA\"","osslconf=\"OPENSSL_NO_CAMELLIA\"","osslconf=\"OPENSSL_NO_COMP\"","osslconf=\"OPENSSL_NO_SSL3_METHOD\"","osslconf=\"OPENSSL_NO_SEED\"","openssl","ossl340","ossl330","ossl320","ossl300","ossl101","ossl102","ossl102f","ossl102h","ossl110","ossl110f","ossl110g","ossl110h","ossl111","ossl111b","ossl111c","ossl111d"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/openssl-sys-cc2c55a10b0b4458/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#idna@0.3.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/idna-0.3.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"idna","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/idna-0.3.0/src/lib.rs","edition":"2018","doc":true,"doctest":false,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libidna-1d770ba5db220286.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/rand-0.8.5/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"rand","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/rand-0.8.5/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["small_rng"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/librand-fa408134de5126ab.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/librand-fa408134de5126ab.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#phf_shared@0.11.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/phf_shared-0.11.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"phf_shared","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/phf_shared-0.11.1/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libphf_shared-2aff3889e55bab21.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libphf_shared-2aff3889e55bab21.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#mime@0.3.16","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mime-0.3.16/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"mime","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mime-0.3.16/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libmime-2b2723846353a670.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.145","linked_libs":[],"linked_paths":[],"cfgs":[],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/serde_derive-dd8a9259f74d9228/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.31","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/encoding_rs-0.8.31/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"encoding_rs","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/encoding_rs-0.8.31/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libencoding_rs-ad8b7e0b5695638e.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#crypto-common@0.1.6","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/crypto-common-0.1.6/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"crypto_common","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/crypto-common-0.1.6/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libcrypto_common-a4d297843708739b.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#serde_urlencoded@0.7.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_urlencoded-0.7.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"serde_urlencoded","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_urlencoded-0.7.1/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":false},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libserde_urlencoded-e5701fd47b9ae8ac.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#block-buffer@0.10.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/block-buffer-0.10.3/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"block_buffer","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/block-buffer-0.10.3/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libblock_buffer-71de2ae197cf49e4.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#syn@2.0.98","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/syn-2.0.98/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"syn","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/syn-2.0.98/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["clone-impls","default","derive","full","parsing","printing","proc-macro"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsyn-f9edb74efaba38fe.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsyn-f9edb74efaba38fe.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#terminal_size@0.1.17","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/terminal_size-0.1.17/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"terminal_size","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/terminal_size-0.1.17/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libterminal_size-10f8b9fe54923faa.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#mime_guess@2.0.4","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mime_guess-2.0.4/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"mime_guess","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mime_guess-2.0.4/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libmime_guess-63b76e2d77f61d83.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.86","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_json-1.0.86/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"serde_json","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_json-1.0.86/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libserde_json-ff6068f9e792fe6b.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#hyper-tls@0.5.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/hyper-tls-0.5.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"hyper_tls","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/hyper-tls-0.5.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libhyper_tls-a19978cce575a2ef.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#phf_generator@0.11.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/phf_generator-0.11.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"phf_generator","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/phf_generator-0.11.1/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libphf_generator-2a3a7762e0cd4c2f.rlib","/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libphf_generator-2a3a7762e0cd4c2f.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#url@2.3.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/url-2.3.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"url","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/url-2.3.1/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/liburl-7a1121a4792a1868.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#ipnet@2.5.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/ipnet-2.5.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"ipnet","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/ipnet-2.5.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libipnet-39508cab361fb234.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#base64@0.13.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/base64-0.13.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"base64","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/base64-0.13.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libbase64-7980120a5c7c7401.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#siphasher@0.3.10","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/siphasher-0.3.10/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"siphasher","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/siphasher-0.3.10/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsiphasher-f2754feac5a35451.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.1.10","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicode-width-0.1.10/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"unicode_width","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unicode-width-0.1.10/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libunicode_width-bef3834b7ac642f2.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.70","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-0.10.70/Cargo.toml","target":{"kind":["custom-build"],"crate_types":["bin"],"name":"build-script-build","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-0.10.70/build.rs","edition":"2021","doc":false,"doctest":false,"test":false},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","vendored"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/openssl-f9825fcbdd1f06d6/build-script-build"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#os_str_bytes@6.3.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/os_str_bytes-6.3.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"os_str_bytes","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/os_str_bytes-6.3.0/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["raw_os_str"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libos_str_bytes-8fdf7d82b18287d2.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#either@1.8.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/either-1.8.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"either","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/either-1.8.0/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["use_std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libeither-b78bdb8f59edb343.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/foreign-types-shared-0.1.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"foreign_types_shared","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/foreign-types-shared-0.1.1/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libforeign_types_shared-9f47b612b0973c3c.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#openssl-macros@0.1.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-macros-0.1.1/Cargo.toml","target":{"kind":["proc-macro"],"crate_types":["proc-macro"],"name":"openssl_macros","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-macros-0.1.1/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libopenssl_macros-b31285524d6232d6.dylib"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#phf_shared@0.11.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/phf_shared-0.11.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"phf_shared","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/phf_shared-0.11.1/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":false},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libphf_shared-3a47f023b25a8654.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#itertools@0.10.5","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/itertools-0.10.5/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"itertools","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/itertools-0.10.5/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":false},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","use_alloc","use_std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libitertools-5073b9beec29f866.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#foreign-types@0.3.2","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/foreign-types-0.3.2/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"foreign_types","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/foreign-types-0.3.2/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libforeign_types-a86f15e182bb3ff5.rmeta"],"executable":null,"fresh":true} {"reason":"build-script-executed","package_id":"registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.70","linked_libs":[],"linked_paths":[],"cfgs":["osslconf=\"OPENSSL_NO_IDEA\"","osslconf=\"OPENSSL_NO_CAMELLIA\"","osslconf=\"OPENSSL_NO_COMP\"","osslconf=\"OPENSSL_NO_SSL3_METHOD\"","osslconf=\"OPENSSL_NO_SEED\"","ossl101","ossl102","ossl110","ossl110g","ossl110h","ossl111","ossl111d","ossl300","ossl310","ossl320","ossl330"],"env":[],"out_dir":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/build/openssl-29d4c3a4f09c7a10/out"} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#phf_macros@0.11.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/phf_macros-0.11.1/Cargo.toml","target":{"kind":["proc-macro"],"crate_types":["proc-macro"],"name":"phf_macros","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/phf_macros-0.11.1/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libphf_macros-2b4e68400a38677b.dylib"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#console@0.15.2","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/console-0.15.2/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"console","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/console-0.15.2/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["ansi-parsing","unicode-width"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libconsole-c3f81e193ef5611f.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#reqwest@0.11.12","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/reqwest-0.11.12/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"reqwest","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/reqwest-0.11.12/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["__tls","default","default-tls","hyper-tls","json","mime_guess","multipart","native-tls-crate","serde_json","stream","tokio-native-tls","tokio-util"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libreqwest-657ad9d52c3ac038.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#clap_lex@0.3.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/clap_lex-0.3.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"clap_lex","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/clap_lex-0.3.0/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libclap_lex-72e5c34bd116d544.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.145","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_derive-1.0.145/Cargo.toml","target":{"kind":["proc-macro"],"crate_types":["proc-macro"],"name":"serde_derive","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_derive-1.0.145/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":0,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libserde_derive-121e4b171e8327ac.dylib"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.105","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-sys-0.9.105/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"openssl_sys","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-sys-0.9.105/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["openssl-src","vendored"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libopenssl_sys-bb273ff9f8c4cfb6.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#digest@0.10.5","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/digest-0.10.5/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"digest","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/digest-0.10.5/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","block-buffer","core-api","default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libdigest-c78d1f0325ba8c6e.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures-executor@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-executor-0.3.24/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"futures_executor","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-executor-0.3.24/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfutures_executor-e9f0f3ec875d5c63.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#combine@4.6.6","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/combine-4.6.6/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"combine","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/combine-4.6.6/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","bytes","default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libcombine-64da968f2ccf3fa0.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#atty@0.2.14","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/atty-0.2.14/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"atty","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/atty-0.2.14/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libatty-75856e7aa7d163cd.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.2.5","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/cpufeatures-0.2.5/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"cpufeatures","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/cpufeatures-0.2.5/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libcpufeatures-427b026017125327.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#same-file@1.0.6","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/same-file-1.0.6/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"same_file","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/same-file-1.0.6/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsame_file-6f1ef61c7135d1cb.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#number_prefix@0.4.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/number_prefix-0.4.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"number_prefix","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/number_prefix-0.4.0/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libnumber_prefix-531fe2cfc1d66054.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#termcolor@1.1.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/termcolor-1.1.3/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"termcolor","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/termcolor-1.1.3/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtermcolor-1c185e20c5f8c915.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#strsim@0.10.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/strsim-0.10.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"strsim","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/strsim-0.10.0/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libstrsim-8915360a20606875.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#bitflags@2.8.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bitflags-2.8.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"bitflags","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bitflags-2.8.0/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libbitflags-4314bdafae61c42e.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#toml_edit@0.14.4","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/toml_edit-0.14.4/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"toml_edit","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/toml_edit-0.14.4/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libtoml_edit-db2a2a06ace1a3cd.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#fastly-api@1.0.0-beta.0","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/fastly-api-1.0.0-beta.0/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"fastly_api","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/fastly-api-1.0.0-beta.0/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfastly_api-7d2ad889a12000da.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#phf@0.11.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/phf-0.11.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"phf","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/phf-0.11.1/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":false},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","macros","phf_macros","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libphf-a8ed2766bc4a7aa1.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#futures@0.3.24","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-0.3.24/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"futures","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-0.3.24/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["alloc","async-await","default","executor","futures-executor","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libfutures-20c4e536a3dc90f0.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#simple-error@0.2.3","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/simple-error-0.2.3/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"simple_error","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/simple-error-0.2.3/src/lib.rs","edition":"2015","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsimple_error-536fd3cff8fc74fa.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.6","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/sha2-0.10.6/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"sha2","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/sha2-0.10.6/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","std"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libsha2-86d591b7436c54dc.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#indicatif@0.17.1","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/indicatif-0.17.1/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"indicatif","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/indicatif-0.17.1/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","unicode-width"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libindicatif-21c89e1334be5a7c.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#walkdir@2.3.2","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/walkdir-2.3.2/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"walkdir","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/walkdir-2.3.2/src/lib.rs","edition":"2018","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libwalkdir-160c19bbaef56868.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.70","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-0.10.70/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"openssl","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/openssl-0.10.70/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["default","vendored"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libopenssl-b8e686407f9c8aa5.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"registry+https://github.com/rust-lang/crates.io-index#clap@4.0.13","manifest_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/clap-4.0.13/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"clap","src_path":"/Users/zkat/.cargo/registry/src/index.crates.io-6f17d22bba15001f/clap-4.0.13/src/lib.rs","edition":"2021","doc":true,"doctest":true,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":["color","default","error-context","help","std","suggestions","usage"],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libclap-17817d23df85a006.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"path+file:///Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli#1.1.0","manifest_path":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/Cargo.toml","target":{"kind":["bin"],"crate_types":["bin"],"name":"compute-file-server-cli","src_path":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/src/main.rs","edition":"2021","doc":true,"doctest":false,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libcompute_file_server_cli-7fe6e195b2448dcc.rmeta"],"executable":null,"fresh":true} {"reason":"compiler-artifact","package_id":"path+file:///Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli#1.1.0","manifest_path":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/Cargo.toml","target":{"kind":["bin"],"crate_types":["bin"],"name":"compute-file-server-cli","src_path":"/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/src/main.rs","edition":"2021","doc":true,"doctest":false,"test":true},"profile":{"opt_level":"0","debuginfo":2,"debug_assertions":true,"overflow_checks":true,"test":true},"features":[],"filenames":["/Users/zkat/src/fastly/js-compute-runtime/compute-file-server-cli/target/debug/deps/libcompute_file_server_cli-3657abf82c3a412c.rmeta"],"executable":null,"fresh":true} {"reason":"build-finished","success":true} ================================================ FILE: test-d/backend.test-d.ts ================================================ /// import { Backend } from 'fastly:backend'; import { expectError, expectType } from 'tsd'; // Backend { expectError(Backend()); expectError(new Backend()); expectError(new Backend({ name: 'eu' })); expectType(new Backend({ target: 'www.example.com' })); expectType(new Backend({ name: 'eu', target: 'www.example.com' })); expectType( new Backend({ name: 'eu', target: 'www.example.com', hostOverride: 'example.com', }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', connectTimeout: 5000, }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', firstByteTimeout: 5000, }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', betweenBytesTimeout: 5000, }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', useSSL: true }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', dontPool: true }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', tlsMinVersion: 1.2 }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', tlsMaxVersion: 1.2 }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', certificateHostname: 'example.com', }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', caCertificate: '' }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', ciphers: 'DEFAULT' }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', sniHostname: 'example.com', }), ); const backend = new Backend({ name: 'eu', target: 'www.example.com' }); expectType(backend.toString()); } ================================================ FILE: test-d/cache-override.test-d.ts ================================================ /// import { CacheOverride } from 'fastly:cache-override'; import { expectType } from 'tsd'; // CacheOverride { expectType(new CacheOverride('none')); expectType(new CacheOverride('pass')); expectType(new CacheOverride('override')); expectType(new CacheOverride('none', { ttl: undefined })); expectType(new CacheOverride('none', { ttl: 1 })); expectType(new CacheOverride('none', { swr: undefined })); expectType(new CacheOverride('none', { swr: 1 })); expectType( new CacheOverride('none', { surrogateKey: undefined }), ); expectType( new CacheOverride('none', { surrogateKey: 'undefined' }), ); expectType(new CacheOverride('none', { pci: undefined })); expectType(new CacheOverride('none', { pci: true })); expectType(new CacheOverride('pass', {})); expectType(new CacheOverride('override', {})); const cacheOverride = new CacheOverride('none'); expectType<'none' | 'pass' | 'override'>(cacheOverride.mode); expectType(cacheOverride.pci); expectType(cacheOverride.ttl); expectType(cacheOverride.swr); expectType(cacheOverride.surrogateKey); } ================================================ FILE: test-d/compute.test-d.ts ================================================ /// import { vCpuTime, purgeSurrogateKey } from 'fastly:compute'; import { expectType } from 'tsd'; // Compute { expectType(vCpuTime()); expectType(purgeSurrogateKey('boo')); } ================================================ FILE: test-d/config-store.test-d.ts ================================================ /// import { ConfigStore } from 'fastly:config-store'; import { expectError, expectType } from 'tsd'; // ConfigStore { expectError(new ConfigStore()); expectError(ConfigStore('example')); expectError(ConfigStore()); expectType(new ConfigStore('example')); expectType<(key: string) => string | null>(new ConfigStore('example').get); } ================================================ FILE: test-d/dictionary.test-d.ts ================================================ /// import { Dictionary } from 'fastly:dictionary'; import { expectError, expectType } from 'tsd'; // Dictionary { expectError(new Dictionary()); expectError(Dictionary('example')); expectError(Dictionary()); expectType(new Dictionary('example')); expectType<(key: string) => string | null>(new Dictionary('example').get); } ================================================ FILE: test-d/env.test-d.ts ================================================ /// import { env } from 'fastly:env'; import { expectType } from 'tsd'; expectType<(key: string) => string>(env); ================================================ FILE: test-d/experimental.test-d.ts ================================================ /// import { setBaseURL, setDefaultBackend, enableDebugLogging, includeBytes, allowDynamicBackends, } from 'fastly:experimental'; import { expectType } from 'tsd'; expectType<(path: string) => Uint8Array>(includeBytes); expectType<(enabled: boolean) => void>(enableDebugLogging); expectType<(base: URL | null | undefined) => void>(setBaseURL); expectType<(backend: string) => void>(setDefaultBackend); expectType<{ (enabled: boolean): void; (defaultConfig: { connectTimeout?: number | undefined; firstByteTimeout?: number | undefined; betweenBytesTimeout?: number | undefined; }): void; }>(allowDynamicBackends); ================================================ FILE: test-d/fanout.test-d.ts ================================================ /// import { createFanoutHandoff } from 'fastly:fanout'; import { expectType } from 'tsd'; expectType<(request: Request, backend: string) => Response>( createFanoutHandoff, ); ================================================ FILE: test-d/geolocation.test-d.ts ================================================ /// import { Geolocation, getGeolocationForIpAddress } from 'fastly:geolocation'; import { expectType } from 'tsd'; expectType<(address: string) => Geolocation | null>(getGeolocationForIpAddress); const geo = {} as Geolocation; expectType(geo.as_name); expectType(geo.as_number); expectType(geo.area_code); expectType(geo.city); expectType(geo.conn_speed); expectType(geo.conn_type); expectType(geo.continent); expectType(geo.country_code); expectType(geo.country_code3); expectType(geo.gmt_offset); expectType(geo.latitude); expectType(geo.longitude); expectType(geo.metro_code); expectType(geo.postal_code); expectType(geo.proxy_description); expectType(geo.proxy_type); expectType(geo.region); expectType(geo.utc_offset); ================================================ FILE: test-d/globals.test-d.ts ================================================ /// import { expectError, expectType } from 'tsd'; // atob { expectError(atob()); expectError(atob(1)); expectError(atob({})); expectError(atob([])); expectError(atob(true)); expectError(atob(Symbol())); expectError(atob(function () {})); expectType(atob('')); } // btoa { expectError(btoa()); expectError(btoa(1)); expectError(btoa({})); expectError(btoa([])); expectError(btoa(true)); expectError(btoa(Symbol())); expectError(btoa(function () {})); expectType(btoa('')); } // setTimeout { expectError(setTimeout()); expectError(setTimeout(null)); expectError(setTimeout(1)); expectError(setTimeout({})); expectError(setTimeout([])); expectError(setTimeout(true)); expectError(setTimeout(Symbol())); expectType(setTimeout(() => {})); expectType(setTimeout(() => {}, 1000)); expectError(setTimeout(() => {}, 1000, 1)); expectType(setTimeout((x) => {}, 1000, 1)); expectError(setTimeout((x) => {}, 1000, 1, 2)); expectType(setTimeout((x, y) => {}, 1000, 1, 2)); } // clearTimeout { expectError(clearTimeout(null)); expectError(clearTimeout({})); expectError(clearTimeout([])); expectError(clearTimeout(true)); expectError(clearTimeout(Symbol())); expectType(clearTimeout()); expectType(clearTimeout(1)); } // setInterval { expectError(setInterval()); expectError(setInterval(null)); expectError(setInterval(1)); expectError(setInterval({})); expectError(setInterval([])); expectError(setInterval(true)); expectError(setInterval(Symbol())); expectType(setInterval(() => {})); expectType(setInterval(() => {}, 1000)); expectError(setInterval(() => {}, 1000, 1)); expectType(setInterval((x) => {}, 1000, 1)); expectError(setInterval((x) => {}, 1000, 1, 2)); expectType(setInterval((x, y) => {}, 1000, 1, 2)); } // clearInterval { expectError(clearInterval(null)); expectError(clearInterval({})); expectError(clearInterval([])); expectError(clearInterval(true)); expectError(clearInterval(Symbol())); expectType(clearInterval()); expectType(clearInterval(1)); } // Backend { expectError(Backend()); expectError(new Backend()); expectError(new Backend({ name: 'eu' })); expectType(new Backend({ target: 'www.example.com' })); expectType(new Backend({ name: 'eu', target: 'www.example.com' })); expectType( new Backend({ name: 'eu', target: 'www.example.com', hostOverride: 'example.com', }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', connectTimeout: 5000, }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', firstByteTimeout: 5000, }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', betweenBytesTimeout: 5000, }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', useSSL: true }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', tlsMinVersion: 1.2 }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', tlsMaxVersion: 1.2 }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', certificateHostname: 'example.com', }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', caCertificate: '' }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', ciphers: 'DEFAULT' }), ); expectType( new Backend({ name: 'eu', target: 'www.example.com', sniHostname: 'example.com', }), ); const backend = new Backend({ name: 'eu', target: 'www.example.com' }); expectType(backend.toString()); } // KVStore { expectError(KVStore()); expectError(KVStore('secrets')); expectType(new KVStore('secrets')); expectError(new KVStore('secrets', {})); const store = new KVStore('secrets'); expectError(store.get()); expectError(store.get(1)); expectType>(store.get('cat')); expectError(store.put()); expectError(store.put('cat')); expectError(store.put('cat', 1)); expectType>(store.put('cat', 'Aki')); } // KVStoreEntry { const entry = {} as KVStoreEntry; expectType>(entry.body); expectType(entry.bodyUsed); expectType>(entry.arrayBuffer()); expectType>(entry.json()); expectType>(entry.text()); } // onfetch { expectType(onfetch); } // addEventListener { // Both parameters are required: // - The first parameter _has_ to be 'fetch' // - The second parameter _has_ to be a function expectError(addEventListener('magic')); expectError(addEventListener('fetch')); expectError(addEventListener('magic', () => {})); expectType(addEventListener('fetch', () => {})); expectType( addEventListener('fetch', (event) => { expectType(event); }), ); } // FetchEventListener { let listener = (() => {}) as FetchEventListener; expectType<(event: FetchEvent) => any>(listener); } // FetchEvent { const event = {} as FetchEvent; expectType(event.client); expectType(event.server); expectType(event.request); expectType<(response: Response | PromiseLike) => void>( event.respondWith, ); expectType<(promise: Promise) => void>(event.waitUntil); } // CacheOverrideMode { const cacheOverride = {} as CacheOverrideMode; expectType<'none' | 'pass' | 'override'>(cacheOverride); } // CacheOverride { expectType(new CacheOverride('none')); expectType(new CacheOverride('pass')); expectType(new CacheOverride('override')); expectType(new CacheOverride('none', { ttl: undefined })); expectType(new CacheOverride('none', { ttl: 1 })); expectType(new CacheOverride('none', { swr: undefined })); expectType(new CacheOverride('none', { swr: 1 })); expectType( new CacheOverride('none', { surrogateKey: undefined }), ); expectType( new CacheOverride('none', { surrogateKey: 'undefined' }), ); expectType(new CacheOverride('none', { pci: undefined })); expectType(new CacheOverride('none', { pci: true })); expectType(new CacheOverride('pass', {})); expectType(new CacheOverride('override', {})); const cacheOverride = new CacheOverride('none'); expectType(cacheOverride.mode); expectType(cacheOverride.pci); expectType(cacheOverride.ttl); expectType(cacheOverride.swr); expectType(cacheOverride.surrogateKey); } // CacheOverrideInit { const cacheOverrideInit = {} as CacheOverrideInit; expectType(cacheOverrideInit.pci); expectType(cacheOverrideInit.ttl); expectType(cacheOverrideInit.swr); expectType(cacheOverrideInit.surrogateKey); } // ClientInfo { const client = {} as ClientInfo; expectType(client.requestId); expectType(client.address); expectType(client.geo); expectType(client.tlsJA3MD5); expectType(client.tlsCipherOpensslName); expectType(client.tlsProtocol); expectType(client.tlsClientCertificate); expectType(client.tlsClientHello); // They are readonly properties expectError((client.requestId = '')); expectError((client.address = '')); expectError((client.geo = {} as Geolocation)); expectError((client.tlsJA3MD5 = '')); expectError((client.tlsCipherOpensslName = '')); expectError((client.tlsProtocol = '')); expectError((client.tlsClientCertificate = '')); expectError((client.tlsClientHello = '')); } // ServerInfo { const server = {} as ServerInfo; expectType(server.address); // They are readonly properties expectError((server.address = '')); } // ConfigStore { expectError(new ConfigStore()); expectError(ConfigStore('example')); expectError(ConfigStore()); expectType(new ConfigStore('example')); expectType<(key: string) => string>(new ConfigStore('example').get); } // Dictionary { expectError(new Dictionary()); expectError(Dictionary('example')); expectError(Dictionary()); expectType(new Dictionary('example')); expectType<(key: string) => string>(new Dictionary('example').get); } // Geolocation { const geo = {} as Geolocation; expectType(geo.as_name); expectType(geo.as_number); expectType(geo.area_code); expectType(geo.city); expectType(geo.conn_speed); expectType(geo.conn_type); expectType(geo.continent); expectType(geo.country_code); expectType(geo.country_code3); expectType(geo.gmt_offset); expectType(geo.latitude); expectType(geo.longitude); expectType(geo.metro_code); expectType(geo.postal_code); expectType(geo.proxy_description); expectType(geo.proxy_type); expectType(geo.region); expectType(geo.utc_offset); } // URL { expectError(new URL()); expectError(URL('example')); expectError(URL('example', 'base')); expectError(URL('example', new URL('example'))); expectError(URL()); expectType(new URL('example')); expectType(new URL('example', 'base')); expectType(new URL('example', new URL('example'))); expectType(new URL('').href); new URL('').href = 'example'; expectError((new URL('').href = 7)); expectType(new URL('').origin); expectError((new URL('').origin = 'example')); expectType(new URL('').protocol); new URL('').protocol = '7'; expectError((new URL('').protocol = 7)); expectType(new URL('').username); new URL('').username = '7'; expectError((new URL('').username = 7)); expectType(new URL('').password); new URL('').password = '7'; expectError((new URL('').password = 7)); expectType(new URL('').host); new URL('').host = '7'; expectError((new URL('').host = 7)); expectType(new URL('').hostname); new URL('').hostname = '7'; expectError((new URL('').hostname = 7)); expectType(new URL('').port); new URL('').port = '7'; expectError((new URL('').port = 7)); expectType(new URL('').pathname); new URL('').pathname = '7'; expectError((new URL('').pathname = 7)); expectType(new URL('').search); new URL('').search = '7'; expectError((new URL('').search = 7)); expectType(new URL('').searchParams); expectType(new URL('').hash); new URL('').hash = '7'; expectError((new URL('').hash = 7)); } // URLSearchParams { expectError(URLSearchParams()); expectError(new URLSearchParams(false)); expectType(new URLSearchParams([])); expectType( new URLSearchParams({ [Symbol.iterator]: function* () { yield ['', '']; return; }, }), ); expectType(new URLSearchParams({})); expectType(new URLSearchParams({ a: 'a' })); expectType(new URLSearchParams('')); const searchParams = new URLSearchParams(); expectType<(name: string, value: string) => void>(searchParams.append); expectType<(name: string) => void>(searchParams.delete); expectType<(name: string) => string | null>(searchParams.get); expectType<(name: string) => string[]>(searchParams.getAll); expectType<(name: string) => boolean>(searchParams.has); expectType<(name: string, value: string) => void>(searchParams.set); expectType<() => void>(searchParams.sort); expectType<() => IterableIterator>(searchParams.keys); expectType<() => IterableIterator>(searchParams.values); expectType<() => IterableIterator<[name: string, value: string]>>( searchParams.entries, ); expectType< ( callback: ( this: THIS_ARG, value: string, name: string, searchParams: URLSearchParams, ) => void, thisArg?: THIS_ARG, ) => void >(searchParams.forEach); expectType<'URLSearchParams'>(searchParams[Symbol.toStringTag]); expectError((searchParams[Symbol.toStringTag] = 'f')); expectType>( searchParams[Symbol.iterator](), ); } // console { expectType(console); expectType<(...objects: any[]) => void>(console.log); expectType<(...objects: any[]) => void>(console.debug); expectType<(...objects: any[]) => void>(console.info); expectType<(...objects: any[]) => void>(console.warn); expectType<(...objects: any[]) => void>(console.error); } // TextDecoder { expectError(TextDecoder()); expectError(new TextDecoder('')); const decoder = new TextDecoder(); expectType(decoder); expectType<(input?: ArrayBuffer | ArrayBufferView) => string>(decoder.decode); expectType<'utf-8'>(decoder.encoding); expectError((decoder.encoding = 'd')); } // TextEncoder { expectError(TextEncoder()); expectError(new TextEncoder('')); const encoder = new TextEncoder(); expectType(encoder); expectType<(input?: string) => Uint8Array>(encoder.encode); expectType<'utf-8'>(encoder.encoding); expectError((encoder.encoding = 'd')); } // Logger { const logger = {} as Logger; expectType<(message: any) => void>(logger.log); } // Fastly { expectType(fastly); expectType(fastly.baseURL); fastly.baseURL = new URL('.'); fastly.baseURL = null; fastly.baseURL = undefined; expectType(fastly.defaultBackend); fastly.defaultBackend = '.'; expectType<(key: string) => string>(fastly.env.get); expectType<(endpoint: string) => Logger>(fastly.getLogger); expectType<(enabled: boolean) => void>(fastly.enableDebugLogging); expectType<(address: string) => Geolocation>( fastly.getGeolocationForIpAddress, ); expectType<(path: string) => Uint8Array>(fastly.includeBytes); } // CompressionStream { expectError(CompressionStream()); expectError(new CompressionStream('')); let stream = new CompressionStream('deflate'); stream = new CompressionStream('deflate-raw'); stream = new CompressionStream('gzip'); expectType>>(stream.readable); expectError((stream.readable = 'd')); expectType>>(stream.writable); expectError((stream.writable = 'd')); } // DecompressionStream { expectError(DecompressionStream()); expectError(new DecompressionStream('')); let stream = new DecompressionStream('deflate'); stream = new DecompressionStream('deflate-raw'); stream = new DecompressionStream('gzip'); expectType>>(stream.readable); expectError((stream.readable = 'd')); expectType>>(stream.writable); expectError((stream.writable = 'd')); } ================================================ FILE: test-d/image-optimizer.test-d.ts ================================================ /// import { ImageOptimizerOptions, optionsToQueryString, } from 'fastly:image-optimizer'; import { expectType } from 'tsd'; expectType<(options: ImageOptimizerOptions) => string>(optionsToQueryString); ================================================ FILE: test-d/kv-store.test-d.ts ================================================ /// import { KVStore, KVStoreEntry } from 'fastly:kv-store'; import { expectError, expectType } from 'tsd'; // KVStore { expectError(KVStore()); expectError(KVStore('secrets')); expectType(new KVStore('secrets')); expectError(new KVStore('secrets', {})); const store = new KVStore('secrets'); expectError(store.get()); expectError(store.get(1)); expectType>(store.get('cat')); expectError(store.put()); expectError(store.put('cat')); expectError(store.put('cat', 1)); expectType>(store.put('cat', 'Aki')); } // KVStoreEntry { const entry = {} as KVStoreEntry; expectType>(entry.body); expectType(entry.bodyUsed); expectType>(entry.arrayBuffer()); expectType>(entry.json()); expectType>(entry.text()); } ================================================ FILE: test-d/logger.test-d.ts ================================================ /// import { Logger } from 'fastly:logger'; import { expectError, expectType } from 'tsd'; expectError(new Logger()); expectError(Logger('example')); expectError(Logger()); expectType(new Logger('example')); expectType<(message: any) => void>(new Logger('example').log); ================================================ FILE: test-d/shielding.test-d.ts ================================================ /// import { Shield } from 'fastly:shielding'; import { expectType, expectError } from 'tsd'; // Shielding { expectError(Shield()); expectType(new Shield('dub-dublin-ie')); } ================================================ FILE: test-d/websocket.test-d.ts ================================================ /// import { createWebsocketHandoff } from 'fastly:websocket'; import { expectType } from 'tsd'; expectType<(request: Request, backend: string) => Response>( createWebsocketHandoff, ); ================================================ FILE: tests/wpt-harness/build-wpt-runtime.sh ================================================ #!/usr/bin/env bash set -euo pipefail script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" inputs=( "${script_dir}/pre-harness.js" "${script_dir}/wpt/resources/testharness.js" "${script_dir}/post-harness.js" ) cat "${inputs[@]}" > "${script_dir}/wpt-test-runner.js" node "${script_dir}/../../dist/cli/js-compute-runtime-cli.js" "${script_dir}/wpt-test-runner.js" "$@" wpt-runtime.wasm ================================================ FILE: tests/wpt-harness/expectations/FileAPI/blob/Blob-array-buffer.any.js.json ================================================ { "Blob.arrayBuffer()": { "status": "PASS" }, "Blob.arrayBuffer() empty Blob data": { "status": "PASS" }, "Blob.arrayBuffer() non-ascii input": { "status": "PASS" }, "Blob.arrayBuffer() non-unicode input": { "status": "PASS" }, "Blob.arrayBuffer() concurrent reads": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/FileAPI/blob/Blob-bytes.any.js.json ================================================ { "Blob.bytes()": { "status": "PASS" }, "Blob.bytes() empty Blob data": { "status": "PASS" }, "Blob.bytes() non-ascii input": { "status": "PASS" }, "Blob.bytes() non-unicode input": { "status": "PASS" }, "Blob.bytes() concurrent reads": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/FileAPI/blob/Blob-constructor-dom.window.js.json ================================================ { "Passing platform objects for blobParts should throw a TypeError.": { "status": "FAIL" }, "A platform object that supports indexed properties should be treated as a sequence for the blobParts argument (overwritten 'length'.)": { "status": "FAIL" }, "Passing an platform object that supports indexed properties as the blobParts array should work (select).": { "status": "FAIL" }, "Passing an platform object that supports indexed properties as the blobParts array should work (attributes).": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/FileAPI/blob/Blob-constructor.any.js.json ================================================ { "Blob interface object": { "status": "PASS" }, "Blob constructor with no arguments": { "status": "PASS" }, "Blob constructor with no arguments, without 'new'": { "status": "PASS" }, "Blob constructor without brackets": { "status": "PASS" }, "Blob constructor with undefined as first argument": { "status": "PASS" }, "Passing non-objects, Dates and RegExps for blobParts should throw a TypeError.": { "status": "PASS" }, "A plain object with @@iterator should be treated as a sequence for the blobParts argument.": { "status": "PASS" }, "A plain object with custom @@iterator should be treated as a sequence for the blobParts argument.": { "status": "PASS" }, "A plain object with @@iterator and a length property should be treated as a sequence for the blobParts argument.": { "status": "PASS" }, "A String object should be treated as a sequence for the blobParts argument.": { "status": "PASS" }, "A Uint8Array object should be treated as a sequence for the blobParts argument.": { "status": "PASS" }, "The length getter should be invoked and any exceptions should be propagated.": { "status": "PASS" }, "ToUint32 should be applied to the length and any exceptions should be propagated.": { "status": "PASS" }, "Getters and value conversions should happen in order until an exception is thrown.": { "status": "PASS" }, "ToString should be called on elements of the blobParts array and any exceptions should be propagated.": { "status": "PASS" }, "Changes to the blobParts array should be reflected in the returned Blob (pop).": { "status": "PASS" }, "Changes to the blobParts array should be reflected in the returned Blob (unshift).": { "status": "PASS" }, "ToString should be called on elements of the blobParts array.": { "status": "PASS" }, "ArrayBuffer elements of the blobParts array should be supported.": { "status": "PASS" }, "Passing typed arrays as elements of the blobParts array should work.": { "status": "PASS" }, "Passing a Float16Array as element of the blobParts array should work.": { "status": "PASS" }, "Passing a Float64Array as element of the blobParts array should work.": { "status": "PASS" }, "Passing BigInt typed arrays as elements of the blobParts array should work.": { "status": "PASS" }, "Passing a FrozenArray as the blobParts array should work (FrozenArray).": { "status": "FAIL" }, "Array with two blobs": { "status": "PASS" }, "Array with two buffers": { "status": "PASS" }, "Array with two bufferviews": { "status": "PASS" }, "Array with mixed types": { "status": "PASS" }, "options properties should be accessed in lexicographic order.": { "status": "PASS" }, "Arguments should be evaluated from left to right.": { "status": "PASS" }, "Passing null (index 0) for options should use the defaults.": { "status": "PASS" }, "Passing null (index 0) for options should use the defaults (with newlines).": { "status": "PASS" }, "Passing undefined (index 1) for options should use the defaults.": { "status": "PASS" }, "Passing undefined (index 1) for options should use the defaults (with newlines).": { "status": "PASS" }, "Passing object \"[object Object]\" (index 2) for options should use the defaults.": { "status": "PASS" }, "Passing object \"[object Object]\" (index 2) for options should use the defaults (with newlines).": { "status": "PASS" }, "Passing object \"[object Object]\" (index 3) for options should use the defaults.": { "status": "PASS" }, "Passing object \"[object Object]\" (index 3) for options should use the defaults (with newlines).": { "status": "PASS" }, "Passing object \"/regex/\" (index 4) for options should use the defaults.": { "status": "PASS" }, "Passing object \"/regex/\" (index 4) for options should use the defaults (with newlines).": { "status": "PASS" }, "Passing function \"function() {}\" (index 5) for options should use the defaults.": { "status": "PASS" }, "Passing function \"function() {}\" (index 5) for options should use the defaults (with newlines).": { "status": "PASS" }, "Passing 123 for options should throw": { "status": "PASS" }, "Passing 123.4 for options should throw": { "status": "PASS" }, "Passing true for options should throw": { "status": "PASS" }, "Passing \"abc\" for options should throw": { "status": "PASS" }, "Blob with type \"\"": { "status": "PASS" }, "Blob with type \"a\"": { "status": "PASS" }, "Blob with type \"A\"": { "status": "PASS" }, "Blob with type \"text/html\"": { "status": "PASS" }, "Blob with type \"TEXT/HTML\"": { "status": "PASS" }, "Blob with type \"text/plain;charset=utf-8\"": { "status": "PASS" }, "Blob with type \"å\"": { "status": "PASS" }, "Blob with type \"𐑾\"": { "status": "PASS" }, "Blob with type \" image/gif \"": { "status": "PASS" }, "Blob with type \"\\timage/gif\\t\"": { "status": "PASS" }, "Blob with type \"image/gif;\"": { "status": "PASS" }, "Blob with type \"İmage/gif\"": { "status": "PASS" }, "Blob with type \"ımage/gif\"": { "status": "PASS" }, "Blob with type \"image/gif\\0\"": { "status": "PASS" }, "Blob with type \"unknown/unknown\"": { "status": "PASS" }, "Blob with type \"text/plain\"": { "status": "PASS" }, "Blob with type \"image/png\"": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/FileAPI/blob/Blob-slice-overflow.any.js.json ================================================ { "slice start is negative, relativeStart will be max((size + start), 0)": { "status": "PASS" }, "slice start is greater than blob size, relativeStart will be min(start, size)": { "status": "PASS" }, "slice end is negative, relativeEnd will be max((size + end), 0)": { "status": "PASS" }, "slice end is greater than blob size, relativeEnd will be min(end, size)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/FileAPI/blob/Blob-slice.any.js.json ================================================ { "no-argument Blob slice": { "status": "PASS" }, "Slices": { "status": "PASS" }, "blob1.": { "status": "PASS" }, "blob2.": { "status": "PASS" }, "null type Blob slice": { "status": "PASS" }, "undefined type Blob slice": { "status": "PASS" }, "no type Blob slice": { "status": "PASS" }, "Slicing test (0,0).": { "status": "PASS" }, "Slicing test: slice (0,0).": { "status": "PASS" }, "Slicing test (0,1).": { "status": "PASS" }, "Slicing test: slice (0,1).": { "status": "PASS" }, "Slicing test (0,2).": { "status": "PASS" }, "Slicing test: slice (0,2).": { "status": "PASS" }, "Slicing test (0,3).": { "status": "PASS" }, "Slicing test: slice (0,3).": { "status": "PASS" }, "Slicing test (0,4).": { "status": "PASS" }, "Slicing test: slice (0,4).": { "status": "PASS" }, "Slicing test (0,5).": { "status": "PASS" }, "Slicing test: slice (0,5).": { "status": "PASS" }, "Slicing test (0,6).": { "status": "PASS" }, "Slicing test: slice (0,6).": { "status": "PASS" }, "Slicing test (0,7).": { "status": "PASS" }, "Slicing test: slice (0,7).": { "status": "PASS" }, "Slicing test (0,8).": { "status": "PASS" }, "Slicing test: slice (0,8).": { "status": "PASS" }, "Slicing test (1,0).": { "status": "PASS" }, "Slicing test: slice (1,0).": { "status": "PASS" }, "Slicing test (1,1).": { "status": "PASS" }, "Slicing test: slice (1,1).": { "status": "PASS" }, "Slicing test (1,2).": { "status": "PASS" }, "Slicing test: slice (1,2).": { "status": "PASS" }, "Slicing test (1,3).": { "status": "PASS" }, "Slicing test: slice (1,3).": { "status": "PASS" }, "Slicing test (1,4).": { "status": "PASS" }, "Slicing test: slice (1,4).": { "status": "PASS" }, "Slicing test (1,5).": { "status": "PASS" }, "Slicing test: slice (1,5).": { "status": "PASS" }, "Slicing test (1,6).": { "status": "PASS" }, "Slicing test: slice (1,6).": { "status": "PASS" }, "Slicing test (1,7).": { "status": "PASS" }, "Slicing test: slice (1,7).": { "status": "PASS" }, "Slicing test (2,0).": { "status": "PASS" }, "Slicing test: slice (2,0).": { "status": "PASS" }, "Slicing test (2,1).": { "status": "PASS" }, "Slicing test: slice (2,1).": { "status": "PASS" }, "Slicing test (2,2).": { "status": "PASS" }, "Slicing test: slice (2,2).": { "status": "PASS" }, "Slicing test (2,3).": { "status": "PASS" }, "Slicing test: slice (2,3).": { "status": "PASS" }, "Slicing test (3,0).": { "status": "PASS" }, "Slicing test: slice (3,0).": { "status": "PASS" }, "Slicing test (3,1).": { "status": "PASS" }, "Slicing test: slice (3,1).": { "status": "PASS" }, "Slicing test (3,2).": { "status": "PASS" }, "Slicing test: slice (3,2).": { "status": "PASS" }, "Slicing test (3,3).": { "status": "PASS" }, "Slicing test: slice (3,3).": { "status": "PASS" }, "Slicing test (3,4).": { "status": "PASS" }, "Slicing test: slice (3,4).": { "status": "PASS" }, "Slicing test (3,5).": { "status": "PASS" }, "Slicing test: slice (3,5).": { "status": "PASS" }, "Slicing test (4,0).": { "status": "PASS" }, "Slicing test: slice (4,0).": { "status": "PASS" }, "Slicing test (4,1).": { "status": "PASS" }, "Slicing test: slice (4,1).": { "status": "PASS" }, "Slicing test (4,2).": { "status": "PASS" }, "Slicing test: slice (4,2).": { "status": "PASS" }, "Slicing test (4,3).": { "status": "PASS" }, "Slicing test: slice (4,3).": { "status": "PASS" }, "Slicing test (4,4).": { "status": "PASS" }, "Slicing test: slice (4,4).": { "status": "PASS" }, "Slicing test (5,0).": { "status": "PASS" }, "Slicing test: slice (5,0).": { "status": "PASS" }, "Slicing test (5,1).": { "status": "PASS" }, "Slicing test: slice (5,1).": { "status": "PASS" }, "Slicing test (5,2).": { "status": "PASS" }, "Slicing test: slice (5,2).": { "status": "PASS" }, "Slicing test (5,3).": { "status": "PASS" }, "Slicing test: slice (5,3).": { "status": "PASS" }, "Slicing test (6,0).": { "status": "PASS" }, "Slicing test: slice (6,0).": { "status": "PASS" }, "Slicing test (6,1).": { "status": "PASS" }, "Slicing test: slice (6,1).": { "status": "PASS" }, "Slicing test (6,2).": { "status": "PASS" }, "Slicing test: slice (6,2).": { "status": "PASS" }, "Slicing test (7,0).": { "status": "PASS" }, "Slicing test: slice (7,0).": { "status": "PASS" }, "Slicing test (7,1).": { "status": "PASS" }, "Slicing test: slice (7,1).": { "status": "PASS" }, "Slicing test (7,2).": { "status": "PASS" }, "Slicing test: slice (7,2).": { "status": "PASS" }, "Slicing test (7,3).": { "status": "PASS" }, "Slicing test: slice (7,3).": { "status": "PASS" }, "Slicing test (8,0).": { "status": "PASS" }, "Slicing test: slice (8,0).": { "status": "PASS" }, "Slicing test (8,1).": { "status": "PASS" }, "Slicing test: slice (8,1).": { "status": "PASS" }, "Slicing test (8,2).": { "status": "PASS" }, "Slicing test: slice (8,2).": { "status": "PASS" }, "Slicing test (8,3).": { "status": "PASS" }, "Slicing test: slice (8,3).": { "status": "PASS" }, "Invalid contentType (\"ÿ\")": { "status": "PASS" }, "Invalid contentType (\"te\\txt/plain\")": { "status": "PASS" }, "Invalid contentType (\"te\\0xt/plain\")": { "status": "PASS" }, "Invalid contentType (\"te\\x1fxt/plain\")": { "status": "PASS" }, "Invalid contentType (\"text/plain\")": { "status": "PASS" }, "Valid contentType (\"te(xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te)xt/plain\")": { "status": "PASS" }, "Valid contentType (\"text/plain\")": { "status": "PASS" }, "Valid contentType (\"te@xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te,xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te;xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te:xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te\\\\xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te\\\"xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te/xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te[xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te]xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te?xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te=xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te{xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te}xt/plain\")": { "status": "PASS" }, "Valid contentType (\"te xt/plain\")": { "status": "PASS" }, "Valid contentType (\"TEXT/PLAIN\")": { "status": "PASS" }, "Valid contentType (\"text/plain;charset = UTF-8\")": { "status": "PASS" }, "Valid contentType (\"text/plain;charset=UTF-8\")": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/FileAPI/blob/Blob-stream.any.js.json ================================================ { "Blob.stream()": { "status": "PASS" }, "Blob.stream() empty Blob": { "status": "PASS" }, "Blob.stream() non-unicode input": { "status": "PASS" }, "Blob.stream() garbage collection of blob shouldn't break stream consumption": { "status": "PASS" }, "Blob.stream() garbage collection of stream shouldn't break stream consumption": { "status": "PASS" }, "Reading Blob.stream() with BYOB reader": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/FileAPI/blob/Blob-text.any.js.json ================================================ { "Blob.text()": { "status": "PASS" }, "Blob.text() empty blob data": { "status": "PASS" }, "Blob.text() multi-element array in constructor": { "status": "PASS" }, "Blob.text() non-unicode": { "status": "PASS" }, "Blob.text() different charset param in type option": { "status": "PASS" }, "Blob.text() different charset param with non-ascii input": { "status": "PASS" }, "Blob.text() invalid utf-8 input": { "status": "PASS" }, "Blob.text() concurrent reads": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/FileAPI/file/File-constructor.any.js.json ================================================ { "File interface object exists": { "status": "PASS" }, "Required arguments": { "status": "PASS" }, "empty fileBits": { "status": "PASS" }, "DOMString fileBits": { "status": "PASS" }, "Unicode DOMString fileBits": { "status": "PASS" }, "String object fileBits": { "status": "PASS" }, "Empty Blob fileBits": { "status": "PASS" }, "Blob fileBits": { "status": "PASS" }, "Empty File fileBits": { "status": "PASS" }, "File fileBits": { "status": "PASS" }, "ArrayBuffer fileBits": { "status": "PASS" }, "Typed array fileBits": { "status": "PASS" }, "Various fileBits": { "status": "PASS" }, "Number in fileBits": { "status": "PASS" }, "Array in fileBits": { "status": "PASS" }, "Object in fileBits": { "status": "PASS" }, "Object with toString in fileBits": { "status": "PASS" }, "Custom @@iterator": { "status": "PASS" }, "Invalid bits argument: \"hello\"": { "status": "PASS" }, "Invalid bits argument: 0": { "status": "PASS" }, "Invalid bits argument: null": { "status": "PASS" }, "Bits argument: object that throws": { "status": "PASS" }, "Using fileName": { "status": "PASS" }, "No replacement when using special character in fileName": { "status": "PASS" }, "Using null fileName": { "status": "PASS" }, "Using number fileName": { "status": "PASS" }, "Using empty string fileName": { "status": "PASS" }, "Using type in File constructor: text/plain": { "status": "PASS" }, "Using type in File constructor: text/plain;charset=UTF-8": { "status": "PASS" }, "Using type in File constructor: TEXT/PLAIN": { "status": "PASS" }, "Using type in File constructor: 𝓽𝓮𝔁𝓽/𝔭𝔩𝔞𝔦𝔫": { "status": "PASS" }, "Using type in File constructor: ascii/nonprintable\u001f": { "status": "PASS" }, "Using type in File constructor: ascii/nonprintable": { "status": "PASS" }, "Using type in File constructor: nonasciiî": { "status": "PASS" }, "Using type in File constructor: nonasciiሴ": { "status": "PASS" }, "Using type in File constructor: nonparsable": { "status": "PASS" }, "Using lastModified": { "status": "PASS" }, "Misusing name": { "status": "PASS" }, "Unknown properties are ignored": { "status": "PASS" }, "Invalid property bag: 123": { "status": "PASS" }, "Invalid property bag: 123.4": { "status": "PASS" }, "Invalid property bag: true": { "status": "PASS" }, "Invalid property bag: \"abc\"": { "status": "PASS" }, "Unusual but valid property bag: null": { "status": "PASS" }, "Unusual but valid property bag: undefined": { "status": "PASS" }, "Unusual but valid property bag: 1,2,3": { "status": "PASS" }, "Unusual but valid property bag: /regex/": { "status": "PASS" }, "Unusual but valid property bag: function() {}": { "status": "PASS" }, "Property bag propagates exceptions": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/WebCryptoAPI/digest/digest.https.any.js.json ================================================ { "SHA-1 with empty source data": { "status": "PASS" }, "sha-1 with empty source data": { "status": "PASS" }, "Sha-1 with empty source data": { "status": "PASS" }, "SHA-1 with empty source data and altered buffer after call": { "status": "PASS" }, "SHA-256 with empty source data": { "status": "PASS" }, "sha-256 with empty source data": { "status": "PASS" }, "Sha-256 with empty source data": { "status": "PASS" }, "SHA-256 with empty source data and altered buffer after call": { "status": "PASS" }, "SHA-384 with empty source data": { "status": "PASS" }, "sha-384 with empty source data": { "status": "PASS" }, "Sha-384 with empty source data": { "status": "PASS" }, "SHA-384 with empty source data and altered buffer after call": { "status": "PASS" }, "SHA-512 with empty source data": { "status": "PASS" }, "sha-512 with empty source data": { "status": "PASS" }, "Sha-512 with empty source data": { "status": "PASS" }, "SHA-512 with empty source data and altered buffer after call": { "status": "PASS" }, "SHA-1 with short source data": { "status": "PASS" }, "sha-1 with short source data": { "status": "PASS" }, "Sha-1 with short source data": { "status": "PASS" }, "SHA-1 with short source data and altered buffer after call": { "status": "PASS" }, "SHA-256 with short source data": { "status": "PASS" }, "sha-256 with short source data": { "status": "PASS" }, "Sha-256 with short source data": { "status": "PASS" }, "SHA-256 with short source data and altered buffer after call": { "status": "PASS" }, "SHA-384 with short source data": { "status": "PASS" }, "sha-384 with short source data": { "status": "PASS" }, "Sha-384 with short source data": { "status": "PASS" }, "SHA-384 with short source data and altered buffer after call": { "status": "PASS" }, "SHA-512 with short source data": { "status": "PASS" }, "sha-512 with short source data": { "status": "PASS" }, "Sha-512 with short source data": { "status": "PASS" }, "SHA-512 with short source data and altered buffer after call": { "status": "PASS" }, "SHA-1 with medium source data": { "status": "PASS" }, "sha-1 with medium source data": { "status": "PASS" }, "Sha-1 with medium source data": { "status": "PASS" }, "SHA-1 with medium source data and altered buffer after call": { "status": "PASS" }, "SHA-256 with medium source data": { "status": "PASS" }, "sha-256 with medium source data": { "status": "PASS" }, "Sha-256 with medium source data": { "status": "PASS" }, "SHA-256 with medium source data and altered buffer after call": { "status": "PASS" }, "SHA-384 with medium source data": { "status": "PASS" }, "sha-384 with medium source data": { "status": "PASS" }, "Sha-384 with medium source data": { "status": "PASS" }, "SHA-384 with medium source data and altered buffer after call": { "status": "PASS" }, "SHA-512 with medium source data": { "status": "PASS" }, "sha-512 with medium source data": { "status": "PASS" }, "Sha-512 with medium source data": { "status": "PASS" }, "SHA-512 with medium source data and altered buffer after call": { "status": "PASS" }, "SHA-1 with long source data": { "status": "PASS" }, "sha-1 with long source data": { "status": "PASS" }, "Sha-1 with long source data": { "status": "PASS" }, "SHA-1 with long source data and altered buffer after call": { "status": "PASS" }, "SHA-256 with long source data": { "status": "PASS" }, "sha-256 with long source data": { "status": "PASS" }, "Sha-256 with long source data": { "status": "PASS" }, "SHA-256 with long source data and altered buffer after call": { "status": "PASS" }, "SHA-384 with long source data": { "status": "PASS" }, "sha-384 with long source data": { "status": "PASS" }, "Sha-384 with long source data": { "status": "PASS" }, "SHA-384 with long source data and altered buffer after call": { "status": "PASS" }, "SHA-512 with long source data": { "status": "PASS" }, "sha-512 with long source data": { "status": "PASS" }, "Sha-512 with long source data": { "status": "PASS" }, "SHA-512 with long source data and altered buffer after call": { "status": "PASS" }, "AES-GCM with empty": { "status": "PASS" }, "RSA-OAEP with empty": { "status": "PASS" }, "PBKDF2 with empty": { "status": "PASS" }, "AES-KW with empty": { "status": "PASS" }, "AES-GCM with short": { "status": "PASS" }, "RSA-OAEP with short": { "status": "PASS" }, "PBKDF2 with short": { "status": "PASS" }, "AES-KW with short": { "status": "PASS" }, "AES-GCM with medium": { "status": "PASS" }, "RSA-OAEP with medium": { "status": "PASS" }, "PBKDF2 with medium": { "status": "PASS" }, "AES-KW with medium": { "status": "PASS" }, "AES-GCM with long": { "status": "PASS" }, "RSA-OAEP with long": { "status": "PASS" }, "PBKDF2 with long": { "status": "PASS" }, "AES-KW with long": { "status": "PASS" }, "empty algorithm object with empty": { "status": "FAIL" }, "empty algorithm object with short": { "status": "FAIL" }, "empty algorithm object with medium": { "status": "FAIL" }, "empty algorithm object with long": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/WebCryptoAPI/getRandomValues.any.js.json ================================================ { "Float16 arrays": { "status": "PASS" }, "Float arrays": { "status": "PASS" }, "DataView": { "status": "PASS" }, "Integer array: Int8Array": { "status": "PASS" }, "Large length: Int8Array": { "status": "PASS" }, "Null arrays: Int8Array": { "status": "PASS" }, "Subclass of Int8Array": { "status": "PASS" }, "Integer array: Int16Array": { "status": "PASS" }, "Large length: Int16Array": { "status": "PASS" }, "Null arrays: Int16Array": { "status": "PASS" }, "Subclass of Int16Array": { "status": "PASS" }, "Integer array: Int32Array": { "status": "PASS" }, "Large length: Int32Array": { "status": "PASS" }, "Null arrays: Int32Array": { "status": "PASS" }, "Subclass of Int32Array": { "status": "PASS" }, "Integer array: BigInt64Array": { "status": "PASS" }, "Large length: BigInt64Array": { "status": "PASS" }, "Null arrays: BigInt64Array": { "status": "PASS" }, "Subclass of BigInt64Array": { "status": "PASS" }, "Integer array: Uint8Array": { "status": "PASS" }, "Large length: Uint8Array": { "status": "PASS" }, "Null arrays: Uint8Array": { "status": "PASS" }, "Subclass of Uint8Array": { "status": "PASS" }, "Integer array: Uint8ClampedArray": { "status": "PASS" }, "Large length: Uint8ClampedArray": { "status": "PASS" }, "Null arrays: Uint8ClampedArray": { "status": "PASS" }, "Subclass of Uint8ClampedArray": { "status": "PASS" }, "Integer array: Uint16Array": { "status": "PASS" }, "Large length: Uint16Array": { "status": "PASS" }, "Null arrays: Uint16Array": { "status": "PASS" }, "Subclass of Uint16Array": { "status": "PASS" }, "Integer array: Uint32Array": { "status": "PASS" }, "Large length: Uint32Array": { "status": "PASS" }, "Null arrays: Uint32Array": { "status": "PASS" }, "Subclass of Uint32Array": { "status": "PASS" }, "Integer array: BigUint64Array": { "status": "PASS" }, "Large length: BigUint64Array": { "status": "PASS" }, "Null arrays: BigUint64Array": { "status": "PASS" }, "Subclass of BigUint64Array": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/WebCryptoAPI/idlharness.https.any.js.json ================================================ { "idl_test setup": { "status": "PASS" }, "idl_test validation": { "status": "PASS" }, "Partial interface mixin WindowOrWorkerGlobalScope: original interface mixin defined": { "status": "PASS" }, "Partial interface mixin WindowOrWorkerGlobalScope: member names are unique": { "status": "PASS" }, "Partial interface Window: member names are unique": { "status": "PASS" }, "Window includes GlobalEventHandlers: member names are unique": { "status": "PASS" }, "Window includes WindowEventHandlers: member names are unique": { "status": "PASS" }, "Window includes WindowOrWorkerGlobalScope: member names are unique": { "status": "PASS" }, "WorkerGlobalScope includes WindowOrWorkerGlobalScope: member names are unique": { "status": "PASS" }, "Window includes AnimationFrameProvider: member names are unique": { "status": "PASS" }, "Window includes WindowSessionStorage: member names are unique": { "status": "PASS" }, "Window includes WindowLocalStorage: member names are unique": { "status": "PASS" }, "Crypto interface: existence and properties of interface object": { "status": "PASS" }, "Crypto interface object length": { "status": "PASS" }, "Crypto interface object name": { "status": "PASS" }, "Crypto interface: existence and properties of interface prototype object": { "status": "PASS" }, "Crypto interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "Crypto interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "Crypto interface: attribute subtle": { "status": "PASS" }, "Crypto interface: operation getRandomValues(ArrayBufferView)": { "status": "PASS" }, "Crypto interface: operation randomUUID()": { "status": "PASS" }, "Crypto must be primary interface of crypto": { "status": "PASS" }, "Stringification of crypto": { "status": "PASS" }, "Crypto interface: crypto must inherit property \"subtle\" with the proper type": { "status": "PASS" }, "Crypto interface: crypto must inherit property \"getRandomValues(ArrayBufferView)\" with the proper type": { "status": "PASS" }, "Crypto interface: calling getRandomValues(ArrayBufferView) on crypto with too few arguments must throw TypeError": { "status": "PASS" }, "Crypto interface: crypto must inherit property \"randomUUID()\" with the proper type": { "status": "PASS" }, "CryptoKey interface: existence and properties of interface object": { "status": "PASS" }, "CryptoKey interface object length": { "status": "PASS" }, "CryptoKey interface object name": { "status": "PASS" }, "CryptoKey interface: existence and properties of interface prototype object": { "status": "PASS" }, "CryptoKey interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "CryptoKey interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "CryptoKey interface: attribute type": { "status": "PASS" }, "CryptoKey interface: attribute extractable": { "status": "PASS" }, "CryptoKey interface: attribute algorithm": { "status": "PASS" }, "CryptoKey interface: attribute usages": { "status": "PASS" }, "SubtleCrypto interface: existence and properties of interface object": { "status": "PASS" }, "SubtleCrypto interface object length": { "status": "PASS" }, "SubtleCrypto interface object name": { "status": "PASS" }, "SubtleCrypto interface: existence and properties of interface prototype object": { "status": "PASS" }, "SubtleCrypto interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "SubtleCrypto interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "SubtleCrypto interface: operation encrypt(AlgorithmIdentifier, CryptoKey, BufferSource)": { "status": "FAIL" }, "SubtleCrypto interface: operation decrypt(AlgorithmIdentifier, CryptoKey, BufferSource)": { "status": "FAIL" }, "SubtleCrypto interface: operation sign(AlgorithmIdentifier, CryptoKey, BufferSource)": { "status": "PASS" }, "SubtleCrypto interface: operation verify(AlgorithmIdentifier, CryptoKey, BufferSource, BufferSource)": { "status": "PASS" }, "SubtleCrypto interface: operation digest(AlgorithmIdentifier, BufferSource)": { "status": "PASS" }, "SubtleCrypto interface: operation generateKey(AlgorithmIdentifier, boolean, sequence)": { "status": "FAIL" }, "SubtleCrypto interface: operation deriveKey(AlgorithmIdentifier, CryptoKey, AlgorithmIdentifier, boolean, sequence)": { "status": "FAIL" }, "SubtleCrypto interface: operation deriveBits(AlgorithmIdentifier, CryptoKey, optional unsigned long?)": { "status": "FAIL" }, "SubtleCrypto interface: operation importKey(KeyFormat, (BufferSource or JsonWebKey), AlgorithmIdentifier, boolean, sequence)": { "status": "PASS" }, "SubtleCrypto interface: operation exportKey(KeyFormat, CryptoKey)": { "status": "FAIL" }, "SubtleCrypto interface: operation wrapKey(KeyFormat, CryptoKey, CryptoKey, AlgorithmIdentifier)": { "status": "FAIL" }, "SubtleCrypto interface: operation unwrapKey(KeyFormat, BufferSource, CryptoKey, AlgorithmIdentifier, AlgorithmIdentifier, boolean, sequence)": { "status": "FAIL" }, "SubtleCrypto must be primary interface of crypto.subtle": { "status": "PASS" }, "Stringification of crypto.subtle": { "status": "PASS" }, "SubtleCrypto interface: crypto.subtle must inherit property \"encrypt(AlgorithmIdentifier, CryptoKey, BufferSource)\" with the proper type": { "status": "FAIL" }, "SubtleCrypto interface: calling encrypt(AlgorithmIdentifier, CryptoKey, BufferSource) on crypto.subtle with too few arguments must throw TypeError": { "status": "FAIL" }, "SubtleCrypto interface: crypto.subtle must inherit property \"decrypt(AlgorithmIdentifier, CryptoKey, BufferSource)\" with the proper type": { "status": "FAIL" }, "SubtleCrypto interface: calling decrypt(AlgorithmIdentifier, CryptoKey, BufferSource) on crypto.subtle with too few arguments must throw TypeError": { "status": "FAIL" }, "SubtleCrypto interface: crypto.subtle must inherit property \"sign(AlgorithmIdentifier, CryptoKey, BufferSource)\" with the proper type": { "status": "PASS" }, "SubtleCrypto interface: calling sign(AlgorithmIdentifier, CryptoKey, BufferSource) on crypto.subtle with too few arguments must throw TypeError": { "status": "PASS" }, "SubtleCrypto interface: crypto.subtle must inherit property \"verify(AlgorithmIdentifier, CryptoKey, BufferSource, BufferSource)\" with the proper type": { "status": "PASS" }, "SubtleCrypto interface: calling verify(AlgorithmIdentifier, CryptoKey, BufferSource, BufferSource) on crypto.subtle with too few arguments must throw TypeError": { "status": "PASS" }, "SubtleCrypto interface: crypto.subtle must inherit property \"digest(AlgorithmIdentifier, BufferSource)\" with the proper type": { "status": "PASS" }, "SubtleCrypto interface: calling digest(AlgorithmIdentifier, BufferSource) on crypto.subtle with too few arguments must throw TypeError": { "status": "PASS" }, "SubtleCrypto interface: crypto.subtle must inherit property \"generateKey(AlgorithmIdentifier, boolean, sequence)\" with the proper type": { "status": "FAIL" }, "SubtleCrypto interface: calling generateKey(AlgorithmIdentifier, boolean, sequence) on crypto.subtle with too few arguments must throw TypeError": { "status": "FAIL" }, "SubtleCrypto interface: crypto.subtle must inherit property \"deriveKey(AlgorithmIdentifier, CryptoKey, AlgorithmIdentifier, boolean, sequence)\" with the proper type": { "status": "FAIL" }, "SubtleCrypto interface: calling deriveKey(AlgorithmIdentifier, CryptoKey, AlgorithmIdentifier, boolean, sequence) on crypto.subtle with too few arguments must throw TypeError": { "status": "FAIL" }, "SubtleCrypto interface: crypto.subtle must inherit property \"deriveBits(AlgorithmIdentifier, CryptoKey, optional unsigned long?)\" with the proper type": { "status": "FAIL" }, "SubtleCrypto interface: calling deriveBits(AlgorithmIdentifier, CryptoKey, optional unsigned long?) on crypto.subtle with too few arguments must throw TypeError": { "status": "FAIL" }, "SubtleCrypto interface: crypto.subtle must inherit property \"importKey(KeyFormat, (BufferSource or JsonWebKey), AlgorithmIdentifier, boolean, sequence)\" with the proper type": { "status": "PASS" }, "SubtleCrypto interface: calling importKey(KeyFormat, (BufferSource or JsonWebKey), AlgorithmIdentifier, boolean, sequence) on crypto.subtle with too few arguments must throw TypeError": { "status": "PASS" }, "SubtleCrypto interface: crypto.subtle must inherit property \"exportKey(KeyFormat, CryptoKey)\" with the proper type": { "status": "FAIL" }, "SubtleCrypto interface: calling exportKey(KeyFormat, CryptoKey) on crypto.subtle with too few arguments must throw TypeError": { "status": "FAIL" }, "SubtleCrypto interface: crypto.subtle must inherit property \"wrapKey(KeyFormat, CryptoKey, CryptoKey, AlgorithmIdentifier)\" with the proper type": { "status": "FAIL" }, "SubtleCrypto interface: calling wrapKey(KeyFormat, CryptoKey, CryptoKey, AlgorithmIdentifier) on crypto.subtle with too few arguments must throw TypeError": { "status": "FAIL" }, "SubtleCrypto interface: crypto.subtle must inherit property \"unwrapKey(KeyFormat, BufferSource, CryptoKey, AlgorithmIdentifier, AlgorithmIdentifier, boolean, sequence)\" with the proper type": { "status": "FAIL" }, "SubtleCrypto interface: calling unwrapKey(KeyFormat, BufferSource, CryptoKey, AlgorithmIdentifier, AlgorithmIdentifier, boolean, sequence) on crypto.subtle with too few arguments must throw TypeError": { "status": "FAIL" }, "Window interface: attribute crypto": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/WebCryptoAPI/import_export/ec_importKey.https.any.js.json ================================================ { "Good parameters: P-256 bits (spki, buffer(91), {name: ECDSA, namedCurve: P-256}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(59, compressed), {name: ECDSA, namedCurve: P-256}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-256}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(65), {name: ECDSA, namedCurve: P-256}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(33, compressed), {name: ECDSA, namedCurve: P-256}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(91), {name: ECDSA, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(59, compressed), {name: ECDSA, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(65), {name: ECDSA, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(33, compressed), {name: ECDSA, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(91), {name: ECDSA, namedCurve: P-256}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(59, compressed), {name: ECDSA, namedCurve: P-256}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-256}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(65), {name: ECDSA, namedCurve: P-256}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(33, compressed), {name: ECDSA, namedCurve: P-256}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDSA, namedCurve: P-256}, true, [sign])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDSA, namedCurve: P-256}, true, [sign, sign])": { "status": "FAIL" }, "Empty Usages: P-256 bits (pkcs8, buffer(138), {name: ECDSA, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-256}, true, [sign])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-256}, true, [sign, sign])": { "status": "FAIL" }, "Empty Usages: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(91), {name: ECDSA, namedCurve: P-256}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(59, compressed), {name: ECDSA, namedCurve: P-256}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-256}, false, [verify])": { "status": "PASS" }, "Good parameters: P-256 bits (raw, buffer(65), {name: ECDSA, namedCurve: P-256}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(33, compressed), {name: ECDSA, namedCurve: P-256}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(91), {name: ECDSA, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(59, compressed), {name: ECDSA, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-256}, false, [])": { "status": "PASS" }, "Good parameters: P-256 bits (raw, buffer(65), {name: ECDSA, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(33, compressed), {name: ECDSA, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(91), {name: ECDSA, namedCurve: P-256}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(59, compressed), {name: ECDSA, namedCurve: P-256}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-256}, false, [verify, verify])": { "status": "PASS" }, "Good parameters: P-256 bits (raw, buffer(65), {name: ECDSA, namedCurve: P-256}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(33, compressed), {name: ECDSA, namedCurve: P-256}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDSA, namedCurve: P-256}, false, [sign])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDSA, namedCurve: P-256}, false, [sign, sign])": { "status": "FAIL" }, "Empty Usages: P-256 bits (pkcs8, buffer(138), {name: ECDSA, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-256}, false, [sign])": { "status": "PASS" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-256}, false, [sign, sign])": { "status": "PASS" }, "Empty Usages: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(120), {name: ECDSA, namedCurve: P-384}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(72, compressed), {name: ECDSA, namedCurve: P-384}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-384}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(97), {name: ECDSA, namedCurve: P-384}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(49, compressed), {name: ECDSA, namedCurve: P-384}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(120), {name: ECDSA, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(72, compressed), {name: ECDSA, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(97), {name: ECDSA, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(49, compressed), {name: ECDSA, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(120), {name: ECDSA, namedCurve: P-384}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(72, compressed), {name: ECDSA, namedCurve: P-384}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-384}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(97), {name: ECDSA, namedCurve: P-384}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(49, compressed), {name: ECDSA, namedCurve: P-384}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDSA, namedCurve: P-384}, true, [sign])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDSA, namedCurve: P-384}, true, [sign, sign])": { "status": "FAIL" }, "Empty Usages: P-384 bits (pkcs8, buffer(185), {name: ECDSA, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-384}, true, [sign])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-384}, true, [sign, sign])": { "status": "FAIL" }, "Empty Usages: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(120), {name: ECDSA, namedCurve: P-384}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(72, compressed), {name: ECDSA, namedCurve: P-384}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-384}, false, [verify])": { "status": "PASS" }, "Good parameters: P-384 bits (raw, buffer(97), {name: ECDSA, namedCurve: P-384}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(49, compressed), {name: ECDSA, namedCurve: P-384}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(120), {name: ECDSA, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(72, compressed), {name: ECDSA, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-384}, false, [])": { "status": "PASS" }, "Good parameters: P-384 bits (raw, buffer(97), {name: ECDSA, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(49, compressed), {name: ECDSA, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(120), {name: ECDSA, namedCurve: P-384}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(72, compressed), {name: ECDSA, namedCurve: P-384}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-384}, false, [verify, verify])": { "status": "PASS" }, "Good parameters: P-384 bits (raw, buffer(97), {name: ECDSA, namedCurve: P-384}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(49, compressed), {name: ECDSA, namedCurve: P-384}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDSA, namedCurve: P-384}, false, [sign])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDSA, namedCurve: P-384}, false, [sign, sign])": { "status": "FAIL" }, "Empty Usages: P-384 bits (pkcs8, buffer(185), {name: ECDSA, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-384}, false, [sign])": { "status": "PASS" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-384}, false, [sign, sign])": { "status": "PASS" }, "Empty Usages: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(158), {name: ECDSA, namedCurve: P-521}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(90, compressed), {name: ECDSA, namedCurve: P-521}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-521}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(133), {name: ECDSA, namedCurve: P-521}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(67, compressed), {name: ECDSA, namedCurve: P-521}, true, [verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(158), {name: ECDSA, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(90, compressed), {name: ECDSA, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(133), {name: ECDSA, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(67, compressed), {name: ECDSA, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(158), {name: ECDSA, namedCurve: P-521}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(90, compressed), {name: ECDSA, namedCurve: P-521}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-521}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(133), {name: ECDSA, namedCurve: P-521}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(67, compressed), {name: ECDSA, namedCurve: P-521}, true, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDSA, namedCurve: P-521}, true, [sign])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDSA, namedCurve: P-521}, true, [sign, sign])": { "status": "FAIL" }, "Empty Usages: P-521 bits (pkcs8, buffer(241), {name: ECDSA, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-521}, true, [sign])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-521}, true, [sign, sign])": { "status": "FAIL" }, "Empty Usages: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(158), {name: ECDSA, namedCurve: P-521}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(90, compressed), {name: ECDSA, namedCurve: P-521}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-521}, false, [verify])": { "status": "PASS" }, "Good parameters: P-521 bits (raw, buffer(133), {name: ECDSA, namedCurve: P-521}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(67, compressed), {name: ECDSA, namedCurve: P-521}, false, [verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(158), {name: ECDSA, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(90, compressed), {name: ECDSA, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-521}, false, [])": { "status": "PASS" }, "Good parameters: P-521 bits (raw, buffer(133), {name: ECDSA, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(67, compressed), {name: ECDSA, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(158), {name: ECDSA, namedCurve: P-521}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(90, compressed), {name: ECDSA, namedCurve: P-521}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y), {name: ECDSA, namedCurve: P-521}, false, [verify, verify])": { "status": "PASS" }, "Good parameters: P-521 bits (raw, buffer(133), {name: ECDSA, namedCurve: P-521}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(67, compressed), {name: ECDSA, namedCurve: P-521}, false, [verify, verify])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDSA, namedCurve: P-521}, false, [sign])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDSA, namedCurve: P-521}, false, [sign, sign])": { "status": "FAIL" }, "Empty Usages: P-521 bits (pkcs8, buffer(241), {name: ECDSA, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-521}, false, [sign])": { "status": "PASS" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-521}, false, [sign, sign])": { "status": "PASS" }, "Empty Usages: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDSA, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(91), {name: ECDH, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(59, compressed), {name: ECDH, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y), {name: ECDH, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "ECDH any JWK alg: P-256 bits (jwk, object(kty, crv, x, y, alg), {name: ECDH, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(65), {name: ECDH, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(33, compressed), {name: ECDH, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDH, namedCurve: P-256}, true, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDH, namedCurve: P-256}, true, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDH, namedCurve: P-256}, true, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDH, namedCurve: P-256}, true, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-256 bits (pkcs8, buffer(138), {name: ECDH, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-256}, true, [deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-256 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-256}, true, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-256}, true, [deriveBits, deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-256 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-256}, true, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-256}, true, [deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-256 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-256}, true, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-256}, true, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-256 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-256}, true, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-256}, true, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(91), {name: ECDH, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (spki, buffer(59, compressed), {name: ECDH, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y), {name: ECDH, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "ECDH any JWK alg: P-256 bits (jwk, object(kty, crv, x, y, alg), {name: ECDH, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(65), {name: ECDH, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (raw, buffer(33, compressed), {name: ECDH, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDH, namedCurve: P-256}, false, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDH, namedCurve: P-256}, false, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDH, namedCurve: P-256}, false, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-256 bits (pkcs8, buffer(138), {name: ECDH, namedCurve: P-256}, false, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-256 bits (pkcs8, buffer(138), {name: ECDH, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-256}, false, [deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-256 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-256}, false, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-256}, false, [deriveBits, deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-256 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-256}, false, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-256}, false, [deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-256 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-256}, false, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-256}, false, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-256 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-256}, false, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-256 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-256}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(120), {name: ECDH, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(72, compressed), {name: ECDH, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y), {name: ECDH, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "ECDH any JWK alg: P-384 bits (jwk, object(kty, crv, x, y, alg), {name: ECDH, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(97), {name: ECDH, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(49, compressed), {name: ECDH, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDH, namedCurve: P-384}, true, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDH, namedCurve: P-384}, true, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDH, namedCurve: P-384}, true, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDH, namedCurve: P-384}, true, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-384 bits (pkcs8, buffer(185), {name: ECDH, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-384}, true, [deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-384 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-384}, true, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-384}, true, [deriveBits, deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-384 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-384}, true, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-384}, true, [deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-384 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-384}, true, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-384}, true, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-384 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-384}, true, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-384}, true, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(120), {name: ECDH, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (spki, buffer(72, compressed), {name: ECDH, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y), {name: ECDH, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "ECDH any JWK alg: P-384 bits (jwk, object(kty, crv, x, y, alg), {name: ECDH, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(97), {name: ECDH, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (raw, buffer(49, compressed), {name: ECDH, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDH, namedCurve: P-384}, false, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDH, namedCurve: P-384}, false, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDH, namedCurve: P-384}, false, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-384 bits (pkcs8, buffer(185), {name: ECDH, namedCurve: P-384}, false, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-384 bits (pkcs8, buffer(185), {name: ECDH, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-384}, false, [deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-384 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-384}, false, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-384}, false, [deriveBits, deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-384 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-384}, false, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-384}, false, [deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-384 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-384}, false, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-384}, false, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-384 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-384}, false, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-384 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-384}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(158), {name: ECDH, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(90, compressed), {name: ECDH, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y), {name: ECDH, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "ECDH any JWK alg: P-521 bits (jwk, object(kty, crv, x, y, alg), {name: ECDH, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(133), {name: ECDH, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(67, compressed), {name: ECDH, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDH, namedCurve: P-521}, true, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDH, namedCurve: P-521}, true, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDH, namedCurve: P-521}, true, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDH, namedCurve: P-521}, true, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-521 bits (pkcs8, buffer(241), {name: ECDH, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-521}, true, [deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-521 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-521}, true, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-521}, true, [deriveBits, deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-521 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-521}, true, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-521}, true, [deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-521 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-521}, true, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-521}, true, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-521 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-521}, true, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-521}, true, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(158), {name: ECDH, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (spki, buffer(90, compressed), {name: ECDH, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y), {name: ECDH, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "ECDH any JWK alg: P-521 bits (jwk, object(kty, crv, x, y, alg), {name: ECDH, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(133), {name: ECDH, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (raw, buffer(67, compressed), {name: ECDH, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDH, namedCurve: P-521}, false, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDH, namedCurve: P-521}, false, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDH, namedCurve: P-521}, false, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-521 bits (pkcs8, buffer(241), {name: ECDH, namedCurve: P-521}, false, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-521 bits (pkcs8, buffer(241), {name: ECDH, namedCurve: P-521}, false, [])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-521}, false, [deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-521 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-521}, false, [deriveKey])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-521}, false, [deriveBits, deriveKey])": { "status": "FAIL" }, "ECDH any JWK alg: P-521 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-521}, false, [deriveBits, deriveKey])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-521}, false, [deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-521 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-521}, false, [deriveBits])": { "status": "FAIL" }, "Good parameters: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-521}, false, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "ECDH any JWK alg: P-521 bits (jwk, object(kty, crv, x, y, d, alg), {name: ECDH, namedCurve: P-521}, false, [deriveKey, deriveBits, deriveKey, deriveBits])": { "status": "FAIL" }, "Empty Usages: P-521 bits (jwk, object(kty, crv, x, y, d), {name: ECDH, namedCurve: P-521}, false, [])": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/WebCryptoAPI/randomUUID.https.any.js.json ================================================ { "namespace format": { "status": "PASS" }, "version set": { "status": "PASS" }, "variant set": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/WebCryptoAPI/sign_verify/ecdsa.https.any.js.json ================================================ { "setup": { "status": "PASS" }, "generate wrong key step: ECDSA P-256 with SHA-1 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-256 with SHA-256 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-256 with SHA-384 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-256 with SHA-512 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-384 with SHA-1 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-384 with SHA-256 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-384 with SHA-384 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-384 with SHA-512 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-521 with SHA-1 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-521 with SHA-256 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-521 with SHA-384 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-521 with SHA-512 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-256 with SHA-1 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-256 with SHA-256 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-256 with SHA-384 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-256 with SHA-512 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-384 with SHA-1 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-384 with SHA-256 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-384 with SHA-384 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-384 with SHA-512 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-521 with SHA-1 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-521 with SHA-256 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-521 with SHA-384 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: ECDSA P-521 with SHA-512 verifying with wrong algorithm name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 verification with altered signature after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 with altered plaintext after call": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 using privateKey to verify": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 using publicKey to sign": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 no verify usage": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 round trip": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 verification failure due to altered signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 verification failure due to wrong hash": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 verification failure due to bad hash name": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 verification failure due to shortened signature": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 verification failure due to altered plaintext": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-1 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-256 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-384 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-256 with SHA-512 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-1 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-256 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-384 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-384 with SHA-512 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-1 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-256 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-512 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-384 - The signature is all zeroes verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 - The signature was truncated by 1 byte verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-1 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-256 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-384 verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 - Signature has excess padding verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 - The signature is empty verification": { "status": "FAIL" }, "importVectorKeys step: ECDSA P-521 with SHA-512 - The signature is all zeroes verification": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/WebCryptoAPI/sign_verify/hmac.https.any.js.json ================================================ { "setup": { "status": "PASS" }, "generate wrong key step: HMAC with SHA-1 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: HMAC with SHA-256 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: HMAC with SHA-384 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: HMAC with SHA-512 signing with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: HMAC with SHA-1 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: HMAC with SHA-256 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: HMAC with SHA-384 verifying with wrong algorithm name": { "status": "FAIL" }, "generate wrong key step: HMAC with SHA-512 verifying with wrong algorithm name": { "status": "FAIL" }, "HMAC with SHA-1 verification": { "status": "PASS" }, "HMAC with SHA-256 verification": { "status": "PASS" }, "HMAC with SHA-384 verification": { "status": "PASS" }, "HMAC with SHA-512 verification": { "status": "PASS" }, "HMAC with SHA-1 verification with altered signature after call": { "status": "PASS" }, "HMAC with SHA-256 verification with altered signature after call": { "status": "PASS" }, "HMAC with SHA-384 verification with altered signature after call": { "status": "PASS" }, "HMAC with SHA-512 verification with altered signature after call": { "status": "PASS" }, "HMAC with SHA-1 with altered plaintext after call": { "status": "PASS" }, "HMAC with SHA-256 with altered plaintext after call": { "status": "PASS" }, "HMAC with SHA-384 with altered plaintext after call": { "status": "PASS" }, "HMAC with SHA-512 with altered plaintext after call": { "status": "PASS" }, "HMAC with SHA-1 no verify usage": { "status": "PASS" }, "HMAC with SHA-256 no verify usage": { "status": "PASS" }, "HMAC with SHA-384 no verify usage": { "status": "PASS" }, "HMAC with SHA-512 no verify usage": { "status": "PASS" }, "HMAC with SHA-1 round trip": { "status": "PASS" }, "HMAC with SHA-256 round trip": { "status": "PASS" }, "HMAC with SHA-384 round trip": { "status": "PASS" }, "HMAC with SHA-512 round trip": { "status": "PASS" }, "HMAC with SHA-1 verification failure due to wrong plaintext": { "status": "PASS" }, "HMAC with SHA-256 verification failure due to wrong plaintext": { "status": "PASS" }, "HMAC with SHA-384 verification failure due to wrong plaintext": { "status": "PASS" }, "HMAC with SHA-512 verification failure due to wrong plaintext": { "status": "PASS" }, "HMAC with SHA-1 verification failure due to wrong signature": { "status": "PASS" }, "HMAC with SHA-256 verification failure due to wrong signature": { "status": "PASS" }, "HMAC with SHA-384 verification failure due to wrong signature": { "status": "PASS" }, "HMAC with SHA-512 verification failure due to wrong signature": { "status": "PASS" }, "HMAC with SHA-1 verification failure due to short signature": { "status": "PASS" }, "HMAC with SHA-256 verification failure due to short signature": { "status": "PASS" }, "HMAC with SHA-384 verification failure due to short signature": { "status": "PASS" }, "HMAC with SHA-512 verification failure due to short signature": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/compression-bad-chunks.tentative.any.js.json ================================================ { "chunk of type undefined should error the stream for gzip": { "status": "PASS" }, "chunk of type undefined should error the stream for deflate": { "status": "PASS" }, "chunk of type undefined should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type null should error the stream for gzip": { "status": "PASS" }, "chunk of type null should error the stream for deflate": { "status": "PASS" }, "chunk of type null should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type numeric should error the stream for gzip": { "status": "PASS" }, "chunk of type numeric should error the stream for deflate": { "status": "PASS" }, "chunk of type numeric should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type object, not BufferSource should error the stream for gzip": { "status": "PASS" }, "chunk of type object, not BufferSource should error the stream for deflate": { "status": "PASS" }, "chunk of type object, not BufferSource should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type array should error the stream for gzip": { "status": "PASS" }, "chunk of type array should error the stream for deflate": { "status": "PASS" }, "chunk of type array should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type SharedArrayBuffer should error the stream for gzip": { "status": "FAIL" }, "chunk of type SharedArrayBuffer should error the stream for deflate": { "status": "FAIL" }, "chunk of type SharedArrayBuffer should error the stream for deflate-raw": { "status": "FAIL" }, "chunk of type shared Uint8Array should error the stream for gzip": { "status": "FAIL" }, "chunk of type shared Uint8Array should error the stream for deflate": { "status": "FAIL" }, "chunk of type shared Uint8Array should error the stream for deflate-raw": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/compression/compression-constructor-error.tentative.any.js.json ================================================ { "\"a\" should cause the constructor to throw": { "status": "PASS" }, "no input should cause the constructor to throw": { "status": "PASS" }, "non-string input should cause the constructor to throw": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/compression-including-empty-chunk.tentative.any.js.json ================================================ { "the result of compressing [,Hello,Hello] with deflate should be 'HelloHello'": { "status": "PASS" }, "the result of compressing [,Hello,Hello] with gzip should be 'HelloHello'": { "status": "PASS" }, "the result of compressing [,Hello,Hello] with deflate-raw should be 'HelloHello'": { "status": "PASS" }, "the result of compressing [Hello,,Hello] with deflate should be 'HelloHello'": { "status": "PASS" }, "the result of compressing [Hello,,Hello] with gzip should be 'HelloHello'": { "status": "PASS" }, "the result of compressing [Hello,,Hello] with deflate-raw should be 'HelloHello'": { "status": "PASS" }, "the result of compressing [Hello,Hello,] with deflate should be 'HelloHello'": { "status": "PASS" }, "the result of compressing [Hello,Hello,] with gzip should be 'HelloHello'": { "status": "PASS" }, "the result of compressing [Hello,Hello,] with deflate-raw should be 'HelloHello'": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/compression-large-flush-output.any.js.json ================================================ { "deflate compression with large flush output": { "status": "FAIL" }, "gzip compression with large flush output": { "status": "FAIL" }, "deflate-raw compression with large flush output": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/compression/compression-multiple-chunks.tentative.any.js.json ================================================ { "compressing 2 chunks with deflate should work": { "status": "PASS" }, "compressing 2 chunks with gzip should work": { "status": "PASS" }, "compressing 2 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 3 chunks with deflate should work": { "status": "PASS" }, "compressing 3 chunks with gzip should work": { "status": "PASS" }, "compressing 3 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 4 chunks with deflate should work": { "status": "PASS" }, "compressing 4 chunks with gzip should work": { "status": "PASS" }, "compressing 4 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 5 chunks with deflate should work": { "status": "PASS" }, "compressing 5 chunks with gzip should work": { "status": "PASS" }, "compressing 5 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 6 chunks with deflate should work": { "status": "PASS" }, "compressing 6 chunks with gzip should work": { "status": "PASS" }, "compressing 6 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 7 chunks with deflate should work": { "status": "PASS" }, "compressing 7 chunks with gzip should work": { "status": "PASS" }, "compressing 7 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 8 chunks with deflate should work": { "status": "PASS" }, "compressing 8 chunks with gzip should work": { "status": "PASS" }, "compressing 8 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 9 chunks with deflate should work": { "status": "PASS" }, "compressing 9 chunks with gzip should work": { "status": "PASS" }, "compressing 9 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 10 chunks with deflate should work": { "status": "PASS" }, "compressing 10 chunks with gzip should work": { "status": "PASS" }, "compressing 10 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 11 chunks with deflate should work": { "status": "PASS" }, "compressing 11 chunks with gzip should work": { "status": "PASS" }, "compressing 11 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 12 chunks with deflate should work": { "status": "PASS" }, "compressing 12 chunks with gzip should work": { "status": "PASS" }, "compressing 12 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 13 chunks with deflate should work": { "status": "PASS" }, "compressing 13 chunks with gzip should work": { "status": "PASS" }, "compressing 13 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 14 chunks with deflate should work": { "status": "PASS" }, "compressing 14 chunks with gzip should work": { "status": "PASS" }, "compressing 14 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 15 chunks with deflate should work": { "status": "PASS" }, "compressing 15 chunks with gzip should work": { "status": "PASS" }, "compressing 15 chunks with deflate-raw should work": { "status": "PASS" }, "compressing 16 chunks with deflate should work": { "status": "PASS" }, "compressing 16 chunks with gzip should work": { "status": "PASS" }, "compressing 16 chunks with deflate-raw should work": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/compression-output-length.tentative.any.js.json ================================================ { "the length of deflated data should be shorter than that of the original data": { "status": "PASS" }, "the length of gzipped data should be shorter than that of the original data": { "status": "PASS" }, "the length of deflated (with -raw) data should be shorter than that of the original data": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/compression-stream.tentative.any.js.json ================================================ { "CompressionStream constructor should throw on invalid format": { "status": "PASS" }, "deflated empty data should be reinflated back to its origin": { "status": "PASS" }, "deflated small amount data should be reinflated back to its origin": { "status": "PASS" }, "deflated large amount data should be reinflated back to its origin": { "status": "PASS" }, "gzipped empty data should be reinflated back to its origin": { "status": "PASS" }, "gzipped small amount data should be reinflated back to its origin": { "status": "PASS" }, "gzipped large amount data should be reinflated back to its origin": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/compression-with-detach.tentative.window.js.json ================================================ { "data should be correctly compressed even if input is detached partway": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/compression/decompression-bad-chunks.tentative.any.js.json ================================================ { "chunk of type undefined should error the stream for gzip": { "status": "PASS" }, "chunk of type undefined should error the stream for deflate": { "status": "PASS" }, "chunk of type undefined should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type null should error the stream for gzip": { "status": "PASS" }, "chunk of type null should error the stream for deflate": { "status": "PASS" }, "chunk of type null should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type numeric should error the stream for gzip": { "status": "PASS" }, "chunk of type numeric should error the stream for deflate": { "status": "PASS" }, "chunk of type numeric should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type object, not BufferSource should error the stream for gzip": { "status": "PASS" }, "chunk of type object, not BufferSource should error the stream for deflate": { "status": "PASS" }, "chunk of type object, not BufferSource should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type array should error the stream for gzip": { "status": "PASS" }, "chunk of type array should error the stream for deflate": { "status": "PASS" }, "chunk of type array should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type SharedArrayBuffer should error the stream for gzip": { "status": "FAIL" }, "chunk of type SharedArrayBuffer should error the stream for deflate": { "status": "FAIL" }, "chunk of type SharedArrayBuffer should error the stream for deflate-raw": { "status": "FAIL" }, "chunk of type shared Uint8Array should error the stream for gzip": { "status": "FAIL" }, "chunk of type shared Uint8Array should error the stream for deflate": { "status": "FAIL" }, "chunk of type shared Uint8Array should error the stream for deflate-raw": { "status": "FAIL" }, "chunk of type invalid deflate bytes should error the stream for gzip": { "status": "PASS" }, "chunk of type invalid deflate bytes should error the stream for deflate": { "status": "PASS" }, "chunk of type invalid deflate bytes should error the stream for deflate-raw": { "status": "PASS" }, "chunk of type invalid gzip bytes should error the stream for gzip": { "status": "PASS" }, "chunk of type invalid gzip bytes should error the stream for deflate": { "status": "PASS" }, "chunk of type invalid gzip bytes should error the stream for deflate-raw": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/decompression-buffersource.tentative.any.js.json ================================================ { "chunk of type ArrayBuffer should work for deflate": { "status": "PASS" }, "chunk of type Int8Array should work for deflate": { "status": "PASS" }, "chunk of type Uint8Array should work for deflate": { "status": "PASS" }, "chunk of type Uint8ClampedArray should work for deflate": { "status": "PASS" }, "chunk of type Int16Array should work for deflate": { "status": "PASS" }, "chunk of type Uint16Array should work for deflate": { "status": "PASS" }, "chunk of type Int32Array should work for deflate": { "status": "PASS" }, "chunk of type Uint32Array should work for deflate": { "status": "PASS" }, "chunk of type Float16Array should work for deflate": { "status": "PASS" }, "chunk of type Float32Array should work for deflate": { "status": "PASS" }, "chunk of type Float64Array should work for deflate": { "status": "PASS" }, "chunk of type DataView should work for deflate": { "status": "PASS" }, "chunk of type ArrayBuffer should work for gzip": { "status": "PASS" }, "chunk of type Int8Array should work for gzip": { "status": "PASS" }, "chunk of type Uint8Array should work for gzip": { "status": "PASS" }, "chunk of type Uint8ClambedArray should work for gzip": { "status": "PASS" }, "chunk of type Int16Array should work for gzip": { "status": "PASS" }, "chunk of type Uint16Array should work for gzip": { "status": "PASS" }, "chunk of type Int32Array should work for gzip": { "status": "PASS" }, "chunk of type Uint32Array should work for gzip": { "status": "PASS" }, "chunk of type Float16Array should work for gzip": { "status": "PASS" }, "chunk of type Float32Array should work for gzip": { "status": "PASS" }, "chunk of type Float64Array should work for gzip": { "status": "PASS" }, "chunk of type DataView should work for gzip": { "status": "PASS" }, "chunk of type ArrayBuffer should work for deflate-raw": { "status": "PASS" }, "chunk of type Int8Array should work for deflate-raw": { "status": "PASS" }, "chunk of type Uint8Array should work for deflate-raw": { "status": "PASS" }, "chunk of type Uint8ClampedArray should work for deflate-raw": { "status": "PASS" }, "chunk of type Int16Array should work for deflate-raw": { "status": "PASS" }, "chunk of type Uint16Array should work for deflate-raw": { "status": "PASS" }, "chunk of type Int32Array should work for deflate-raw": { "status": "PASS" }, "chunk of type Uint32Array should work for deflate-raw": { "status": "PASS" }, "chunk of type Float16Array should work for deflate-raw": { "status": "PASS" }, "chunk of type Float32Array should work for deflate-raw": { "status": "PASS" }, "chunk of type Float64Array should work for deflate-raw": { "status": "PASS" }, "chunk of type DataView should work for deflate-raw": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/decompression-constructor-error.tentative.any.js.json ================================================ { "\"a\" should cause the constructor to throw": { "status": "PASS" }, "no input should cause the constructor to throw": { "status": "PASS" }, "non-string input should cause the constructor to throw": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/decompression-correct-input.tentative.any.js.json ================================================ { "decompressing deflated input should work": { "status": "PASS" }, "decompressing gzip input should work": { "status": "PASS" }, "decompressing deflated (with -raw) input should work": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/decompression-corrupt-input.tentative.any.js.json ================================================ { "the unchanged input for 'deflate' should decompress successfully": { "status": "PASS" }, "truncating the input for 'deflate' should give an error": { "status": "FAIL" }, "trailing junk for 'deflate' should give an error": { "status": "PASS" }, "format 'deflate' field CMF should be error for 0": { "status": "PASS" }, "format 'deflate' field FLG should be success for 218": { "status": "PASS" }, "format 'deflate' field FLG should be success for 1": { "status": "PASS" }, "format 'deflate' field FLG should be success for 94": { "status": "PASS" }, "format 'deflate' field FLG should be error for 157": { "status": "PASS" }, "format 'deflate' field DATA should be success for 4": { "status": "PASS" }, "format 'deflate' field DATA should be error for 5": { "status": "PASS" }, "format 'deflate' field ADLER should be error for 255": { "status": "FAIL" }, "the unchanged input for 'gzip' should decompress successfully": { "status": "PASS" }, "truncating the input for 'gzip' should give an error": { "status": "FAIL" }, "trailing junk for 'gzip' should give an error": { "status": "PASS" }, "format 'gzip' field ID should be error for 255": { "status": "PASS" }, "format 'gzip' field CM should be error for 0": { "status": "PASS" }, "format 'gzip' field FLG should be success for 1": { "status": "PASS" }, "format 'gzip' field FLG should be error for 2": { "status": "PASS" }, "format 'gzip' field MTIME should be success for 255": { "status": "PASS" }, "format 'gzip' field XFL should be success for 255": { "status": "PASS" }, "format 'gzip' field OS should be success for 128": { "status": "PASS" }, "format 'gzip' field DATA should be error for 3": { "status": "PASS" }, "format 'gzip' field DATA should be success for 4": { "status": "PASS" }, "format 'gzip' field CRC should be error for 0": { "status": "PASS" }, "format 'gzip' field ISIZE should be error for 1": { "status": "FAIL" }, "the deflate input compressed with dictionary should give an error": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/decompression-empty-input.tentative.any.js.json ================================================ { "decompressing gzip empty input should work": { "status": "PASS" }, "decompressing deflate empty input should work": { "status": "PASS" }, "decompressing deflate-raw empty input should work": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/decompression-split-chunk.tentative.any.js.json ================================================ { "decompressing splitted chunk into pieces of size 1 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 1 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 1 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 2 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 2 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 2 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 3 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 3 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 3 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 4 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 4 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 4 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 5 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 5 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 5 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 6 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 6 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 6 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 7 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 7 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 7 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 8 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 8 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 8 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 9 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 9 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 9 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 10 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 10 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 10 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 11 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 11 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 11 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 12 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 12 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 12 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 13 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 13 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 13 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 14 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 14 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 14 should work in deflate-raw": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 15 should work in deflate": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 15 should work in gzip": { "status": "PASS" }, "decompressing splitted chunk into pieces of size 15 should work in deflate-raw": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/decompression-uint8array-output.tentative.any.js.json ================================================ { "decompressing deflated output should give Uint8Array chunks": { "status": "PASS" }, "decompressing gzip output should give Uint8Array chunks": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/compression/decompression-with-detach.tentative.window.js.json ================================================ { "data should be correctly decompressed even if input is detached partway": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/compression/idlharness.https.any.js.json ================================================ { "idl_test setup": { "status": "PASS" }, "idl_test validation": { "status": "PASS" }, "CompressionStream includes GenericTransformStream: member names are unique": { "status": "PASS" }, "DecompressionStream includes GenericTransformStream: member names are unique": { "status": "PASS" }, "CompressionStream interface: existence and properties of interface object": { "status": "PASS" }, "CompressionStream interface object length": { "status": "PASS" }, "CompressionStream interface object name": { "status": "PASS" }, "CompressionStream interface: existence and properties of interface prototype object": { "status": "PASS" }, "CompressionStream interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "CompressionStream interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "CompressionStream must be primary interface of new CompressionStream(\"deflate\")": { "status": "PASS" }, "Stringification of new CompressionStream(\"deflate\")": { "status": "PASS" }, "DecompressionStream interface: existence and properties of interface object": { "status": "PASS" }, "DecompressionStream interface object length": { "status": "PASS" }, "DecompressionStream interface object name": { "status": "PASS" }, "DecompressionStream interface: existence and properties of interface prototype object": { "status": "PASS" }, "DecompressionStream interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "DecompressionStream interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "DecompressionStream must be primary interface of new DecompressionStream(\"deflate\")": { "status": "PASS" }, "Stringification of new DecompressionStream(\"deflate\")": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/console/console-is-a-namespace.any.js.json ================================================ { "console exists on the global object": { "status": "PASS" }, "console has the right property descriptors": { "status": "PASS" }, "Console (uppercase, as if it were an interface) must not exist": { "status": "PASS" }, "The prototype chain must be correct": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/console/console-label-conversion.any.js.json ================================================ { "console.count()'s label gets converted to string via label.toString() when label is an object": { "status": "PASS" }, "console.count() throws exceptions generated by erroneous label.toString() conversion": { "status": "PASS" }, "console.countReset()'s label gets converted to string via label.toString() when label is an object": { "status": "PASS" }, "console.countReset() throws exceptions generated by erroneous label.toString() conversion": { "status": "PASS" }, "console.time()'s label gets converted to string via label.toString() when label is an object": { "status": "PASS" }, "console.time() throws exceptions generated by erroneous label.toString() conversion": { "status": "PASS" }, "console.timeLog()'s label gets converted to string via label.toString() when label is an object": { "status": "PASS" }, "console.timeLog() throws exceptions generated by erroneous label.toString() conversion": { "status": "PASS" }, "console.timeEnd()'s label gets converted to string via label.toString() when label is an object": { "status": "PASS" }, "console.timeEnd() throws exceptions generated by erroneous label.toString() conversion": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/console/console-log-symbol.any.js.json ================================================ { "Logging a symbol doesn't throw": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/console/console-namespace-object-class-string.any.js.json ================================================ { "@@toStringTag exists on the namespace object with the appropriate descriptor": { "status": "PASS" }, "Object.prototype.toString applied to the namespace object": { "status": "PASS" }, "Object.prototype.toString applied after modifying the namespace object's @@toStringTag": { "status": "PASS" }, "Object.prototype.toString applied after deleting @@toStringTag": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/console/console-tests-historical.any.js.json ================================================ { "'timeline' function should not exist on the console object": { "status": "PASS" }, "'timelineEnd' function should not exist on the console object": { "status": "PASS" }, "'markTimeline' function should not exist on the console object": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/console/idlharness.any.js.json ================================================ { "idl_test setup": { "status": "PASS" }, "idl_test validation": { "status": "PASS" }, "console namespace: extended attributes": { "status": "PASS" }, "console namespace: property descriptor": { "status": "PASS" }, "console namespace: [[Extensible]] is true": { "status": "PASS" }, "console namespace: [[Prototype]] is Object.prototype": { "status": "PASS" }, "console namespace: typeof is \"object\"": { "status": "PASS" }, "console namespace: has no length property": { "status": "PASS" }, "console namespace: has no name property": { "status": "PASS" }, "console namespace: operation assert(optional boolean, any...)": { "status": "PASS" }, "console namespace: operation clear()": { "status": "PASS" }, "console namespace: operation debug(any...)": { "status": "PASS" }, "console namespace: operation error(any...)": { "status": "PASS" }, "console namespace: operation info(any...)": { "status": "PASS" }, "console namespace: operation log(any...)": { "status": "PASS" }, "console namespace: operation table(optional any, optional sequence)": { "status": "PASS" }, "console namespace: operation trace(any...)": { "status": "PASS" }, "console namespace: operation warn(any...)": { "status": "PASS" }, "console namespace: operation dir(optional any, optional object?)": { "status": "PASS" }, "console namespace: operation dirxml(any...)": { "status": "PASS" }, "console namespace: operation count(optional DOMString)": { "status": "PASS" }, "console namespace: operation countReset(optional DOMString)": { "status": "PASS" }, "console namespace: operation group(any...)": { "status": "PASS" }, "console namespace: operation groupCollapsed(any...)": { "status": "PASS" }, "console namespace: operation groupEnd()": { "status": "PASS" }, "console namespace: operation time(optional DOMString)": { "status": "PASS" }, "console namespace: operation timeLog(optional DOMString, any...)": { "status": "PASS" }, "console namespace: operation timeEnd(optional DOMString)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/dom/events/AddEventListenerOptions-once.any.js.json ================================================ { "Once listener should be invoked only once": { "status": "PASS" }, "Once listener should be invoked only once even if the event is nested": { "status": "PASS" }, "Once listener should be added / removed like normal listeners": { "status": "PASS" }, "Multiple once listeners should be invoked even if the stopImmediatePropagation is set": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/dom/events/AddEventListenerOptions-passive.any.js.json ================================================ { "Supports passive option on addEventListener only": { "status": "PASS" }, "preventDefault should be ignored if-and-only-if the passive option is true": { "status": "PASS" }, "returnValue should be ignored if-and-only-if the passive option is true": { "status": "PASS" }, "passive behavior of one listener should be unaffected by the presence of other listeners": { "status": "PASS" }, "Equivalence of option values": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/dom/events/Event-constructors.any.js.json ================================================ { "Event-constructors": { "status": "PASS" }, "Event-constructors 1": { "status": "PASS" }, "Event-constructors 2": { "status": "PASS" }, "Event-constructors 3": { "status": "PASS" }, "Event-constructors 4": { "status": "PASS" }, "Event-constructors 5": { "status": "PASS" }, "Event-constructors 6": { "status": "PASS" }, "Event-constructors 7": { "status": "PASS" }, "Event-constructors 8": { "status": "PASS" }, "Event-constructors 9": { "status": "PASS" }, "Event-constructors 10": { "status": "PASS" }, "Event-constructors 11": { "status": "PASS" }, "Event-constructors 12": { "status": "PASS" }, "Event-constructors 13": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/dom/events/EventTarget-add-remove-listener.any.js.json ================================================ { "Removing an event listener without explicit capture arg should succeed": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/dom/events/EventTarget-addEventListener.any.js.json ================================================ { "Adding a null event listener should succeed": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/dom/events/EventTarget-constructible.any.js.json ================================================ { "A constructed EventTarget can be used as expected": { "status": "PASS" }, "A constructed EventTarget implements dispatch correctly": { "status": "PASS" }, "EventTarget can be subclassed": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/dom/events/EventTarget-removeEventListener.any.js.json ================================================ { "removing a null event listener should succeed": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/api-basics.any.js.json ================================================ { "Default encodings": { "status": "PASS" }, "Default inputs": { "status": "PASS" }, "Encode/decode round trip: utf-8": { "status": "PASS" }, "Decode sample: utf-16le": { "status": "PASS" }, "Decode sample: utf-16be": { "status": "PASS" }, "Decode sample: utf-16": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/api-invalid-label.any.js.json ================================================ { "Invalid label \"invalid-invalidLabel\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicode-1-1-utf-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode-1-1-utf-8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicode-1-1-utf-8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicode-1-1-utf-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode-1-1-utf-8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicode-1-1-utf-8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicode-1-1-utf-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode-1-1-utf-8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicode-1-1-utf-8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode-1-1-utf-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode-1-1-utf-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode-1-1-utf-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode-1-1-utf-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode-1-1-utf-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode-1-1-utf-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicode11utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode11utf8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicode11utf8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicode11utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode11utf8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicode11utf8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicode11utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode11utf8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicode11utf8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode11utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode11utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode11utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode11utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode11utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode11utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicode20utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode20utf8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicode20utf8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicode20utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode20utf8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicode20utf8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicode20utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode20utf8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicode20utf8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode20utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode20utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode20utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode20utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode20utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode20utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0utf-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0utf-8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vutf-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vutf-8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" utf-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" utf-8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0utf8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vutf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vutf8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" utf8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-unicode20utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-unicode20utf8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-unicode20utf8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-unicode20utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-unicode20utf8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-unicode20utf8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-unicode20utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-unicode20utf8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-unicode20utf8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-unicode20utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-unicode20utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-unicode20utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-unicode20utf8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-unicode20utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-unicode20utf8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"866\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0866\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\v866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"866\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\v866\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" 866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"866 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" 866 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp866\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp866\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp866\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp866\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp866 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp866 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csibm866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csibm866\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csibm866\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsibm866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csibm866\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsibm866\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csibm866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csibm866 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csibm866 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csibm866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csibm866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csibm866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csibm866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csibm866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csibm866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ibm866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ibm866\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ibm866\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vibm866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ibm866\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vibm866\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ibm866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ibm866 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ibm866 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ibm866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ibm866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ibm866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ibm866\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ibm866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ibm866
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-101\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-101\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-101\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-101\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-101\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-101\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-101\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-101 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-101 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-101\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-101
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-101
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-101\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-101
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-101
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88592\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88592\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88592\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88592\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88592\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88592\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88592\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88592 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88592 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88592\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88592
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88592
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88592\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88592
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88592
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-2:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-2:1987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-2:1987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-2:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-2:1987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-2:1987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-2:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-2:1987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-2:1987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-2:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-2:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-2:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-2:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-2:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-2:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-109\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-109\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-109\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-109\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-109\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-109\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-109\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-109 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-109 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-109\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-109
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-109
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-109\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-109
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-109
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88593\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88593\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88593\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88593\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88593\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88593\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88593\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88593 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88593 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88593\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88593
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88593
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88593\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88593
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88593
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-3:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-3:1988\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-3:1988\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-3:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-3:1988\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-3:1988\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-3:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-3:1988 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-3:1988 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-3:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-3:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-3:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-3:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-3:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-3:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin3\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin3\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin3 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin3\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin3
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-110\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-110\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-110\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-110\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-110\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-110\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-110\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-110 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-110 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-110\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-110
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-110
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-110\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-110
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-110
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88594\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88594\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88594\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88594\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88594\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88594\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88594\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88594 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88594 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88594\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88594
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88594
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88594\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88594
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88594
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-4:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-4:1988\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-4:1988\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-4:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-4:1988\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-4:1988\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-4:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-4:1988 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-4:1988 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-4:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-4:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-4:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-4:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-4:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-4:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin4\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin4\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin4 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin4\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin4
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatincyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatincyrillic\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatincyrillic\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatincyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatincyrillic\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatincyrillic\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatincyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatincyrillic \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatincyrillic \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatincyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatincyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatincyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatincyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatincyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatincyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cyrillic\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cyrillic\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cyrillic\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcyrillic\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cyrillic \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cyrillic \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-144\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-144\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-144\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-144\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-144\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-144\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-144\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-144 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-144 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-144\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-144
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-144
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-144\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-144
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-144
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88595\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88595\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88595\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88595\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88595\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88595\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88595\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88595 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88595 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88595\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88595
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88595
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88595\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88595
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88595
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-5:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-5:1988\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-5:1988\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-5:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-5:1988\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-5:1988\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-5:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-5:1988 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-5:1988 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-5:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-5:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-5:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-5:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-5:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-5:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0arabic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"arabic\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0arabic\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\varabic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"arabic\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\varabic\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" arabic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"arabic \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" arabic \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
arabic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"arabic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
arabic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
arabic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"arabic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
arabic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0asmo-708\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"asmo-708\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0asmo-708\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vasmo-708\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"asmo-708\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vasmo-708\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" asmo-708\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"asmo-708 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" asmo-708 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
asmo-708\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"asmo-708
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
asmo-708
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
asmo-708\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"asmo-708
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
asmo-708
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso88596e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88596e\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso88596e\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso88596e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88596e\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso88596e\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso88596e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88596e \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso88596e \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88596e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88596e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88596e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88596e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88596e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88596e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso88596i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88596i\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso88596i\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso88596i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88596i\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso88596i\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso88596i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88596i \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso88596i \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88596i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88596i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88596i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88596i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88596i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88596i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatinarabic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatinarabic\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatinarabic\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatinarabic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatinarabic\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatinarabic\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatinarabic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatinarabic \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatinarabic \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatinarabic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatinarabic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatinarabic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatinarabic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatinarabic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatinarabic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ecma-114\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ecma-114\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ecma-114\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vecma-114\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ecma-114\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vecma-114\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ecma-114\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ecma-114 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ecma-114 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ecma-114\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ecma-114
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ecma-114
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ecma-114\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ecma-114
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ecma-114
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-6-e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6-e\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-6-e\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-6-e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6-e\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-6-e\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-6-e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6-e \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-6-e \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6-e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6-e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6-e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6-e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6-e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6-e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-6-i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6-i\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-6-i\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-6-i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6-i\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-6-i\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-6-i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6-i \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-6-i \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6-i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6-i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6-i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6-i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-6-i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-6-i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-127\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-127\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-127\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-127\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-127\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-127\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-127\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-127 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-127 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-127\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-127
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-127
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-127\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-127
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-127
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88596\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88596\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88596\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88596\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88596\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88596\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88596\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88596 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88596 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88596\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88596
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88596
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88596\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88596
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88596
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-6:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-6:1987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-6:1987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-6:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-6:1987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-6:1987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-6:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-6:1987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-6:1987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-6:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-6:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-6:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-6:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-6:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-6:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatingreek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatingreek\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatingreek\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatingreek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatingreek\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatingreek\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatingreek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatingreek \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatingreek \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatingreek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatingreek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatingreek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatingreek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatingreek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatingreek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ecma-118\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ecma-118\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ecma-118\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vecma-118\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ecma-118\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vecma-118\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ecma-118\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ecma-118 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ecma-118 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ecma-118\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ecma-118
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ecma-118
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ecma-118\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ecma-118
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ecma-118
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0elot_928\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"elot_928\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0elot_928\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\velot_928\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"elot_928\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\velot_928\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" elot_928\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"elot_928 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" elot_928 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
elot_928\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"elot_928
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
elot_928
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
elot_928\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"elot_928
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
elot_928
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0greek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"greek\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0greek\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgreek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"greek\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgreek\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" greek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"greek \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" greek \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
greek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"greek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
greek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
greek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"greek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
greek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0greek8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"greek8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0greek8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgreek8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"greek8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgreek8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" greek8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"greek8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" greek8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
greek8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"greek8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
greek8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
greek8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"greek8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
greek8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-7\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-7\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-7\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-7\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-7 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-7 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-126\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-126\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-126\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-126\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-126\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-126\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-126\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-126 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-126 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-126\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-126
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-126
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-126\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-126
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-126
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-7\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-7\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-7\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-7\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-7 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-7 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88597\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88597\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88597\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88597\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88597\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88597\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88597\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88597 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88597 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88597\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88597
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88597
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88597\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88597
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88597
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-7\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-7\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-7\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-7\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-7 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-7 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-7\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-7
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-7:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-7:1987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-7:1987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-7:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-7:1987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-7:1987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-7:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-7:1987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-7:1987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-7:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-7:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-7:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-7:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-7:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-7:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0sun_eu_greek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"sun_eu_greek\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0sun_eu_greek\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vsun_eu_greek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"sun_eu_greek\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vsun_eu_greek\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" sun_eu_greek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"sun_eu_greek \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" sun_eu_greek \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
sun_eu_greek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"sun_eu_greek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
sun_eu_greek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
sun_eu_greek\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"sun_eu_greek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
sun_eu_greek
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso88598e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88598e\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso88598e\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso88598e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88598e\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso88598e\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso88598e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88598e \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso88598e \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88598e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88598e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88598e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88598e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88598e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88598e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatinhebrew\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatinhebrew\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatinhebrew\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatinhebrew\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatinhebrew\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatinhebrew\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatinhebrew\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatinhebrew \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatinhebrew \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatinhebrew\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatinhebrew
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatinhebrew
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatinhebrew\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatinhebrew
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatinhebrew
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0hebrew\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"hebrew\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0hebrew\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vhebrew\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"hebrew\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vhebrew\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" hebrew\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"hebrew \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" hebrew \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
hebrew\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"hebrew
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
hebrew
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
hebrew\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"hebrew
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
hebrew
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-8-e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8-e\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-8-e\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-8-e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8-e\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-8-e\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-8-e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8-e \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-8-e \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8-e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8-e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8-e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8-e\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8-e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8-e
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-138\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-138\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-138\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-138\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-138\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-138\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-138\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-138 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-138 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-138\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-138
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-138
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-138\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-138
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-138
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88598\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88598\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88598\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88598\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88598\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88598\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88598\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88598 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88598 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88598\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88598
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88598
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88598\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88598
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88598
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-8:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-8:1988\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-8:1988\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-8:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-8:1988\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-8:1988\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-8:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-8:1988 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-8:1988 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-8:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-8:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-8:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-8:1988\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-8:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-8:1988
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0visual\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"visual\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0visual\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vvisual\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"visual\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vvisual\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" visual\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"visual \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" visual \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
visual\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"visual
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
visual
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
visual\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"visual
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
visual
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso88598i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88598i\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso88598i\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso88598i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88598i\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso88598i\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso88598i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88598i \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso88598i \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88598i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88598i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88598i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88598i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso88598i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso88598i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-8-i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8-i\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-8-i\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-8-i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8-i\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-8-i\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-8-i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8-i \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-8-i \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8-i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8-i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8-i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8-i\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-8-i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-8-i
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0logical\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"logical\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0logical\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlogical\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"logical\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlogical\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" logical\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"logical \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" logical \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
logical\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"logical
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
logical
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
logical\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"logical
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
logical
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-10\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-10\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-10\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-10\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-10\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-10\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-10\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-10 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-10 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-10\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-10
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-10
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-10\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-10
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-10
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-157\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-157\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-157\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-157\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-157\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-157\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-157\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-157 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-157 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-157\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-157
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-157
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-157\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-157
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-157
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-10\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-10\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-10\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-10\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-10\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-10\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-10\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-10 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-10 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-10\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-10
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-10
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-10\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-10
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-10
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso885910\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885910\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso885910\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso885910\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885910\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso885910\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso885910\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885910 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso885910 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885910\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885910
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885910
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885910\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885910
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885910
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin6\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin6\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin6 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin6\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin6
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-13\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-13\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-13\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-13\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-13\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-13\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-13\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-13 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-13 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-13\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-13
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-13
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-13\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-13
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-13
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-13\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-13\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-13\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-13\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-13\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-13\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-13\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-13 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-13 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-13\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-13
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-13
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-13\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-13
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-13
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso885913\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885913\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso885913\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso885913\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885913\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso885913\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso885913\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885913 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso885913 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885913\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885913
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885913
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885913\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885913
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885913
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-14\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-14\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-14\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-14\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-14\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-14\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-14\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-14 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-14 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-14\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-14
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-14
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-14\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-14
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-14
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-14\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-14\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-14\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-14\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-14\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-14\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-14\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-14 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-14 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-14\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-14
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-14
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-14\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-14
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-14
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso885914\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885914\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso885914\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso885914\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885914\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso885914\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso885914\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885914 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso885914 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885914\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885914
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885914
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885914\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885914
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885914
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin9\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin9\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin9\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin9\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin9 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin9 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-15\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-15\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-15\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-15\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-15 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-15 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-15\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-15\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-15\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-15\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-15 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-15 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso885915\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885915\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso885915\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso885915\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885915\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso885915\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso885915\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885915 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso885915 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885915\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885915
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885915
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885915\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885915
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885915
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-15\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-15\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-15\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-15\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-15 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-15 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-15\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-15
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l9\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l9\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l9\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl9\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l9 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l9 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-16\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-16\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-16\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-16\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-16\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-16\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-16\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-16 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-16 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-16\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-16
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-16
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-16\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-16
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-16
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cskoi8r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cskoi8r\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cskoi8r\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcskoi8r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cskoi8r\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcskoi8r\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cskoi8r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cskoi8r \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cskoi8r \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cskoi8r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cskoi8r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cskoi8r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cskoi8r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cskoi8r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cskoi8r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi8\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi8\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi8 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi8-r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-r\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi8-r\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi8-r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-r\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi8-r\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi8-r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-r \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi8-r \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi8_r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8_r\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi8_r\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi8_r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8_r\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi8_r\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi8_r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8_r \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi8_r \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8_r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8_r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8_r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8_r\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8_r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8_r
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi8-ru\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-ru\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi8-ru\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi8-ru\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-ru\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi8-ru\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi8-ru\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-ru \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi8-ru \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-ru\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-ru
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-ru
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-ru\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-ru
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-ru
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi8-u\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-u\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0koi8-u\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi8-u\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-u\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkoi8-u\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi8-u\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-u \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" koi8-u \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-u\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-u
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-u
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-u\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"koi8-u
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
koi8-u
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csmacintosh\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csmacintosh\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csmacintosh\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsmacintosh\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csmacintosh\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsmacintosh\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csmacintosh\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csmacintosh \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csmacintosh \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csmacintosh\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csmacintosh
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csmacintosh
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csmacintosh\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csmacintosh
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csmacintosh
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0mac\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"mac\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0mac\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vmac\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"mac\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vmac\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" mac\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"mac \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" mac \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
mac\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"mac
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
mac
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
mac\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"mac
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
mac
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0macintosh\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"macintosh\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0macintosh\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vmacintosh\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"macintosh\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vmacintosh\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" macintosh\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"macintosh \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" macintosh \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
macintosh\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"macintosh
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
macintosh
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
macintosh\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"macintosh
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
macintosh
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-mac-roman\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-roman\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-mac-roman\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-mac-roman\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-roman\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-mac-roman\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-mac-roman\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-roman \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-mac-roman \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-roman\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-roman
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-roman
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-roman\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-roman
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-roman
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0dos-874\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"dos-874\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0dos-874\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vdos-874\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"dos-874\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vdos-874\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" dos-874\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"dos-874 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" dos-874 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
dos-874\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"dos-874
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
dos-874
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
dos-874\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"dos-874
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
dos-874
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-11\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-11\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-11\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-11\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-11\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-11\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-11\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-11 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-11 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-11\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-11
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-11
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-11\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-11
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-11
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-11\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-11\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-11\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-11\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-11\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-11\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-11\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-11 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-11 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-11\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-11
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-11
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-11\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-11
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-11
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso885911\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885911\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso885911\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso885911\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885911\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso885911\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso885911\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885911 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso885911 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885911\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885911
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885911
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885911\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso885911
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso885911
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0tis-620\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"tis-620\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0tis-620\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vtis-620\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"tis-620\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vtis-620\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" tis-620\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"tis-620 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" tis-620 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
tis-620\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"tis-620
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
tis-620
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
tis-620\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"tis-620
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
tis-620
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-874\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-874\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-874\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-874\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-874\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-874\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-874\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-874 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-874 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-874\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-874
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-874
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-874\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-874
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-874
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1250\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1250\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1250\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1250\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1250 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1250 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1250\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1250\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1250\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1250\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1250 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1250 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1250\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1250\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1250\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1250\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1250 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1250 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1250\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1250
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1251\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1251\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1251\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1251\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1251 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1251 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1251\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1251\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1251\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1251\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1251 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1251 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1251\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1251\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1251\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1251\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1251 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1251 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1251\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1251
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ansi_x3.4-1968\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ansi_x3.4-1968\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ansi_x3.4-1968\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vansi_x3.4-1968\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ansi_x3.4-1968\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vansi_x3.4-1968\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ansi_x3.4-1968\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ansi_x3.4-1968 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ansi_x3.4-1968 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ansi_x3.4-1968\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ansi_x3.4-1968
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ansi_x3.4-1968
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ansi_x3.4-1968\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ansi_x3.4-1968
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ansi_x3.4-1968
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ascii\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ascii\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ascii\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vascii\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ascii\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vascii\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ascii\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ascii \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ascii \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ascii\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ascii
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ascii
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ascii\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ascii
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ascii
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1252\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1252\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1252\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1252\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1252 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1252 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp819\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp819\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp819\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp819\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp819\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp819\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp819\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp819 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp819 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp819\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp819
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp819
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp819\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp819
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp819
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ibm819\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ibm819\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ibm819\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vibm819\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ibm819\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vibm819\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ibm819\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ibm819 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ibm819 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ibm819\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ibm819
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ibm819
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ibm819\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ibm819
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ibm819
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-100\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-100\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-100\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-100\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-100\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-100\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-100\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-100 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-100 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-100\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-100
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-100
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-100\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-100
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-100
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88591\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88591\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88591\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88591\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88591\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88591\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88591\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88591 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88591 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88591\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88591
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88591
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88591\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88591
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88591
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-1:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-1:1987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-1:1987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-1:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-1:1987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-1:1987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-1:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-1:1987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-1:1987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-1:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-1:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-1:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-1:1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-1:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-1:1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin1\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin1\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin1 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin1\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin1
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0us-ascii\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"us-ascii\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0us-ascii\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vus-ascii\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"us-ascii\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vus-ascii\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" us-ascii\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"us-ascii \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" us-ascii \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
us-ascii\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"us-ascii
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
us-ascii
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
us-ascii\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"us-ascii
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
us-ascii
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1252\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1252\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1252\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1252\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1252 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1252 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1252\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1252\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1252\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1252\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1252 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1252 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1252\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1252
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1253\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1253\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1253\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1253\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1253 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1253 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1253\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1253\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1253\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1253\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1253 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1253 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1253\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1253\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1253\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1253\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1253 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1253 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1253\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1253
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1254\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1254\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1254\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1254\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1254 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1254 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csisolatin5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsisolatin5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csisolatin5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csisolatin5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csisolatin5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-9\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-8859-9\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-9\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-8859-9\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-9 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-8859-9 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-148\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-148\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-148\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-148\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-148\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-148\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-148\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-148 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-148 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-148\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-148
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-148
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-148\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-148
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-148
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-9\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso8859-9\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-9\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso8859-9\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-9 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso8859-9 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88599\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88599\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso88599\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88599\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88599\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso88599\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88599\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88599 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso88599 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88599\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88599
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88599
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88599\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso88599
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso88599
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-9\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-9\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-9\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-9\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-9 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-9 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-9\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-9
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-9:1989\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-9:1989\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso_8859-9:1989\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-9:1989\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-9:1989\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso_8859-9:1989\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-9:1989\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-9:1989 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso_8859-9:1989 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-9:1989\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-9:1989
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-9:1989
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-9:1989\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso_8859-9:1989
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso_8859-9:1989
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0l5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vl5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" l5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"l5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
l5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0latin5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vlatin5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" latin5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"latin5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
latin5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1254\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1254\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1254\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1254\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1254 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1254 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1254\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1254\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1254\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1254\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1254 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1254 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1254\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1254
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1255\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1255\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1255\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1255\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1255 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1255 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1255\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1255\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1255\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1255\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1255 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1255 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1255\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1255\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1255\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1255\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1255 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1255 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1255\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1255
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1256\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1256\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1256\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1256\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1256 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1256 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1256\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1256\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1256\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1256\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1256 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1256 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1256\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1256\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1256\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1256\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1256 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1256 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1256\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1256
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1257\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1257\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1257\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1257\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1257 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1257 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1257\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1257\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1257\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1257\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1257 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1257 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1257\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1257\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1257\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1257\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1257 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1257 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1257\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1257
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1258\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cp1258\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1258\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcp1258\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1258 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cp1258 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cp1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cp1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1258\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-1258\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1258\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-1258\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1258 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-1258 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1258\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-cp1258\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1258\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-cp1258\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1258 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-cp1258 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1258\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-cp1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-cp1258
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-mac-cyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-cyrillic\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-mac-cyrillic\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-mac-cyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-cyrillic\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-mac-cyrillic\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-mac-cyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-cyrillic \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-mac-cyrillic \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-cyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-cyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-cyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-cyrillic\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-cyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-cyrillic
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-mac-ukrainian\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-ukrainian\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-mac-ukrainian\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-mac-ukrainian\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-ukrainian\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-mac-ukrainian\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-mac-ukrainian\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-ukrainian \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-mac-ukrainian \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-ukrainian\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-ukrainian
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-ukrainian
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-ukrainian\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-mac-ukrainian
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-mac-ukrainian
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0chinese\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"chinese\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0chinese\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vchinese\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"chinese\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vchinese\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" chinese\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"chinese \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" chinese \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
chinese\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"chinese
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
chinese
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
chinese\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"chinese
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
chinese
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csgb2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csgb2312\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csgb2312\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsgb2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csgb2312\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsgb2312\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csgb2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csgb2312 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csgb2312 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csgb2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csgb2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csgb2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csgb2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csgb2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csgb2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso58gb231280\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso58gb231280\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso58gb231280\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso58gb231280\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso58gb231280\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso58gb231280\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso58gb231280\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso58gb231280 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso58gb231280 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso58gb231280\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso58gb231280
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso58gb231280
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso58gb231280\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso58gb231280
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso58gb231280
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0gb2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb2312\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0gb2312\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgb2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb2312\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgb2312\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" gb2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb2312 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" gb2312 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0gb_2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb_2312\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0gb_2312\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgb_2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb_2312\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgb_2312\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" gb_2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb_2312 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" gb_2312 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb_2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb_2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb_2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb_2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb_2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb_2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0gb_2312-80\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb_2312-80\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0gb_2312-80\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgb_2312-80\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb_2312-80\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgb_2312-80\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" gb_2312-80\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb_2312-80 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" gb_2312-80 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb_2312-80\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb_2312-80
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb_2312-80
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb_2312-80\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb_2312-80
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb_2312-80
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0gbk\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gbk\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0gbk\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgbk\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gbk\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgbk\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" gbk\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gbk \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" gbk \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gbk\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gbk
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gbk
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gbk\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gbk
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gbk
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-58\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-58\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-58\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-58\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-58\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-58\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-58\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-58 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-58 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-58\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-58
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-58
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-58\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-58
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-58
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-gbk\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-gbk\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-gbk\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-gbk\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-gbk\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-gbk\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-gbk\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-gbk \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-gbk \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-gbk\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-gbk
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-gbk
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-gbk\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-gbk
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-gbk
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0gb18030\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb18030\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0gb18030\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgb18030\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb18030\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vgb18030\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" gb18030\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb18030 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" gb18030 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb18030\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb18030
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb18030
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb18030\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"gb18030
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
gb18030
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"big5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0big5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vbig5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"big5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vbig5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"big5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" big5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0big5-hkscs\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"big5-hkscs\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0big5-hkscs\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vbig5-hkscs\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"big5-hkscs\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vbig5-hkscs\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" big5-hkscs\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"big5-hkscs \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" big5-hkscs \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
big5-hkscs\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"big5-hkscs
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
big5-hkscs
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
big5-hkscs\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"big5-hkscs
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
big5-hkscs
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cn-big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cn-big5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cn-big5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcn-big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cn-big5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcn-big5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cn-big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cn-big5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cn-big5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cn-big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cn-big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cn-big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cn-big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cn-big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cn-big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csbig5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csbig5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csbig5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsbig5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csbig5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsbig5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csbig5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csbig5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csbig5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csbig5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csbig5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csbig5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csbig5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csbig5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csbig5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-x-big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-x-big5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-x-big5\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-x-big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-x-big5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-x-big5\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-x-big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-x-big5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-x-big5 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-x-big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-x-big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-x-big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-x-big5\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-x-big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-x-big5
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cseucpkdfmtjapanese\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cseucpkdfmtjapanese\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cseucpkdfmtjapanese\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcseucpkdfmtjapanese\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cseucpkdfmtjapanese\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcseucpkdfmtjapanese\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cseucpkdfmtjapanese\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cseucpkdfmtjapanese \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cseucpkdfmtjapanese \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cseucpkdfmtjapanese\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cseucpkdfmtjapanese
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cseucpkdfmtjapanese
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cseucpkdfmtjapanese\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cseucpkdfmtjapanese
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cseucpkdfmtjapanese
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0euc-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"euc-jp\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0euc-jp\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\veuc-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"euc-jp\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\veuc-jp\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" euc-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"euc-jp \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" euc-jp \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
euc-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"euc-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
euc-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
euc-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"euc-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
euc-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-euc-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-euc-jp\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-euc-jp\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-euc-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-euc-jp\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-euc-jp\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-euc-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-euc-jp \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-euc-jp \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-euc-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-euc-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-euc-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-euc-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-euc-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-euc-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso2022jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso2022jp\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso2022jp\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso2022jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso2022jp\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso2022jp\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso2022jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso2022jp \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso2022jp \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso2022jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso2022jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso2022jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso2022jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso2022jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso2022jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-2022-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-jp\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-2022-jp\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-2022-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-jp\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-2022-jp\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-2022-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-jp \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-2022-jp \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-jp\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-jp
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csshiftjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csshiftjis\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csshiftjis\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsshiftjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csshiftjis\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsshiftjis\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csshiftjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csshiftjis \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csshiftjis \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csshiftjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csshiftjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csshiftjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csshiftjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csshiftjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csshiftjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ms932\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ms932\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ms932\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vms932\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ms932\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vms932\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ms932\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ms932 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ms932 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ms932\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ms932
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ms932
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ms932\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ms932
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ms932
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ms_kanji\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ms_kanji\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ms_kanji\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vms_kanji\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ms_kanji\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vms_kanji\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ms_kanji\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ms_kanji \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ms_kanji \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ms_kanji\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ms_kanji
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ms_kanji
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ms_kanji\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ms_kanji
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ms_kanji
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0shift-jis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"shift-jis\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0shift-jis\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vshift-jis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"shift-jis\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vshift-jis\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" shift-jis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"shift-jis \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" shift-jis \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
shift-jis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"shift-jis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
shift-jis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
shift-jis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"shift-jis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
shift-jis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0shift_jis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"shift_jis\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0shift_jis\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vshift_jis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"shift_jis\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vshift_jis\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" shift_jis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"shift_jis \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" shift_jis \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
shift_jis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"shift_jis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
shift_jis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
shift_jis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"shift_jis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
shift_jis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0sjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"sjis\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0sjis\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vsjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"sjis\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vsjis\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" sjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"sjis \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" sjis \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
sjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"sjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
sjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
sjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"sjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
sjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-31j\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-31j\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-31j\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-31j\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-31j\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-31j\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-31j\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-31j \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-31j \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-31j\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-31j
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-31j
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-31j\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-31j
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-31j
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-sjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-sjis\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-sjis\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-sjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-sjis\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-sjis\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-sjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-sjis \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-sjis \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-sjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-sjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-sjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-sjis\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-sjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-sjis
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cseuckr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cseuckr\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0cseuckr\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcseuckr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cseuckr\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcseuckr\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cseuckr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cseuckr \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" cseuckr \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cseuckr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cseuckr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cseuckr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cseuckr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"cseuckr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
cseuckr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csksc56011987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csksc56011987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csksc56011987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsksc56011987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csksc56011987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsksc56011987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csksc56011987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csksc56011987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csksc56011987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csksc56011987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csksc56011987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csksc56011987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csksc56011987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csksc56011987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csksc56011987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0euc-kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"euc-kr\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0euc-kr\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\veuc-kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"euc-kr\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\veuc-kr\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" euc-kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"euc-kr \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" euc-kr \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
euc-kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"euc-kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
euc-kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
euc-kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"euc-kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
euc-kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-149\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-149\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-ir-149\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-149\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-149\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-ir-149\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-149\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-149 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-ir-149 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-149\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-149
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-149
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-149\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-ir-149
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-ir-149
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0korean\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"korean\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0korean\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkorean\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"korean\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vkorean\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" korean\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"korean \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" korean \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
korean\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"korean
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
korean
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
korean\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"korean
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
korean
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ks_c_5601-1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ks_c_5601-1987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ks_c_5601-1987\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vks_c_5601-1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ks_c_5601-1987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vks_c_5601-1987\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ks_c_5601-1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ks_c_5601-1987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ks_c_5601-1987 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ks_c_5601-1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ks_c_5601-1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ks_c_5601-1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ks_c_5601-1987\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ks_c_5601-1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ks_c_5601-1987
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ks_c_5601-1989\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ks_c_5601-1989\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ks_c_5601-1989\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vks_c_5601-1989\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ks_c_5601-1989\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vks_c_5601-1989\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ks_c_5601-1989\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ks_c_5601-1989 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ks_c_5601-1989 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ks_c_5601-1989\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ks_c_5601-1989
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ks_c_5601-1989
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ks_c_5601-1989\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ks_c_5601-1989
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ks_c_5601-1989
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ksc5601\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ksc5601\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ksc5601\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vksc5601\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ksc5601\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vksc5601\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ksc5601\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ksc5601 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ksc5601 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ksc5601\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ksc5601
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ksc5601
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ksc5601\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ksc5601
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ksc5601
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ksc_5601\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ksc_5601\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ksc_5601\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vksc_5601\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ksc_5601\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vksc_5601\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ksc_5601\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ksc_5601 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ksc_5601 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ksc_5601\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ksc_5601
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ksc_5601
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ksc_5601\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ksc_5601
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ksc_5601
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-949\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-949\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0windows-949\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-949\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-949\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vwindows-949\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-949\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-949 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" windows-949 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-949\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-949
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-949
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-949\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"windows-949
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
windows-949
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso2022kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso2022kr\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csiso2022kr\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso2022kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso2022kr\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsiso2022kr\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso2022kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso2022kr \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csiso2022kr \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso2022kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso2022kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso2022kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso2022kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csiso2022kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csiso2022kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0hz-gb-2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"hz-gb-2312\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0hz-gb-2312\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vhz-gb-2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"hz-gb-2312\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vhz-gb-2312\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" hz-gb-2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"hz-gb-2312 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" hz-gb-2312 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
hz-gb-2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"hz-gb-2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
hz-gb-2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
hz-gb-2312\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"hz-gb-2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
hz-gb-2312
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-2022-cn\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-cn\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-2022-cn\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-2022-cn\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-cn\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-2022-cn\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-2022-cn\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-cn \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-2022-cn \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-cn\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-cn
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-cn
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-cn\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-cn
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-cn
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-2022-cn-ext\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-cn-ext\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-2022-cn-ext\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-2022-cn-ext\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-cn-ext\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-2022-cn-ext\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-2022-cn-ext\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-cn-ext \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-2022-cn-ext \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-cn-ext\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-cn-ext
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-cn-ext
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-cn-ext\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-cn-ext
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-cn-ext
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-2022-kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-kr\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-2022-kr\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-2022-kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-kr\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-2022-kr\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-2022-kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-kr \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-2022-kr \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-kr\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-2022-kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-2022-kr
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0replacement\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"replacement\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0replacement\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vreplacement\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"replacement\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vreplacement\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" replacement\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"replacement \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" replacement \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
replacement\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"replacement
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
replacement
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
replacement\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"replacement
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
replacement
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicodefffe\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicodefffe\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicodefffe\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicodefffe\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicodefffe\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicodefffe\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicodefffe\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicodefffe \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicodefffe \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicodefffe\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicodefffe
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicodefffe
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicodefffe\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicodefffe
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicodefffe
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0utf-16be\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16be\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0utf-16be\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vutf-16be\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16be\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vutf-16be\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" utf-16be\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16be \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" utf-16be \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16be\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16be
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16be
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16be\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16be
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16be
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csunicode\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csunicode\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0csunicode\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsunicode\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csunicode\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vcsunicode\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csunicode\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csunicode \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" csunicode \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csunicode\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csunicode
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csunicode
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csunicode\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"csunicode
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
csunicode
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-10646-ucs-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-10646-ucs-2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0iso-10646-ucs-2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-10646-ucs-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-10646-ucs-2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\viso-10646-ucs-2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-10646-ucs-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-10646-ucs-2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" iso-10646-ucs-2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-10646-ucs-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-10646-ucs-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-10646-ucs-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-10646-ucs-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"iso-10646-ucs-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
iso-10646-ucs-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ucs-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ucs-2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0ucs-2\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vucs-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ucs-2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vucs-2\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ucs-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ucs-2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" ucs-2 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ucs-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ucs-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ucs-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ucs-2\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"ucs-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
ucs-2
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicode\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicode\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicode\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicode\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicode\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicode \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicode
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicode
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicodefeff\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicodefeff\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0unicodefeff\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicodefeff\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicodefeff\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vunicodefeff\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicodefeff\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicodefeff \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" unicodefeff \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicodefeff\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicodefeff
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicodefeff
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicodefeff\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"unicodefeff
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
unicodefeff
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0utf-16\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0utf-16\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vutf-16\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vutf-16\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" utf-16\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" utf-16 \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0utf-16le\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16le\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0utf-16le\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vutf-16le\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16le\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vutf-16le\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" utf-16le\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16le \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" utf-16le \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16le\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16le
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16le
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16le\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"utf-16le
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
utf-16le
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-user-defined\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-user-defined\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\0x-user-defined\\0\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-user-defined\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-user-defined\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"\\vx-user-defined\\v\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-user-defined\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-user-defined \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \" x-user-defined \" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-user-defined\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-user-defined
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-user-defined
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-user-defined\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"x-user-defined
\" should be rejected by TextDecoder.": { "status": "PASS" }, "Invalid label \"
x-user-defined
\" should be rejected by TextDecoder.": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/api-replacement-encodings.any.js.json ================================================ { "Label for \"replacement\" should be rejected by API: csiso2022kr": { "status": "PASS" }, "Label for \"replacement\" should be rejected by API: hz-gb-2312": { "status": "PASS" }, "Label for \"replacement\" should be rejected by API: iso-2022-cn": { "status": "PASS" }, "Label for \"replacement\" should be rejected by API: iso-2022-cn-ext": { "status": "PASS" }, "Label for \"replacement\" should be rejected by API: iso-2022-kr": { "status": "PASS" }, "Label for \"replacement\" should be rejected by API: replacement": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/api-surrogates-utf8.any.js.json ================================================ { "Invalid surrogates encoded into UTF-8: Sanity check": { "status": "PASS" }, "Invalid surrogates encoded into UTF-8: Surrogate half (low)": { "status": "PASS" }, "Invalid surrogates encoded into UTF-8: Surrogate half (high)": { "status": "PASS" }, "Invalid surrogates encoded into UTF-8: Surrogate half (low), in a string": { "status": "PASS" }, "Invalid surrogates encoded into UTF-8: Surrogate half (high), in a string": { "status": "PASS" }, "Invalid surrogates encoded into UTF-8: Wrong order": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/encodeInto.any.js.json ================================================ { "encodeInto() into ArrayBuffer with Hi and destination length 0, offset 0, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with Hi and destination length 0, offset 0, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with Hi and destination length 0, offset 4, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with Hi and destination length 0, offset 4, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with Hi and destination length 0, offset 0, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with Hi and destination length 0, offset 0, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with Hi and destination length 0, offset 4, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with Hi and destination length 0, offset 4, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with Hi and destination length 0, offset 0, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with Hi and destination length 0, offset 0, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with Hi and destination length 0, offset 4, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with Hi and destination length 0, offset 4, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with A and destination length 10, offset 0, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with A and destination length 10, offset 0, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with A and destination length 10, offset 4, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with A and destination length 10, offset 4, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with A and destination length 10, offset 0, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with A and destination length 10, offset 0, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with A and destination length 10, offset 4, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with A and destination length 10, offset 4, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with A and destination length 10, offset 0, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with A and destination length 10, offset 0, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with A and destination length 10, offset 4, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with A and destination length 10, offset 4, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆 and destination length 4, offset 0, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆 and destination length 4, offset 0, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆 and destination length 4, offset 4, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆 and destination length 4, offset 4, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆 and destination length 4, offset 0, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆 and destination length 4, offset 0, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆 and destination length 4, offset 4, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆 and destination length 4, offset 4, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆 and destination length 4, offset 0, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆 and destination length 4, offset 0, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆 and destination length 4, offset 4, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆 and destination length 4, offset 4, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆A and destination length 3, offset 0, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆A and destination length 3, offset 0, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆A and destination length 3, offset 4, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆A and destination length 3, offset 4, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆A and destination length 3, offset 0, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆A and destination length 3, offset 0, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆A and destination length 3, offset 4, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆A and destination length 3, offset 4, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆A and destination length 3, offset 0, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆A and destination length 3, offset 0, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with 𝌆A and destination length 3, offset 4, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with 𝌆A and destination length 3, offset 4, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 0, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 0, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 4, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 4, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 0, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 0, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 4, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 4, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 0, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 0, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 4, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with U+d834AU+df06A¥Hi and destination length 10, offset 4, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with AU+df06 and destination length 4, offset 0, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with AU+df06 and destination length 4, offset 0, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with AU+df06 and destination length 4, offset 4, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with AU+df06 and destination length 4, offset 4, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with AU+df06 and destination length 4, offset 0, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with AU+df06 and destination length 4, offset 0, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with AU+df06 and destination length 4, offset 4, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with AU+df06 and destination length 4, offset 4, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with AU+df06 and destination length 4, offset 0, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with AU+df06 and destination length 4, offset 0, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with AU+df06 and destination length 4, offset 4, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with AU+df06 and destination length 4, offset 4, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with ¥¥ and destination length 4, offset 0, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with ¥¥ and destination length 4, offset 0, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with ¥¥ and destination length 4, offset 4, filler 0": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with ¥¥ and destination length 4, offset 4, filler 0": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with ¥¥ and destination length 4, offset 0, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with ¥¥ and destination length 4, offset 0, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with ¥¥ and destination length 4, offset 4, filler 128": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with ¥¥ and destination length 4, offset 4, filler 128": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with ¥¥ and destination length 4, offset 0, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with ¥¥ and destination length 4, offset 0, filler random": { "status": "FAIL" }, "encodeInto() into ArrayBuffer with ¥¥ and destination length 4, offset 4, filler random": { "status": "PASS" }, "encodeInto() into SharedArrayBuffer with ¥¥ and destination length 4, offset 4, filler random": { "status": "FAIL" }, "Invalid encodeInto() destination: DataView, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: DataView, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: Int8Array, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: Int8Array, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: Int16Array, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: Int16Array, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: Int32Array, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: Int32Array, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: Uint16Array, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: Uint16Array, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: Uint32Array, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: Uint32Array, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: Uint8ClampedArray, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: Uint8ClampedArray, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: BigInt64Array, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: BigInt64Array, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: BigUint64Array, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: BigUint64Array, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: Float16Array, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: Float16Array, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: Float32Array, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: Float32Array, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: Float64Array, backed by: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: Float64Array, backed by: SharedArrayBuffer": { "status": "FAIL" }, "Invalid encodeInto() destination: ArrayBuffer": { "status": "PASS" }, "Invalid encodeInto() destination: SharedArrayBuffer": { "status": "PASS" }, "encodeInto() and a detached output buffer": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/idlharness.any.js.json ================================================ { "idl_test setup": { "status": "PASS" }, "idl_test validation": { "status": "PASS" }, "TextDecoder includes TextDecoderCommon: member names are unique": { "status": "PASS" }, "TextEncoder includes TextEncoderCommon: member names are unique": { "status": "PASS" }, "TextDecoderStream includes TextDecoderCommon: member names are unique": { "status": "PASS" }, "TextDecoderStream includes GenericTransformStream: member names are unique": { "status": "PASS" }, "TextEncoderStream includes TextEncoderCommon: member names are unique": { "status": "PASS" }, "TextEncoderStream includes GenericTransformStream: member names are unique": { "status": "PASS" }, "TextDecoder interface: existence and properties of interface object": { "status": "PASS" }, "TextDecoder interface object length": { "status": "PASS" }, "TextDecoder interface object name": { "status": "PASS" }, "TextDecoder interface: existence and properties of interface prototype object": { "status": "PASS" }, "TextDecoder interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "TextDecoder interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "TextDecoder interface: operation decode(optional AllowSharedBufferSource, optional TextDecodeOptions)": { "status": "PASS" }, "TextDecoder interface: attribute encoding": { "status": "PASS" }, "TextDecoder interface: attribute fatal": { "status": "PASS" }, "TextDecoder interface: attribute ignoreBOM": { "status": "PASS" }, "TextDecoder must be primary interface of new TextDecoder()": { "status": "PASS" }, "Stringification of new TextDecoder()": { "status": "PASS" }, "TextDecoder interface: new TextDecoder() must inherit property \"decode(optional AllowSharedBufferSource, optional TextDecodeOptions)\" with the proper type": { "status": "PASS" }, "TextDecoder interface: calling decode(optional AllowSharedBufferSource, optional TextDecodeOptions) on new TextDecoder() with too few arguments must throw TypeError": { "status": "PASS" }, "TextDecoder interface: new TextDecoder() must inherit property \"encoding\" with the proper type": { "status": "PASS" }, "TextDecoder interface: new TextDecoder() must inherit property \"fatal\" with the proper type": { "status": "PASS" }, "TextDecoder interface: new TextDecoder() must inherit property \"ignoreBOM\" with the proper type": { "status": "PASS" }, "TextEncoder interface: existence and properties of interface object": { "status": "PASS" }, "TextEncoder interface object length": { "status": "PASS" }, "TextEncoder interface object name": { "status": "PASS" }, "TextEncoder interface: existence and properties of interface prototype object": { "status": "PASS" }, "TextEncoder interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "TextEncoder interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "TextEncoder interface: operation encode(optional USVString)": { "status": "PASS" }, "TextEncoder interface: operation encodeInto(USVString, Uint8Array)": { "status": "PASS" }, "TextEncoder interface: attribute encoding": { "status": "PASS" }, "TextEncoder must be primary interface of new TextEncoder()": { "status": "PASS" }, "Stringification of new TextEncoder()": { "status": "PASS" }, "TextEncoder interface: new TextEncoder() must inherit property \"encode(optional USVString)\" with the proper type": { "status": "PASS" }, "TextEncoder interface: calling encode(optional USVString) on new TextEncoder() with too few arguments must throw TypeError": { "status": "PASS" }, "TextEncoder interface: new TextEncoder() must inherit property \"encodeInto(USVString, Uint8Array)\" with the proper type": { "status": "PASS" }, "TextEncoder interface: calling encodeInto(USVString, Uint8Array) on new TextEncoder() with too few arguments must throw TypeError": { "status": "PASS" }, "TextEncoder interface: new TextEncoder() must inherit property \"encoding\" with the proper type": { "status": "PASS" }, "TextDecoderStream interface: existence and properties of interface object": { "status": "FAIL" }, "TextDecoderStream interface object length": { "status": "FAIL" }, "TextDecoderStream interface object name": { "status": "FAIL" }, "TextDecoderStream interface: existence and properties of interface prototype object": { "status": "FAIL" }, "TextDecoderStream interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "FAIL" }, "TextDecoderStream interface: existence and properties of interface prototype object's @@unscopables property": { "status": "FAIL" }, "TextDecoderStream interface: attribute encoding": { "status": "FAIL" }, "TextDecoderStream interface: attribute fatal": { "status": "FAIL" }, "TextDecoderStream interface: attribute ignoreBOM": { "status": "FAIL" }, "TextEncoderStream interface: existence and properties of interface object": { "status": "FAIL" }, "TextEncoderStream interface object length": { "status": "FAIL" }, "TextEncoderStream interface object name": { "status": "FAIL" }, "TextEncoderStream interface: existence and properties of interface prototype object": { "status": "FAIL" }, "TextEncoderStream interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "FAIL" }, "TextEncoderStream interface: existence and properties of interface prototype object's @@unscopables property": { "status": "FAIL" }, "TextEncoderStream interface: attribute encoding": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/iso-2022-jp-decoder.any.js.json ================================================ { "iso-2022-jp decoder: Error ESC": { "status": "PASS" }, "iso-2022-jp decoder: Error ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: ASCII ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: Double ASCII ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: character, ASCII ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: characters": { "status": "PASS" }, "iso-2022-jp decoder: SO / SI": { "status": "PASS" }, "iso-2022-jp decoder: Roman ESC, characters": { "status": "PASS" }, "iso-2022-jp decoder: Roman ESC, SO / SI": { "status": "PASS" }, "iso-2022-jp decoder: Roman ESC, error ESC, Katakana ESC": { "status": "PASS" }, "iso-2022-jp decoder: Katakana ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: Katakana ESC, multibyte ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: Katakana ESC, error ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: Katakana ESC, error ESC #2, character": { "status": "PASS" }, "iso-2022-jp decoder: Katakana ESC, character, Katakana ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: Katakana ESC, SO / SI": { "status": "PASS" }, "iso-2022-jp decoder: Multibyte ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: Multibyte ESC #2, character": { "status": "PASS" }, "iso-2022-jp decoder: Multibyte ESC, error ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: Double multibyte ESC": { "status": "PASS" }, "iso-2022-jp decoder: Double multibyte ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: Double multibyte ESC #2, character": { "status": "PASS" }, "iso-2022-jp decoder: Multibyte ESC, error ESC #2, character": { "status": "PASS" }, "iso-2022-jp decoder: Multibyte ESC, single byte, multibyte ESC, character": { "status": "PASS" }, "iso-2022-jp decoder: Multibyte ESC, lead error byte": { "status": "PASS" }, "iso-2022-jp decoder: Multibyte ESC, trail error byte": { "status": "PASS" }, "iso-2022-jp decoder: character, error ESC": { "status": "PASS" }, "iso-2022-jp decoder: character, error ESC #2": { "status": "PASS" }, "iso-2022-jp decoder: character, error ESC #3": { "status": "PASS" }, "iso-2022-jp decoder: character, ASCII ESC": { "status": "PASS" }, "iso-2022-jp decoder: character, Roman ESC": { "status": "PASS" }, "iso-2022-jp decoder: character, Katakana ESC": { "status": "PASS" }, "iso-2022-jp decoder: character, Multibyte ESC": { "status": "PASS" }, "iso-2022-jp decoder: character, Multibyte ESC #2": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/replacement-encodings.any.js.json ================================================ { "csiso2022kr - non-empty input decodes to one replacement character.": { "status": "FAIL" }, "csiso2022kr - empty input decodes to empty output.": { "status": "FAIL" }, "hz-gb-2312 - non-empty input decodes to one replacement character.": { "status": "FAIL" }, "hz-gb-2312 - empty input decodes to empty output.": { "status": "FAIL" }, "iso-2022-cn - non-empty input decodes to one replacement character.": { "status": "FAIL" }, "iso-2022-cn - empty input decodes to empty output.": { "status": "FAIL" }, "iso-2022-cn-ext - non-empty input decodes to one replacement character.": { "status": "FAIL" }, "iso-2022-cn-ext - empty input decodes to empty output.": { "status": "FAIL" }, "iso-2022-kr - non-empty input decodes to one replacement character.": { "status": "FAIL" }, "iso-2022-kr - empty input decodes to empty output.": { "status": "FAIL" }, "replacement - non-empty input decodes to one replacement character.": { "status": "FAIL" }, "replacement - empty input decodes to empty output.": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-arguments.any.js.json ================================================ { "TextDecoder decode() with explicit undefined": { "status": "PASS" }, "TextDecoder decode() with undefined and undefined": { "status": "PASS" }, "TextDecoder decode() with undefined and options": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-byte-order-marks.any.js.json ================================================ { "Byte-order marks: utf-8": { "status": "PASS" }, "Byte-order marks: utf-16le": { "status": "PASS" }, "Byte-order marks: utf-16be": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-copy.any.js.json ================================================ { "Modify buffer after passing it in (ArrayBuffer)": { "status": "PASS" }, "Modify buffer after passing it in (SharedArrayBuffer)": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-eof.any.js.json ================================================ { "TextDecoder end-of-queue handling": { "status": "PASS" }, "TextDecoder end-of-queue handling using stream: true": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-fatal-single-byte.any.js.json ================================================ { "Not throw: IBM866 has a pointer 0": { "status": "PASS" }, "Not throw: IBM866 has a pointer 1": { "status": "PASS" }, "Not throw: IBM866 has a pointer 2": { "status": "PASS" }, "Not throw: IBM866 has a pointer 3": { "status": "PASS" }, "Not throw: IBM866 has a pointer 4": { "status": "PASS" }, "Not throw: IBM866 has a pointer 5": { "status": "PASS" }, "Not throw: IBM866 has a pointer 6": { "status": "PASS" }, "Not throw: IBM866 has a pointer 7": { "status": "PASS" }, "Not throw: IBM866 has a pointer 8": { "status": "PASS" }, "Not throw: IBM866 has a pointer 9": { "status": "PASS" }, "Not throw: IBM866 has a pointer 10": { "status": "PASS" }, "Not throw: IBM866 has a pointer 11": { "status": "PASS" }, "Not throw: IBM866 has a pointer 12": { "status": "PASS" }, "Not throw: IBM866 has a pointer 13": { "status": "PASS" }, "Not throw: IBM866 has a pointer 14": { "status": "PASS" }, "Not throw: IBM866 has a pointer 15": { "status": "PASS" }, "Not throw: IBM866 has a pointer 16": { "status": "PASS" }, "Not throw: IBM866 has a pointer 17": { "status": "PASS" }, "Not throw: IBM866 has a pointer 18": { "status": "PASS" }, "Not throw: IBM866 has a pointer 19": { "status": "PASS" }, "Not throw: IBM866 has a pointer 20": { "status": "PASS" }, "Not throw: IBM866 has a pointer 21": { "status": "PASS" }, "Not throw: IBM866 has a pointer 22": { "status": "PASS" }, "Not throw: IBM866 has a pointer 23": { "status": "PASS" }, "Not throw: IBM866 has a pointer 24": { "status": "PASS" }, "Not throw: IBM866 has a pointer 25": { "status": "PASS" }, "Not throw: IBM866 has a pointer 26": { "status": "PASS" }, "Not throw: IBM866 has a pointer 27": { "status": "PASS" }, "Not throw: IBM866 has a pointer 28": { "status": "PASS" }, "Not throw: IBM866 has a pointer 29": { "status": "PASS" }, "Not throw: IBM866 has a pointer 30": { "status": "PASS" }, "Not throw: IBM866 has a pointer 31": { "status": "PASS" }, "Not throw: IBM866 has a pointer 32": { "status": "PASS" }, "Not throw: IBM866 has a pointer 33": { "status": "PASS" }, "Not throw: IBM866 has a pointer 34": { "status": "PASS" }, "Not throw: IBM866 has a pointer 35": { "status": "PASS" }, "Not throw: IBM866 has a pointer 36": { "status": "PASS" }, "Not throw: IBM866 has a pointer 37": { "status": "PASS" }, "Not throw: IBM866 has a pointer 38": { "status": "PASS" }, "Not throw: IBM866 has a pointer 39": { "status": "PASS" }, "Not throw: IBM866 has a pointer 40": { "status": "PASS" }, "Not throw: IBM866 has a pointer 41": { "status": "PASS" }, "Not throw: IBM866 has a pointer 42": { "status": "PASS" }, "Not throw: IBM866 has a pointer 43": { "status": "PASS" }, "Not throw: IBM866 has a pointer 44": { "status": "PASS" }, "Not throw: IBM866 has a pointer 45": { "status": "PASS" }, "Not throw: IBM866 has a pointer 46": { "status": "PASS" }, "Not throw: IBM866 has a pointer 47": { "status": "PASS" }, "Not throw: IBM866 has a pointer 48": { "status": "PASS" }, "Not throw: IBM866 has a pointer 49": { "status": "PASS" }, "Not throw: IBM866 has a pointer 50": { "status": "PASS" }, "Not throw: IBM866 has a pointer 51": { "status": "PASS" }, "Not throw: IBM866 has a pointer 52": { "status": "PASS" }, "Not throw: IBM866 has a pointer 53": { "status": "PASS" }, "Not throw: IBM866 has a pointer 54": { "status": "PASS" }, "Not throw: IBM866 has a pointer 55": { "status": "PASS" }, "Not throw: IBM866 has a pointer 56": { "status": "PASS" }, "Not throw: IBM866 has a pointer 57": { "status": "PASS" }, "Not throw: IBM866 has a pointer 58": { "status": "PASS" }, "Not throw: IBM866 has a pointer 59": { "status": "PASS" }, "Not throw: IBM866 has a pointer 60": { "status": "PASS" }, "Not throw: IBM866 has a pointer 61": { "status": "PASS" }, "Not throw: IBM866 has a pointer 62": { "status": "PASS" }, "Not throw: IBM866 has a pointer 63": { "status": "PASS" }, "Not throw: IBM866 has a pointer 64": { "status": "PASS" }, "Not throw: IBM866 has a pointer 65": { "status": "PASS" }, "Not throw: IBM866 has a pointer 66": { "status": "PASS" }, "Not throw: IBM866 has a pointer 67": { "status": "PASS" }, "Not throw: IBM866 has a pointer 68": { "status": "PASS" }, "Not throw: IBM866 has a pointer 69": { "status": "PASS" }, "Not throw: IBM866 has a pointer 70": { "status": "PASS" }, "Not throw: IBM866 has a pointer 71": { "status": "PASS" }, "Not throw: IBM866 has a pointer 72": { "status": "PASS" }, "Not throw: IBM866 has a pointer 73": { "status": "PASS" }, "Not throw: IBM866 has a pointer 74": { "status": "PASS" }, "Not throw: IBM866 has a pointer 75": { "status": "PASS" }, "Not throw: IBM866 has a pointer 76": { "status": "PASS" }, "Not throw: IBM866 has a pointer 77": { "status": "PASS" }, "Not throw: IBM866 has a pointer 78": { "status": "PASS" }, "Not throw: IBM866 has a pointer 79": { "status": "PASS" }, "Not throw: IBM866 has a pointer 80": { "status": "PASS" }, "Not throw: IBM866 has a pointer 81": { "status": "PASS" }, "Not throw: IBM866 has a pointer 82": { "status": "PASS" }, "Not throw: IBM866 has a pointer 83": { "status": "PASS" }, "Not throw: IBM866 has a pointer 84": { "status": "PASS" }, "Not throw: IBM866 has a pointer 85": { "status": "PASS" }, "Not throw: IBM866 has a pointer 86": { "status": "PASS" }, "Not throw: IBM866 has a pointer 87": { "status": "PASS" }, "Not throw: IBM866 has a pointer 88": { "status": "PASS" }, "Not throw: IBM866 has a pointer 89": { "status": "PASS" }, "Not throw: IBM866 has a pointer 90": { "status": "PASS" }, "Not throw: IBM866 has a pointer 91": { "status": "PASS" }, "Not throw: IBM866 has a pointer 92": { "status": "PASS" }, "Not throw: IBM866 has a pointer 93": { "status": "PASS" }, "Not throw: IBM866 has a pointer 94": { "status": "PASS" }, "Not throw: IBM866 has a pointer 95": { "status": "PASS" }, "Not throw: IBM866 has a pointer 96": { "status": "PASS" }, "Not throw: IBM866 has a pointer 97": { "status": "PASS" }, "Not throw: IBM866 has a pointer 98": { "status": "PASS" }, "Not throw: IBM866 has a pointer 99": { "status": "PASS" }, "Not throw: IBM866 has a pointer 100": { "status": "PASS" }, "Not throw: IBM866 has a pointer 101": { "status": "PASS" }, "Not throw: IBM866 has a pointer 102": { "status": "PASS" }, "Not throw: IBM866 has a pointer 103": { "status": "PASS" }, "Not throw: IBM866 has a pointer 104": { "status": "PASS" }, "Not throw: IBM866 has a pointer 105": { "status": "PASS" }, "Not throw: IBM866 has a pointer 106": { "status": "PASS" }, "Not throw: IBM866 has a pointer 107": { "status": "PASS" }, "Not throw: IBM866 has a pointer 108": { "status": "PASS" }, "Not throw: IBM866 has a pointer 109": { "status": "PASS" }, "Not throw: IBM866 has a pointer 110": { "status": "PASS" }, "Not throw: IBM866 has a pointer 111": { "status": "PASS" }, "Not throw: IBM866 has a pointer 112": { "status": "PASS" }, "Not throw: IBM866 has a pointer 113": { "status": "PASS" }, "Not throw: IBM866 has a pointer 114": { "status": "PASS" }, "Not throw: IBM866 has a pointer 115": { "status": "PASS" }, "Not throw: IBM866 has a pointer 116": { "status": "PASS" }, "Not throw: IBM866 has a pointer 117": { "status": "PASS" }, "Not throw: IBM866 has a pointer 118": { "status": "PASS" }, "Not throw: IBM866 has a pointer 119": { "status": "PASS" }, "Not throw: IBM866 has a pointer 120": { "status": "PASS" }, "Not throw: IBM866 has a pointer 121": { "status": "PASS" }, "Not throw: IBM866 has a pointer 122": { "status": "PASS" }, "Not throw: IBM866 has a pointer 123": { "status": "PASS" }, "Not throw: IBM866 has a pointer 124": { "status": "PASS" }, "Not throw: IBM866 has a pointer 125": { "status": "PASS" }, "Not throw: IBM866 has a pointer 126": { "status": "PASS" }, "Not throw: IBM866 has a pointer 127": { "status": "PASS" }, "Not throw: IBM866 has a pointer 128": { "status": "PASS" }, "Not throw: IBM866 has a pointer 129": { "status": "PASS" }, "Not throw: IBM866 has a pointer 130": { "status": "PASS" }, "Not throw: IBM866 has a pointer 131": { "status": "PASS" }, "Not throw: IBM866 has a pointer 132": { "status": "PASS" }, "Not throw: IBM866 has a pointer 133": { "status": "PASS" }, "Not throw: IBM866 has a pointer 134": { "status": "PASS" }, "Not throw: IBM866 has a pointer 135": { "status": "PASS" }, "Not throw: IBM866 has a pointer 136": { "status": "PASS" }, "Not throw: IBM866 has a pointer 137": { "status": "PASS" }, "Not throw: IBM866 has a pointer 138": { "status": "PASS" }, "Not throw: IBM866 has a pointer 139": { "status": "PASS" }, "Not throw: IBM866 has a pointer 140": { "status": "PASS" }, "Not throw: IBM866 has a pointer 141": { "status": "PASS" }, "Not throw: IBM866 has a pointer 142": { "status": "PASS" }, "Not throw: IBM866 has a pointer 143": { "status": "PASS" }, "Not throw: IBM866 has a pointer 144": { "status": "PASS" }, "Not throw: IBM866 has a pointer 145": { "status": "PASS" }, "Not throw: IBM866 has a pointer 146": { "status": "PASS" }, "Not throw: IBM866 has a pointer 147": { "status": "PASS" }, "Not throw: IBM866 has a pointer 148": { "status": "PASS" }, "Not throw: IBM866 has a pointer 149": { "status": "PASS" }, "Not throw: IBM866 has a pointer 150": { "status": "PASS" }, "Not throw: IBM866 has a pointer 151": { "status": "PASS" }, "Not throw: IBM866 has a pointer 152": { "status": "PASS" }, "Not throw: IBM866 has a pointer 153": { "status": "PASS" }, "Not throw: IBM866 has a pointer 154": { "status": "PASS" }, "Not throw: IBM866 has a pointer 155": { "status": "PASS" }, "Not throw: IBM866 has a pointer 156": { "status": "PASS" }, "Not throw: IBM866 has a pointer 157": { "status": "PASS" }, "Not throw: IBM866 has a pointer 158": { "status": "PASS" }, "Not throw: IBM866 has a pointer 159": { "status": "PASS" }, "Not throw: IBM866 has a pointer 160": { "status": "PASS" }, "Not throw: IBM866 has a pointer 161": { "status": "PASS" }, "Not throw: IBM866 has a pointer 162": { "status": "PASS" }, "Not throw: IBM866 has a pointer 163": { "status": "PASS" }, "Not throw: IBM866 has a pointer 164": { "status": "PASS" }, "Not throw: IBM866 has a pointer 165": { "status": "PASS" }, "Not throw: IBM866 has a pointer 166": { "status": "PASS" }, "Not throw: IBM866 has a pointer 167": { "status": "PASS" }, "Not throw: IBM866 has a pointer 168": { "status": "PASS" }, "Not throw: IBM866 has a pointer 169": { "status": "PASS" }, "Not throw: IBM866 has a pointer 170": { "status": "PASS" }, "Not throw: IBM866 has a pointer 171": { "status": "PASS" }, "Not throw: IBM866 has a pointer 172": { "status": "PASS" }, "Not throw: IBM866 has a pointer 173": { "status": "PASS" }, "Not throw: IBM866 has a pointer 174": { "status": "PASS" }, "Not throw: IBM866 has a pointer 175": { "status": "PASS" }, "Not throw: IBM866 has a pointer 176": { "status": "PASS" }, "Not throw: IBM866 has a pointer 177": { "status": "PASS" }, "Not throw: IBM866 has a pointer 178": { "status": "PASS" }, "Not throw: IBM866 has a pointer 179": { "status": "PASS" }, "Not throw: IBM866 has a pointer 180": { "status": "PASS" }, "Not throw: IBM866 has a pointer 181": { "status": "PASS" }, "Not throw: IBM866 has a pointer 182": { "status": "PASS" }, "Not throw: IBM866 has a pointer 183": { "status": "PASS" }, "Not throw: IBM866 has a pointer 184": { "status": "PASS" }, "Not throw: IBM866 has a pointer 185": { "status": "PASS" }, "Not throw: IBM866 has a pointer 186": { "status": "PASS" }, "Not throw: IBM866 has a pointer 187": { "status": "PASS" }, "Not throw: IBM866 has a pointer 188": { "status": "PASS" }, "Not throw: IBM866 has a pointer 189": { "status": "PASS" }, "Not throw: IBM866 has a pointer 190": { "status": "PASS" }, "Not throw: IBM866 has a pointer 191": { "status": "PASS" }, "Not throw: IBM866 has a pointer 192": { "status": "PASS" }, "Not throw: IBM866 has a pointer 193": { "status": "PASS" }, "Not throw: IBM866 has a pointer 194": { "status": "PASS" }, "Not throw: IBM866 has a pointer 195": { "status": "PASS" }, "Not throw: IBM866 has a pointer 196": { "status": "PASS" }, "Not throw: IBM866 has a pointer 197": { "status": "PASS" }, "Not throw: IBM866 has a pointer 198": { "status": "PASS" }, "Not throw: IBM866 has a pointer 199": { "status": "PASS" }, "Not throw: IBM866 has a pointer 200": { "status": "PASS" }, "Not throw: IBM866 has a pointer 201": { "status": "PASS" }, "Not throw: IBM866 has a pointer 202": { "status": "PASS" }, "Not throw: IBM866 has a pointer 203": { "status": "PASS" }, "Not throw: IBM866 has a pointer 204": { "status": "PASS" }, "Not throw: IBM866 has a pointer 205": { "status": "PASS" }, "Not throw: IBM866 has a pointer 206": { "status": "PASS" }, "Not throw: IBM866 has a pointer 207": { "status": "PASS" }, "Not throw: IBM866 has a pointer 208": { "status": "PASS" }, "Not throw: IBM866 has a pointer 209": { "status": "PASS" }, "Not throw: IBM866 has a pointer 210": { "status": "PASS" }, "Not throw: IBM866 has a pointer 211": { "status": "PASS" }, "Not throw: IBM866 has a pointer 212": { "status": "PASS" }, "Not throw: IBM866 has a pointer 213": { "status": "PASS" }, "Not throw: IBM866 has a pointer 214": { "status": "PASS" }, "Not throw: IBM866 has a pointer 215": { "status": "PASS" }, "Not throw: IBM866 has a pointer 216": { "status": "PASS" }, "Not throw: IBM866 has a pointer 217": { "status": "PASS" }, "Not throw: IBM866 has a pointer 218": { "status": "PASS" }, "Not throw: IBM866 has a pointer 219": { "status": "PASS" }, "Not throw: IBM866 has a pointer 220": { "status": "PASS" }, "Not throw: IBM866 has a pointer 221": { "status": "PASS" }, "Not throw: IBM866 has a pointer 222": { "status": "PASS" }, "Not throw: IBM866 has a pointer 223": { "status": "PASS" }, "Not throw: IBM866 has a pointer 224": { "status": "PASS" }, "Not throw: IBM866 has a pointer 225": { "status": "PASS" }, "Not throw: IBM866 has a pointer 226": { "status": "PASS" }, "Not throw: IBM866 has a pointer 227": { "status": "PASS" }, "Not throw: IBM866 has a pointer 228": { "status": "PASS" }, "Not throw: IBM866 has a pointer 229": { "status": "PASS" }, "Not throw: IBM866 has a pointer 230": { "status": "PASS" }, "Not throw: IBM866 has a pointer 231": { "status": "PASS" }, "Not throw: IBM866 has a pointer 232": { "status": "PASS" }, "Not throw: IBM866 has a pointer 233": { "status": "PASS" }, "Not throw: IBM866 has a pointer 234": { "status": "PASS" }, "Not throw: IBM866 has a pointer 235": { "status": "PASS" }, "Not throw: IBM866 has a pointer 236": { "status": "PASS" }, "Not throw: IBM866 has a pointer 237": { "status": "PASS" }, "Not throw: IBM866 has a pointer 238": { "status": "PASS" }, "Not throw: IBM866 has a pointer 239": { "status": "PASS" }, "Not throw: IBM866 has a pointer 240": { "status": "PASS" }, "Not throw: IBM866 has a pointer 241": { "status": "PASS" }, "Not throw: IBM866 has a pointer 242": { "status": "PASS" }, "Not throw: IBM866 has a pointer 243": { "status": "PASS" }, "Not throw: IBM866 has a pointer 244": { "status": "PASS" }, "Not throw: IBM866 has a pointer 245": { "status": "PASS" }, "Not throw: IBM866 has a pointer 246": { "status": "PASS" }, "Not throw: IBM866 has a pointer 247": { "status": "PASS" }, "Not throw: IBM866 has a pointer 248": { "status": "PASS" }, "Not throw: IBM866 has a pointer 249": { "status": "PASS" }, "Not throw: IBM866 has a pointer 250": { "status": "PASS" }, "Not throw: IBM866 has a pointer 251": { "status": "PASS" }, "Not throw: IBM866 has a pointer 252": { "status": "PASS" }, "Not throw: IBM866 has a pointer 253": { "status": "PASS" }, "Not throw: IBM866 has a pointer 254": { "status": "PASS" }, "Not throw: IBM866 has a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 160": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 173": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 191": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 194": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 207": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 209": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 218": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 219": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 220": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 221": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 250": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 251": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 254": { "status": "PASS" }, "Not throw: ISO-8859-2 has a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 160": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 164": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-3 doesn't have a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 173": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-3 doesn't have a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 189": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-3 doesn't have a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 191": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 194": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-3 doesn't have a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 207": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-3 doesn't have a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 209": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 218": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 219": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 220": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 221": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 226": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-3 doesn't have a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 239": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-3 doesn't have a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 250": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 251": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 254": { "status": "PASS" }, "Not throw: ISO-8859-3 has a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 160": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 173": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 191": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 194": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 207": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 209": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 218": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 219": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 220": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 221": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 250": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 251": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 254": { "status": "PASS" }, "Not throw: ISO-8859-4 has a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 160": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 173": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 191": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 194": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 207": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 209": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 218": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 219": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 220": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 221": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 250": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 251": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 254": { "status": "PASS" }, "Not throw: ISO-8859-5 has a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 160": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 161": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 162": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 164": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 165": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 166": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 167": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 168": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 169": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 170": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 173": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 174": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 175": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 176": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 177": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 178": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 179": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 180": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 181": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 182": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 183": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 184": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 185": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 187": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 188": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 189": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 191": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 194": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 207": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 209": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 218": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 219": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 220": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 221": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 222": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-6 has a pointer 242": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 243": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 244": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 245": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 246": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 247": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 248": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 249": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 250": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 251": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 252": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 253": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 254": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-6 doesn't have a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 160": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 173": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-7 doesn't have a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 191": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 194": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 207": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 209": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-7 doesn't have a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 218": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 219": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 220": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 221": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 250": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 251": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-7 has a pointer 254": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-7 doesn't have a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 160": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 173": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 190": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 191": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 192": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 193": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 194": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 195": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 196": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 197": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 198": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 199": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 200": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 201": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 202": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 203": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 204": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 205": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 206": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 207": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 208": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 209": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 210": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 211": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 212": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 213": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 214": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 215": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 216": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 217": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 218": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 219": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 220": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 221": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 250": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 251": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-8 has a pointer 254": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8 doesn't have a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 160": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 173": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 190": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 191": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 192": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 193": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 194": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 195": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 196": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 197": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 198": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 199": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 200": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 201": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 202": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 203": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 204": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 205": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 206": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 207": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 208": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 209": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 210": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 211": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 212": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 213": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 214": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 215": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 216": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 217": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 218": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 219": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 220": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 221": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 250": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 251": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-8-I has a pointer 254": { "status": "PASS" }, "Throw due to fatal flag: ISO-8859-8-I doesn't have a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 160": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 173": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 191": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 194": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 207": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 209": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 218": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 219": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 220": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 221": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 250": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 251": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 254": { "status": "PASS" }, "Not throw: ISO-8859-10 has a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 160": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 173": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 191": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 194": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 207": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 209": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 218": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 219": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 220": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 221": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 250": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 251": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 254": { "status": "PASS" }, "Not throw: ISO-8859-13 has a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 160": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 173": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 191": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 194": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 207": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 209": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 218": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 219": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 220": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 221": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 250": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 251": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 254": { "status": "PASS" }, "Not throw: ISO-8859-14 has a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 160": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 173": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 191": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 194": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 207": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 209": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 218": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 219": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 220": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 221": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 250": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 251": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 254": { "status": "PASS" }, "Not throw: ISO-8859-15 has a pointer 255": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 0": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 1": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 2": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 3": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 4": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 5": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 6": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 7": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 8": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 9": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 10": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 11": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 12": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 13": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 14": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 15": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 16": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 17": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 18": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 19": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 20": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 21": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 22": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 23": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 24": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 25": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 26": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 27": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 28": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 29": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 30": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 31": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 32": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 33": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 34": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 35": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 36": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 37": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 38": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 39": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 40": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 41": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 42": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 43": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 44": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 45": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 46": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 47": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 48": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 49": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 50": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 51": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 52": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 53": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 54": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 55": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 56": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 57": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 58": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 59": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 60": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 61": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 62": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 63": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 64": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 65": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 66": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 67": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 68": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 69": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 70": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 71": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 72": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 73": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 74": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 75": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 76": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 77": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 78": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 79": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 80": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 81": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 82": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 83": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 84": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 85": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 86": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 87": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 88": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 89": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 90": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 91": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 92": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 93": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 94": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 95": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 96": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 97": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 98": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 99": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 100": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 101": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 102": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 103": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 104": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 105": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 106": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 107": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 108": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 109": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 110": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 111": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 112": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 113": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 114": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 115": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 116": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 117": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 118": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 119": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 120": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 121": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 122": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 123": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 124": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 125": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 126": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 127": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 128": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 129": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 130": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 131": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 132": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 133": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 134": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 135": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 136": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 137": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 138": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 139": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 140": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 141": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 142": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 143": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 144": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 145": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 146": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 147": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 148": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 149": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 150": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 151": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 152": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 153": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 154": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 155": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 156": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 157": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 158": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 159": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 160": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 161": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 162": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 163": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 164": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 165": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 166": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 167": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 168": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 169": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 170": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 171": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 172": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 173": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 174": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 175": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 176": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 177": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 178": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 179": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 180": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 181": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 182": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 183": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 184": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 185": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 186": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 187": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 188": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 189": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 190": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 191": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 192": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 193": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 194": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 195": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 196": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 197": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 198": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 199": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 200": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 201": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 202": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 203": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 204": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 205": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 206": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 207": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 208": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 209": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 210": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 211": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 212": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 213": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 214": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 215": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 216": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 217": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 218": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 219": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 220": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 221": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 222": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 223": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 224": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 225": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 226": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 227": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 228": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 229": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 230": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 231": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 232": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 233": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 234": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 235": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 236": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 237": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 238": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 239": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 240": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 241": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 242": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 243": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 244": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 245": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 246": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 247": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 248": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 249": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 250": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 251": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 252": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 253": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 254": { "status": "PASS" }, "Not throw: ISO-8859-16 has a pointer 255": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 0": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 1": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 2": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 3": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 4": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 5": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 6": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 7": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 8": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 9": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 10": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 11": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 12": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 13": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 14": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 15": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 16": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 17": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 18": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 19": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 20": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 21": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 22": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 23": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 24": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 25": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 26": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 27": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 28": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 29": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 30": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 31": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 32": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 33": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 34": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 35": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 36": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 37": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 38": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 39": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 40": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 41": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 42": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 43": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 44": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 45": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 46": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 47": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 48": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 49": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 50": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 51": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 52": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 53": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 54": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 55": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 56": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 57": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 58": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 59": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 60": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 61": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 62": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 63": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 64": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 65": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 66": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 67": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 68": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 69": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 70": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 71": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 72": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 73": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 74": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 75": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 76": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 77": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 78": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 79": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 80": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 81": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 82": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 83": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 84": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 85": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 86": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 87": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 88": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 89": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 90": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 91": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 92": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 93": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 94": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 95": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 96": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 97": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 98": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 99": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 100": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 101": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 102": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 103": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 104": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 105": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 106": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 107": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 108": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 109": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 110": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 111": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 112": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 113": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 114": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 115": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 116": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 117": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 118": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 119": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 120": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 121": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 122": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 123": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 124": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 125": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 126": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 127": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 128": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 129": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 130": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 131": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 132": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 133": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 134": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 135": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 136": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 137": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 138": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 139": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 140": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 141": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 142": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 143": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 144": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 145": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 146": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 147": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 148": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 149": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 150": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 151": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 152": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 153": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 154": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 155": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 156": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 157": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 158": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 159": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 160": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 161": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 162": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 163": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 164": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 165": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 166": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 167": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 168": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 169": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 170": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 171": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 172": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 173": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 174": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 175": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 176": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 177": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 178": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 179": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 180": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 181": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 182": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 183": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 184": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 185": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 186": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 187": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 188": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 189": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 190": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 191": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 192": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 193": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 194": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 195": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 196": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 197": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 198": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 199": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 200": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 201": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 202": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 203": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 204": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 205": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 206": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 207": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 208": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 209": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 210": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 211": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 212": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 213": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 214": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 215": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 216": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 217": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 218": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 219": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 220": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 221": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 222": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 223": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 224": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 225": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 226": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 227": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 228": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 229": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 230": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 231": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 232": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 233": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 234": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 235": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 236": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 237": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 238": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 239": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 240": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 241": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 242": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 243": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 244": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 245": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 246": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 247": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 248": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 249": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 250": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 251": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 252": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 253": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 254": { "status": "PASS" }, "Not throw: KOI8-R has a pointer 255": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 0": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 1": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 2": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 3": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 4": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 5": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 6": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 7": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 8": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 9": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 10": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 11": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 12": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 13": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 14": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 15": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 16": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 17": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 18": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 19": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 20": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 21": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 22": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 23": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 24": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 25": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 26": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 27": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 28": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 29": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 30": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 31": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 32": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 33": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 34": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 35": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 36": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 37": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 38": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 39": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 40": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 41": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 42": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 43": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 44": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 45": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 46": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 47": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 48": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 49": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 50": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 51": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 52": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 53": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 54": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 55": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 56": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 57": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 58": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 59": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 60": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 61": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 62": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 63": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 64": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 65": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 66": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 67": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 68": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 69": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 70": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 71": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 72": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 73": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 74": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 75": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 76": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 77": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 78": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 79": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 80": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 81": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 82": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 83": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 84": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 85": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 86": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 87": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 88": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 89": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 90": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 91": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 92": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 93": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 94": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 95": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 96": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 97": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 98": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 99": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 100": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 101": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 102": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 103": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 104": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 105": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 106": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 107": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 108": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 109": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 110": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 111": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 112": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 113": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 114": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 115": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 116": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 117": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 118": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 119": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 120": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 121": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 122": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 123": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 124": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 125": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 126": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 127": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 128": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 129": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 130": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 131": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 132": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 133": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 134": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 135": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 136": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 137": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 138": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 139": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 140": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 141": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 142": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 143": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 144": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 145": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 146": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 147": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 148": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 149": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 150": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 151": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 152": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 153": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 154": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 155": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 156": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 157": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 158": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 159": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 160": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 161": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 162": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 163": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 164": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 165": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 166": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 167": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 168": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 169": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 170": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 171": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 172": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 173": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 174": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 175": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 176": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 177": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 178": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 179": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 180": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 181": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 182": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 183": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 184": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 185": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 186": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 187": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 188": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 189": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 190": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 191": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 192": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 193": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 194": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 195": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 196": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 197": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 198": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 199": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 200": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 201": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 202": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 203": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 204": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 205": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 206": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 207": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 208": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 209": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 210": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 211": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 212": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 213": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 214": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 215": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 216": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 217": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 218": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 219": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 220": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 221": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 222": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 223": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 224": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 225": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 226": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 227": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 228": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 229": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 230": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 231": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 232": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 233": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 234": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 235": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 236": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 237": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 238": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 239": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 240": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 241": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 242": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 243": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 244": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 245": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 246": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 247": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 248": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 249": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 250": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 251": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 252": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 253": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 254": { "status": "PASS" }, "Not throw: KOI8-U has a pointer 255": { "status": "PASS" }, "Not throw: macintosh has a pointer 0": { "status": "PASS" }, "Not throw: macintosh has a pointer 1": { "status": "PASS" }, "Not throw: macintosh has a pointer 2": { "status": "PASS" }, "Not throw: macintosh has a pointer 3": { "status": "PASS" }, "Not throw: macintosh has a pointer 4": { "status": "PASS" }, "Not throw: macintosh has a pointer 5": { "status": "PASS" }, "Not throw: macintosh has a pointer 6": { "status": "PASS" }, "Not throw: macintosh has a pointer 7": { "status": "PASS" }, "Not throw: macintosh has a pointer 8": { "status": "PASS" }, "Not throw: macintosh has a pointer 9": { "status": "PASS" }, "Not throw: macintosh has a pointer 10": { "status": "PASS" }, "Not throw: macintosh has a pointer 11": { "status": "PASS" }, "Not throw: macintosh has a pointer 12": { "status": "PASS" }, "Not throw: macintosh has a pointer 13": { "status": "PASS" }, "Not throw: macintosh has a pointer 14": { "status": "PASS" }, "Not throw: macintosh has a pointer 15": { "status": "PASS" }, "Not throw: macintosh has a pointer 16": { "status": "PASS" }, "Not throw: macintosh has a pointer 17": { "status": "PASS" }, "Not throw: macintosh has a pointer 18": { "status": "PASS" }, "Not throw: macintosh has a pointer 19": { "status": "PASS" }, "Not throw: macintosh has a pointer 20": { "status": "PASS" }, "Not throw: macintosh has a pointer 21": { "status": "PASS" }, "Not throw: macintosh has a pointer 22": { "status": "PASS" }, "Not throw: macintosh has a pointer 23": { "status": "PASS" }, "Not throw: macintosh has a pointer 24": { "status": "PASS" }, "Not throw: macintosh has a pointer 25": { "status": "PASS" }, "Not throw: macintosh has a pointer 26": { "status": "PASS" }, "Not throw: macintosh has a pointer 27": { "status": "PASS" }, "Not throw: macintosh has a pointer 28": { "status": "PASS" }, "Not throw: macintosh has a pointer 29": { "status": "PASS" }, "Not throw: macintosh has a pointer 30": { "status": "PASS" }, "Not throw: macintosh has a pointer 31": { "status": "PASS" }, "Not throw: macintosh has a pointer 32": { "status": "PASS" }, "Not throw: macintosh has a pointer 33": { "status": "PASS" }, "Not throw: macintosh has a pointer 34": { "status": "PASS" }, "Not throw: macintosh has a pointer 35": { "status": "PASS" }, "Not throw: macintosh has a pointer 36": { "status": "PASS" }, "Not throw: macintosh has a pointer 37": { "status": "PASS" }, "Not throw: macintosh has a pointer 38": { "status": "PASS" }, "Not throw: macintosh has a pointer 39": { "status": "PASS" }, "Not throw: macintosh has a pointer 40": { "status": "PASS" }, "Not throw: macintosh has a pointer 41": { "status": "PASS" }, "Not throw: macintosh has a pointer 42": { "status": "PASS" }, "Not throw: macintosh has a pointer 43": { "status": "PASS" }, "Not throw: macintosh has a pointer 44": { "status": "PASS" }, "Not throw: macintosh has a pointer 45": { "status": "PASS" }, "Not throw: macintosh has a pointer 46": { "status": "PASS" }, "Not throw: macintosh has a pointer 47": { "status": "PASS" }, "Not throw: macintosh has a pointer 48": { "status": "PASS" }, "Not throw: macintosh has a pointer 49": { "status": "PASS" }, "Not throw: macintosh has a pointer 50": { "status": "PASS" }, "Not throw: macintosh has a pointer 51": { "status": "PASS" }, "Not throw: macintosh has a pointer 52": { "status": "PASS" }, "Not throw: macintosh has a pointer 53": { "status": "PASS" }, "Not throw: macintosh has a pointer 54": { "status": "PASS" }, "Not throw: macintosh has a pointer 55": { "status": "PASS" }, "Not throw: macintosh has a pointer 56": { "status": "PASS" }, "Not throw: macintosh has a pointer 57": { "status": "PASS" }, "Not throw: macintosh has a pointer 58": { "status": "PASS" }, "Not throw: macintosh has a pointer 59": { "status": "PASS" }, "Not throw: macintosh has a pointer 60": { "status": "PASS" }, "Not throw: macintosh has a pointer 61": { "status": "PASS" }, "Not throw: macintosh has a pointer 62": { "status": "PASS" }, "Not throw: macintosh has a pointer 63": { "status": "PASS" }, "Not throw: macintosh has a pointer 64": { "status": "PASS" }, "Not throw: macintosh has a pointer 65": { "status": "PASS" }, "Not throw: macintosh has a pointer 66": { "status": "PASS" }, "Not throw: macintosh has a pointer 67": { "status": "PASS" }, "Not throw: macintosh has a pointer 68": { "status": "PASS" }, "Not throw: macintosh has a pointer 69": { "status": "PASS" }, "Not throw: macintosh has a pointer 70": { "status": "PASS" }, "Not throw: macintosh has a pointer 71": { "status": "PASS" }, "Not throw: macintosh has a pointer 72": { "status": "PASS" }, "Not throw: macintosh has a pointer 73": { "status": "PASS" }, "Not throw: macintosh has a pointer 74": { "status": "PASS" }, "Not throw: macintosh has a pointer 75": { "status": "PASS" }, "Not throw: macintosh has a pointer 76": { "status": "PASS" }, "Not throw: macintosh has a pointer 77": { "status": "PASS" }, "Not throw: macintosh has a pointer 78": { "status": "PASS" }, "Not throw: macintosh has a pointer 79": { "status": "PASS" }, "Not throw: macintosh has a pointer 80": { "status": "PASS" }, "Not throw: macintosh has a pointer 81": { "status": "PASS" }, "Not throw: macintosh has a pointer 82": { "status": "PASS" }, "Not throw: macintosh has a pointer 83": { "status": "PASS" }, "Not throw: macintosh has a pointer 84": { "status": "PASS" }, "Not throw: macintosh has a pointer 85": { "status": "PASS" }, "Not throw: macintosh has a pointer 86": { "status": "PASS" }, "Not throw: macintosh has a pointer 87": { "status": "PASS" }, "Not throw: macintosh has a pointer 88": { "status": "PASS" }, "Not throw: macintosh has a pointer 89": { "status": "PASS" }, "Not throw: macintosh has a pointer 90": { "status": "PASS" }, "Not throw: macintosh has a pointer 91": { "status": "PASS" }, "Not throw: macintosh has a pointer 92": { "status": "PASS" }, "Not throw: macintosh has a pointer 93": { "status": "PASS" }, "Not throw: macintosh has a pointer 94": { "status": "PASS" }, "Not throw: macintosh has a pointer 95": { "status": "PASS" }, "Not throw: macintosh has a pointer 96": { "status": "PASS" }, "Not throw: macintosh has a pointer 97": { "status": "PASS" }, "Not throw: macintosh has a pointer 98": { "status": "PASS" }, "Not throw: macintosh has a pointer 99": { "status": "PASS" }, "Not throw: macintosh has a pointer 100": { "status": "PASS" }, "Not throw: macintosh has a pointer 101": { "status": "PASS" }, "Not throw: macintosh has a pointer 102": { "status": "PASS" }, "Not throw: macintosh has a pointer 103": { "status": "PASS" }, "Not throw: macintosh has a pointer 104": { "status": "PASS" }, "Not throw: macintosh has a pointer 105": { "status": "PASS" }, "Not throw: macintosh has a pointer 106": { "status": "PASS" }, "Not throw: macintosh has a pointer 107": { "status": "PASS" }, "Not throw: macintosh has a pointer 108": { "status": "PASS" }, "Not throw: macintosh has a pointer 109": { "status": "PASS" }, "Not throw: macintosh has a pointer 110": { "status": "PASS" }, "Not throw: macintosh has a pointer 111": { "status": "PASS" }, "Not throw: macintosh has a pointer 112": { "status": "PASS" }, "Not throw: macintosh has a pointer 113": { "status": "PASS" }, "Not throw: macintosh has a pointer 114": { "status": "PASS" }, "Not throw: macintosh has a pointer 115": { "status": "PASS" }, "Not throw: macintosh has a pointer 116": { "status": "PASS" }, "Not throw: macintosh has a pointer 117": { "status": "PASS" }, "Not throw: macintosh has a pointer 118": { "status": "PASS" }, "Not throw: macintosh has a pointer 119": { "status": "PASS" }, "Not throw: macintosh has a pointer 120": { "status": "PASS" }, "Not throw: macintosh has a pointer 121": { "status": "PASS" }, "Not throw: macintosh has a pointer 122": { "status": "PASS" }, "Not throw: macintosh has a pointer 123": { "status": "PASS" }, "Not throw: macintosh has a pointer 124": { "status": "PASS" }, "Not throw: macintosh has a pointer 125": { "status": "PASS" }, "Not throw: macintosh has a pointer 126": { "status": "PASS" }, "Not throw: macintosh has a pointer 127": { "status": "PASS" }, "Not throw: macintosh has a pointer 128": { "status": "PASS" }, "Not throw: macintosh has a pointer 129": { "status": "PASS" }, "Not throw: macintosh has a pointer 130": { "status": "PASS" }, "Not throw: macintosh has a pointer 131": { "status": "PASS" }, "Not throw: macintosh has a pointer 132": { "status": "PASS" }, "Not throw: macintosh has a pointer 133": { "status": "PASS" }, "Not throw: macintosh has a pointer 134": { "status": "PASS" }, "Not throw: macintosh has a pointer 135": { "status": "PASS" }, "Not throw: macintosh has a pointer 136": { "status": "PASS" }, "Not throw: macintosh has a pointer 137": { "status": "PASS" }, "Not throw: macintosh has a pointer 138": { "status": "PASS" }, "Not throw: macintosh has a pointer 139": { "status": "PASS" }, "Not throw: macintosh has a pointer 140": { "status": "PASS" }, "Not throw: macintosh has a pointer 141": { "status": "PASS" }, "Not throw: macintosh has a pointer 142": { "status": "PASS" }, "Not throw: macintosh has a pointer 143": { "status": "PASS" }, "Not throw: macintosh has a pointer 144": { "status": "PASS" }, "Not throw: macintosh has a pointer 145": { "status": "PASS" }, "Not throw: macintosh has a pointer 146": { "status": "PASS" }, "Not throw: macintosh has a pointer 147": { "status": "PASS" }, "Not throw: macintosh has a pointer 148": { "status": "PASS" }, "Not throw: macintosh has a pointer 149": { "status": "PASS" }, "Not throw: macintosh has a pointer 150": { "status": "PASS" }, "Not throw: macintosh has a pointer 151": { "status": "PASS" }, "Not throw: macintosh has a pointer 152": { "status": "PASS" }, "Not throw: macintosh has a pointer 153": { "status": "PASS" }, "Not throw: macintosh has a pointer 154": { "status": "PASS" }, "Not throw: macintosh has a pointer 155": { "status": "PASS" }, "Not throw: macintosh has a pointer 156": { "status": "PASS" }, "Not throw: macintosh has a pointer 157": { "status": "PASS" }, "Not throw: macintosh has a pointer 158": { "status": "PASS" }, "Not throw: macintosh has a pointer 159": { "status": "PASS" }, "Not throw: macintosh has a pointer 160": { "status": "PASS" }, "Not throw: macintosh has a pointer 161": { "status": "PASS" }, "Not throw: macintosh has a pointer 162": { "status": "PASS" }, "Not throw: macintosh has a pointer 163": { "status": "PASS" }, "Not throw: macintosh has a pointer 164": { "status": "PASS" }, "Not throw: macintosh has a pointer 165": { "status": "PASS" }, "Not throw: macintosh has a pointer 166": { "status": "PASS" }, "Not throw: macintosh has a pointer 167": { "status": "PASS" }, "Not throw: macintosh has a pointer 168": { "status": "PASS" }, "Not throw: macintosh has a pointer 169": { "status": "PASS" }, "Not throw: macintosh has a pointer 170": { "status": "PASS" }, "Not throw: macintosh has a pointer 171": { "status": "PASS" }, "Not throw: macintosh has a pointer 172": { "status": "PASS" }, "Not throw: macintosh has a pointer 173": { "status": "PASS" }, "Not throw: macintosh has a pointer 174": { "status": "PASS" }, "Not throw: macintosh has a pointer 175": { "status": "PASS" }, "Not throw: macintosh has a pointer 176": { "status": "PASS" }, "Not throw: macintosh has a pointer 177": { "status": "PASS" }, "Not throw: macintosh has a pointer 178": { "status": "PASS" }, "Not throw: macintosh has a pointer 179": { "status": "PASS" }, "Not throw: macintosh has a pointer 180": { "status": "PASS" }, "Not throw: macintosh has a pointer 181": { "status": "PASS" }, "Not throw: macintosh has a pointer 182": { "status": "PASS" }, "Not throw: macintosh has a pointer 183": { "status": "PASS" }, "Not throw: macintosh has a pointer 184": { "status": "PASS" }, "Not throw: macintosh has a pointer 185": { "status": "PASS" }, "Not throw: macintosh has a pointer 186": { "status": "PASS" }, "Not throw: macintosh has a pointer 187": { "status": "PASS" }, "Not throw: macintosh has a pointer 188": { "status": "PASS" }, "Not throw: macintosh has a pointer 189": { "status": "PASS" }, "Not throw: macintosh has a pointer 190": { "status": "PASS" }, "Not throw: macintosh has a pointer 191": { "status": "PASS" }, "Not throw: macintosh has a pointer 192": { "status": "PASS" }, "Not throw: macintosh has a pointer 193": { "status": "PASS" }, "Not throw: macintosh has a pointer 194": { "status": "PASS" }, "Not throw: macintosh has a pointer 195": { "status": "PASS" }, "Not throw: macintosh has a pointer 196": { "status": "PASS" }, "Not throw: macintosh has a pointer 197": { "status": "PASS" }, "Not throw: macintosh has a pointer 198": { "status": "PASS" }, "Not throw: macintosh has a pointer 199": { "status": "PASS" }, "Not throw: macintosh has a pointer 200": { "status": "PASS" }, "Not throw: macintosh has a pointer 201": { "status": "PASS" }, "Not throw: macintosh has a pointer 202": { "status": "PASS" }, "Not throw: macintosh has a pointer 203": { "status": "PASS" }, "Not throw: macintosh has a pointer 204": { "status": "PASS" }, "Not throw: macintosh has a pointer 205": { "status": "PASS" }, "Not throw: macintosh has a pointer 206": { "status": "PASS" }, "Not throw: macintosh has a pointer 207": { "status": "PASS" }, "Not throw: macintosh has a pointer 208": { "status": "PASS" }, "Not throw: macintosh has a pointer 209": { "status": "PASS" }, "Not throw: macintosh has a pointer 210": { "status": "PASS" }, "Not throw: macintosh has a pointer 211": { "status": "PASS" }, "Not throw: macintosh has a pointer 212": { "status": "PASS" }, "Not throw: macintosh has a pointer 213": { "status": "PASS" }, "Not throw: macintosh has a pointer 214": { "status": "PASS" }, "Not throw: macintosh has a pointer 215": { "status": "PASS" }, "Not throw: macintosh has a pointer 216": { "status": "PASS" }, "Not throw: macintosh has a pointer 217": { "status": "PASS" }, "Not throw: macintosh has a pointer 218": { "status": "PASS" }, "Not throw: macintosh has a pointer 219": { "status": "PASS" }, "Not throw: macintosh has a pointer 220": { "status": "PASS" }, "Not throw: macintosh has a pointer 221": { "status": "PASS" }, "Not throw: macintosh has a pointer 222": { "status": "PASS" }, "Not throw: macintosh has a pointer 223": { "status": "PASS" }, "Not throw: macintosh has a pointer 224": { "status": "PASS" }, "Not throw: macintosh has a pointer 225": { "status": "PASS" }, "Not throw: macintosh has a pointer 226": { "status": "PASS" }, "Not throw: macintosh has a pointer 227": { "status": "PASS" }, "Not throw: macintosh has a pointer 228": { "status": "PASS" }, "Not throw: macintosh has a pointer 229": { "status": "PASS" }, "Not throw: macintosh has a pointer 230": { "status": "PASS" }, "Not throw: macintosh has a pointer 231": { "status": "PASS" }, "Not throw: macintosh has a pointer 232": { "status": "PASS" }, "Not throw: macintosh has a pointer 233": { "status": "PASS" }, "Not throw: macintosh has a pointer 234": { "status": "PASS" }, "Not throw: macintosh has a pointer 235": { "status": "PASS" }, "Not throw: macintosh has a pointer 236": { "status": "PASS" }, "Not throw: macintosh has a pointer 237": { "status": "PASS" }, "Not throw: macintosh has a pointer 238": { "status": "PASS" }, "Not throw: macintosh has a pointer 239": { "status": "PASS" }, "Not throw: macintosh has a pointer 240": { "status": "PASS" }, "Not throw: macintosh has a pointer 241": { "status": "PASS" }, "Not throw: macintosh has a pointer 242": { "status": "PASS" }, "Not throw: macintosh has a pointer 243": { "status": "PASS" }, "Not throw: macintosh has a pointer 244": { "status": "PASS" }, "Not throw: macintosh has a pointer 245": { "status": "PASS" }, "Not throw: macintosh has a pointer 246": { "status": "PASS" }, "Not throw: macintosh has a pointer 247": { "status": "PASS" }, "Not throw: macintosh has a pointer 248": { "status": "PASS" }, "Not throw: macintosh has a pointer 249": { "status": "PASS" }, "Not throw: macintosh has a pointer 250": { "status": "PASS" }, "Not throw: macintosh has a pointer 251": { "status": "PASS" }, "Not throw: macintosh has a pointer 252": { "status": "PASS" }, "Not throw: macintosh has a pointer 253": { "status": "PASS" }, "Not throw: macintosh has a pointer 254": { "status": "PASS" }, "Not throw: macintosh has a pointer 255": { "status": "PASS" }, "Not throw: windows-874 has a pointer 0": { "status": "PASS" }, "Not throw: windows-874 has a pointer 1": { "status": "PASS" }, "Not throw: windows-874 has a pointer 2": { "status": "PASS" }, "Not throw: windows-874 has a pointer 3": { "status": "PASS" }, "Not throw: windows-874 has a pointer 4": { "status": "PASS" }, "Not throw: windows-874 has a pointer 5": { "status": "PASS" }, "Not throw: windows-874 has a pointer 6": { "status": "PASS" }, "Not throw: windows-874 has a pointer 7": { "status": "PASS" }, "Not throw: windows-874 has a pointer 8": { "status": "PASS" }, "Not throw: windows-874 has a pointer 9": { "status": "PASS" }, "Not throw: windows-874 has a pointer 10": { "status": "PASS" }, "Not throw: windows-874 has a pointer 11": { "status": "PASS" }, "Not throw: windows-874 has a pointer 12": { "status": "PASS" }, "Not throw: windows-874 has a pointer 13": { "status": "PASS" }, "Not throw: windows-874 has a pointer 14": { "status": "PASS" }, "Not throw: windows-874 has a pointer 15": { "status": "PASS" }, "Not throw: windows-874 has a pointer 16": { "status": "PASS" }, "Not throw: windows-874 has a pointer 17": { "status": "PASS" }, "Not throw: windows-874 has a pointer 18": { "status": "PASS" }, "Not throw: windows-874 has a pointer 19": { "status": "PASS" }, "Not throw: windows-874 has a pointer 20": { "status": "PASS" }, "Not throw: windows-874 has a pointer 21": { "status": "PASS" }, "Not throw: windows-874 has a pointer 22": { "status": "PASS" }, "Not throw: windows-874 has a pointer 23": { "status": "PASS" }, "Not throw: windows-874 has a pointer 24": { "status": "PASS" }, "Not throw: windows-874 has a pointer 25": { "status": "PASS" }, "Not throw: windows-874 has a pointer 26": { "status": "PASS" }, "Not throw: windows-874 has a pointer 27": { "status": "PASS" }, "Not throw: windows-874 has a pointer 28": { "status": "PASS" }, "Not throw: windows-874 has a pointer 29": { "status": "PASS" }, "Not throw: windows-874 has a pointer 30": { "status": "PASS" }, "Not throw: windows-874 has a pointer 31": { "status": "PASS" }, "Not throw: windows-874 has a pointer 32": { "status": "PASS" }, "Not throw: windows-874 has a pointer 33": { "status": "PASS" }, "Not throw: windows-874 has a pointer 34": { "status": "PASS" }, "Not throw: windows-874 has a pointer 35": { "status": "PASS" }, "Not throw: windows-874 has a pointer 36": { "status": "PASS" }, "Not throw: windows-874 has a pointer 37": { "status": "PASS" }, "Not throw: windows-874 has a pointer 38": { "status": "PASS" }, "Not throw: windows-874 has a pointer 39": { "status": "PASS" }, "Not throw: windows-874 has a pointer 40": { "status": "PASS" }, "Not throw: windows-874 has a pointer 41": { "status": "PASS" }, "Not throw: windows-874 has a pointer 42": { "status": "PASS" }, "Not throw: windows-874 has a pointer 43": { "status": "PASS" }, "Not throw: windows-874 has a pointer 44": { "status": "PASS" }, "Not throw: windows-874 has a pointer 45": { "status": "PASS" }, "Not throw: windows-874 has a pointer 46": { "status": "PASS" }, "Not throw: windows-874 has a pointer 47": { "status": "PASS" }, "Not throw: windows-874 has a pointer 48": { "status": "PASS" }, "Not throw: windows-874 has a pointer 49": { "status": "PASS" }, "Not throw: windows-874 has a pointer 50": { "status": "PASS" }, "Not throw: windows-874 has a pointer 51": { "status": "PASS" }, "Not throw: windows-874 has a pointer 52": { "status": "PASS" }, "Not throw: windows-874 has a pointer 53": { "status": "PASS" }, "Not throw: windows-874 has a pointer 54": { "status": "PASS" }, "Not throw: windows-874 has a pointer 55": { "status": "PASS" }, "Not throw: windows-874 has a pointer 56": { "status": "PASS" }, "Not throw: windows-874 has a pointer 57": { "status": "PASS" }, "Not throw: windows-874 has a pointer 58": { "status": "PASS" }, "Not throw: windows-874 has a pointer 59": { "status": "PASS" }, "Not throw: windows-874 has a pointer 60": { "status": "PASS" }, "Not throw: windows-874 has a pointer 61": { "status": "PASS" }, "Not throw: windows-874 has a pointer 62": { "status": "PASS" }, "Not throw: windows-874 has a pointer 63": { "status": "PASS" }, "Not throw: windows-874 has a pointer 64": { "status": "PASS" }, "Not throw: windows-874 has a pointer 65": { "status": "PASS" }, "Not throw: windows-874 has a pointer 66": { "status": "PASS" }, "Not throw: windows-874 has a pointer 67": { "status": "PASS" }, "Not throw: windows-874 has a pointer 68": { "status": "PASS" }, "Not throw: windows-874 has a pointer 69": { "status": "PASS" }, "Not throw: windows-874 has a pointer 70": { "status": "PASS" }, "Not throw: windows-874 has a pointer 71": { "status": "PASS" }, "Not throw: windows-874 has a pointer 72": { "status": "PASS" }, "Not throw: windows-874 has a pointer 73": { "status": "PASS" }, "Not throw: windows-874 has a pointer 74": { "status": "PASS" }, "Not throw: windows-874 has a pointer 75": { "status": "PASS" }, "Not throw: windows-874 has a pointer 76": { "status": "PASS" }, "Not throw: windows-874 has a pointer 77": { "status": "PASS" }, "Not throw: windows-874 has a pointer 78": { "status": "PASS" }, "Not throw: windows-874 has a pointer 79": { "status": "PASS" }, "Not throw: windows-874 has a pointer 80": { "status": "PASS" }, "Not throw: windows-874 has a pointer 81": { "status": "PASS" }, "Not throw: windows-874 has a pointer 82": { "status": "PASS" }, "Not throw: windows-874 has a pointer 83": { "status": "PASS" }, "Not throw: windows-874 has a pointer 84": { "status": "PASS" }, "Not throw: windows-874 has a pointer 85": { "status": "PASS" }, "Not throw: windows-874 has a pointer 86": { "status": "PASS" }, "Not throw: windows-874 has a pointer 87": { "status": "PASS" }, "Not throw: windows-874 has a pointer 88": { "status": "PASS" }, "Not throw: windows-874 has a pointer 89": { "status": "PASS" }, "Not throw: windows-874 has a pointer 90": { "status": "PASS" }, "Not throw: windows-874 has a pointer 91": { "status": "PASS" }, "Not throw: windows-874 has a pointer 92": { "status": "PASS" }, "Not throw: windows-874 has a pointer 93": { "status": "PASS" }, "Not throw: windows-874 has a pointer 94": { "status": "PASS" }, "Not throw: windows-874 has a pointer 95": { "status": "PASS" }, "Not throw: windows-874 has a pointer 96": { "status": "PASS" }, "Not throw: windows-874 has a pointer 97": { "status": "PASS" }, "Not throw: windows-874 has a pointer 98": { "status": "PASS" }, "Not throw: windows-874 has a pointer 99": { "status": "PASS" }, "Not throw: windows-874 has a pointer 100": { "status": "PASS" }, "Not throw: windows-874 has a pointer 101": { "status": "PASS" }, "Not throw: windows-874 has a pointer 102": { "status": "PASS" }, "Not throw: windows-874 has a pointer 103": { "status": "PASS" }, "Not throw: windows-874 has a pointer 104": { "status": "PASS" }, "Not throw: windows-874 has a pointer 105": { "status": "PASS" }, "Not throw: windows-874 has a pointer 106": { "status": "PASS" }, "Not throw: windows-874 has a pointer 107": { "status": "PASS" }, "Not throw: windows-874 has a pointer 108": { "status": "PASS" }, "Not throw: windows-874 has a pointer 109": { "status": "PASS" }, "Not throw: windows-874 has a pointer 110": { "status": "PASS" }, "Not throw: windows-874 has a pointer 111": { "status": "PASS" }, "Not throw: windows-874 has a pointer 112": { "status": "PASS" }, "Not throw: windows-874 has a pointer 113": { "status": "PASS" }, "Not throw: windows-874 has a pointer 114": { "status": "PASS" }, "Not throw: windows-874 has a pointer 115": { "status": "PASS" }, "Not throw: windows-874 has a pointer 116": { "status": "PASS" }, "Not throw: windows-874 has a pointer 117": { "status": "PASS" }, "Not throw: windows-874 has a pointer 118": { "status": "PASS" }, "Not throw: windows-874 has a pointer 119": { "status": "PASS" }, "Not throw: windows-874 has a pointer 120": { "status": "PASS" }, "Not throw: windows-874 has a pointer 121": { "status": "PASS" }, "Not throw: windows-874 has a pointer 122": { "status": "PASS" }, "Not throw: windows-874 has a pointer 123": { "status": "PASS" }, "Not throw: windows-874 has a pointer 124": { "status": "PASS" }, "Not throw: windows-874 has a pointer 125": { "status": "PASS" }, "Not throw: windows-874 has a pointer 126": { "status": "PASS" }, "Not throw: windows-874 has a pointer 127": { "status": "PASS" }, "Not throw: windows-874 has a pointer 128": { "status": "PASS" }, "Not throw: windows-874 has a pointer 129": { "status": "PASS" }, "Not throw: windows-874 has a pointer 130": { "status": "PASS" }, "Not throw: windows-874 has a pointer 131": { "status": "PASS" }, "Not throw: windows-874 has a pointer 132": { "status": "PASS" }, "Not throw: windows-874 has a pointer 133": { "status": "PASS" }, "Not throw: windows-874 has a pointer 134": { "status": "PASS" }, "Not throw: windows-874 has a pointer 135": { "status": "PASS" }, "Not throw: windows-874 has a pointer 136": { "status": "PASS" }, "Not throw: windows-874 has a pointer 137": { "status": "PASS" }, "Not throw: windows-874 has a pointer 138": { "status": "PASS" }, "Not throw: windows-874 has a pointer 139": { "status": "PASS" }, "Not throw: windows-874 has a pointer 140": { "status": "PASS" }, "Not throw: windows-874 has a pointer 141": { "status": "PASS" }, "Not throw: windows-874 has a pointer 142": { "status": "PASS" }, "Not throw: windows-874 has a pointer 143": { "status": "PASS" }, "Not throw: windows-874 has a pointer 144": { "status": "PASS" }, "Not throw: windows-874 has a pointer 145": { "status": "PASS" }, "Not throw: windows-874 has a pointer 146": { "status": "PASS" }, "Not throw: windows-874 has a pointer 147": { "status": "PASS" }, "Not throw: windows-874 has a pointer 148": { "status": "PASS" }, "Not throw: windows-874 has a pointer 149": { "status": "PASS" }, "Not throw: windows-874 has a pointer 150": { "status": "PASS" }, "Not throw: windows-874 has a pointer 151": { "status": "PASS" }, "Not throw: windows-874 has a pointer 152": { "status": "PASS" }, "Not throw: windows-874 has a pointer 153": { "status": "PASS" }, "Not throw: windows-874 has a pointer 154": { "status": "PASS" }, "Not throw: windows-874 has a pointer 155": { "status": "PASS" }, "Not throw: windows-874 has a pointer 156": { "status": "PASS" }, "Not throw: windows-874 has a pointer 157": { "status": "PASS" }, "Not throw: windows-874 has a pointer 158": { "status": "PASS" }, "Not throw: windows-874 has a pointer 159": { "status": "PASS" }, "Not throw: windows-874 has a pointer 160": { "status": "PASS" }, "Not throw: windows-874 has a pointer 161": { "status": "PASS" }, "Not throw: windows-874 has a pointer 162": { "status": "PASS" }, "Not throw: windows-874 has a pointer 163": { "status": "PASS" }, "Not throw: windows-874 has a pointer 164": { "status": "PASS" }, "Not throw: windows-874 has a pointer 165": { "status": "PASS" }, "Not throw: windows-874 has a pointer 166": { "status": "PASS" }, "Not throw: windows-874 has a pointer 167": { "status": "PASS" }, "Not throw: windows-874 has a pointer 168": { "status": "PASS" }, "Not throw: windows-874 has a pointer 169": { "status": "PASS" }, "Not throw: windows-874 has a pointer 170": { "status": "PASS" }, "Not throw: windows-874 has a pointer 171": { "status": "PASS" }, "Not throw: windows-874 has a pointer 172": { "status": "PASS" }, "Not throw: windows-874 has a pointer 173": { "status": "PASS" }, "Not throw: windows-874 has a pointer 174": { "status": "PASS" }, "Not throw: windows-874 has a pointer 175": { "status": "PASS" }, "Not throw: windows-874 has a pointer 176": { "status": "PASS" }, "Not throw: windows-874 has a pointer 177": { "status": "PASS" }, "Not throw: windows-874 has a pointer 178": { "status": "PASS" }, "Not throw: windows-874 has a pointer 179": { "status": "PASS" }, "Not throw: windows-874 has a pointer 180": { "status": "PASS" }, "Not throw: windows-874 has a pointer 181": { "status": "PASS" }, "Not throw: windows-874 has a pointer 182": { "status": "PASS" }, "Not throw: windows-874 has a pointer 183": { "status": "PASS" }, "Not throw: windows-874 has a pointer 184": { "status": "PASS" }, "Not throw: windows-874 has a pointer 185": { "status": "PASS" }, "Not throw: windows-874 has a pointer 186": { "status": "PASS" }, "Not throw: windows-874 has a pointer 187": { "status": "PASS" }, "Not throw: windows-874 has a pointer 188": { "status": "PASS" }, "Not throw: windows-874 has a pointer 189": { "status": "PASS" }, "Not throw: windows-874 has a pointer 190": { "status": "PASS" }, "Not throw: windows-874 has a pointer 191": { "status": "PASS" }, "Not throw: windows-874 has a pointer 192": { "status": "PASS" }, "Not throw: windows-874 has a pointer 193": { "status": "PASS" }, "Not throw: windows-874 has a pointer 194": { "status": "PASS" }, "Not throw: windows-874 has a pointer 195": { "status": "PASS" }, "Not throw: windows-874 has a pointer 196": { "status": "PASS" }, "Not throw: windows-874 has a pointer 197": { "status": "PASS" }, "Not throw: windows-874 has a pointer 198": { "status": "PASS" }, "Not throw: windows-874 has a pointer 199": { "status": "PASS" }, "Not throw: windows-874 has a pointer 200": { "status": "PASS" }, "Not throw: windows-874 has a pointer 201": { "status": "PASS" }, "Not throw: windows-874 has a pointer 202": { "status": "PASS" }, "Not throw: windows-874 has a pointer 203": { "status": "PASS" }, "Not throw: windows-874 has a pointer 204": { "status": "PASS" }, "Not throw: windows-874 has a pointer 205": { "status": "PASS" }, "Not throw: windows-874 has a pointer 206": { "status": "PASS" }, "Not throw: windows-874 has a pointer 207": { "status": "PASS" }, "Not throw: windows-874 has a pointer 208": { "status": "PASS" }, "Not throw: windows-874 has a pointer 209": { "status": "PASS" }, "Not throw: windows-874 has a pointer 210": { "status": "PASS" }, "Not throw: windows-874 has a pointer 211": { "status": "PASS" }, "Not throw: windows-874 has a pointer 212": { "status": "PASS" }, "Not throw: windows-874 has a pointer 213": { "status": "PASS" }, "Not throw: windows-874 has a pointer 214": { "status": "PASS" }, "Not throw: windows-874 has a pointer 215": { "status": "PASS" }, "Not throw: windows-874 has a pointer 216": { "status": "PASS" }, "Not throw: windows-874 has a pointer 217": { "status": "PASS" }, "Not throw: windows-874 has a pointer 218": { "status": "PASS" }, "Throw due to fatal flag: windows-874 doesn't have a pointer 219": { "status": "PASS" }, "Throw due to fatal flag: windows-874 doesn't have a pointer 220": { "status": "PASS" }, "Throw due to fatal flag: windows-874 doesn't have a pointer 221": { "status": "PASS" }, "Throw due to fatal flag: windows-874 doesn't have a pointer 222": { "status": "PASS" }, "Not throw: windows-874 has a pointer 223": { "status": "PASS" }, "Not throw: windows-874 has a pointer 224": { "status": "PASS" }, "Not throw: windows-874 has a pointer 225": { "status": "PASS" }, "Not throw: windows-874 has a pointer 226": { "status": "PASS" }, "Not throw: windows-874 has a pointer 227": { "status": "PASS" }, "Not throw: windows-874 has a pointer 228": { "status": "PASS" }, "Not throw: windows-874 has a pointer 229": { "status": "PASS" }, "Not throw: windows-874 has a pointer 230": { "status": "PASS" }, "Not throw: windows-874 has a pointer 231": { "status": "PASS" }, "Not throw: windows-874 has a pointer 232": { "status": "PASS" }, "Not throw: windows-874 has a pointer 233": { "status": "PASS" }, "Not throw: windows-874 has a pointer 234": { "status": "PASS" }, "Not throw: windows-874 has a pointer 235": { "status": "PASS" }, "Not throw: windows-874 has a pointer 236": { "status": "PASS" }, "Not throw: windows-874 has a pointer 237": { "status": "PASS" }, "Not throw: windows-874 has a pointer 238": { "status": "PASS" }, "Not throw: windows-874 has a pointer 239": { "status": "PASS" }, "Not throw: windows-874 has a pointer 240": { "status": "PASS" }, "Not throw: windows-874 has a pointer 241": { "status": "PASS" }, "Not throw: windows-874 has a pointer 242": { "status": "PASS" }, "Not throw: windows-874 has a pointer 243": { "status": "PASS" }, "Not throw: windows-874 has a pointer 244": { "status": "PASS" }, "Not throw: windows-874 has a pointer 245": { "status": "PASS" }, "Not throw: windows-874 has a pointer 246": { "status": "PASS" }, "Not throw: windows-874 has a pointer 247": { "status": "PASS" }, "Not throw: windows-874 has a pointer 248": { "status": "PASS" }, "Not throw: windows-874 has a pointer 249": { "status": "PASS" }, "Not throw: windows-874 has a pointer 250": { "status": "PASS" }, "Not throw: windows-874 has a pointer 251": { "status": "PASS" }, "Throw due to fatal flag: windows-874 doesn't have a pointer 252": { "status": "PASS" }, "Throw due to fatal flag: windows-874 doesn't have a pointer 253": { "status": "PASS" }, "Throw due to fatal flag: windows-874 doesn't have a pointer 254": { "status": "PASS" }, "Throw due to fatal flag: windows-874 doesn't have a pointer 255": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 0": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 1": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 2": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 3": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 4": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 5": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 6": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 7": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 8": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 9": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 10": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 11": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 12": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 13": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 14": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 15": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 16": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 17": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 18": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 19": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 20": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 21": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 22": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 23": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 24": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 25": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 26": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 27": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 28": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 29": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 30": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 31": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 32": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 33": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 34": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 35": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 36": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 37": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 38": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 39": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 40": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 41": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 42": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 43": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 44": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 45": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 46": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 47": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 48": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 49": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 50": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 51": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 52": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 53": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 54": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 55": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 56": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 57": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 58": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 59": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 60": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 61": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 62": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 63": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 64": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 65": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 66": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 67": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 68": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 69": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 70": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 71": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 72": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 73": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 74": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 75": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 76": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 77": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 78": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 79": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 80": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 81": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 82": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 83": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 84": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 85": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 86": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 87": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 88": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 89": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 90": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 91": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 92": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 93": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 94": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 95": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 96": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 97": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 98": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 99": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 100": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 101": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 102": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 103": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 104": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 105": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 106": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 107": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 108": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 109": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 110": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 111": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 112": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 113": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 114": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 115": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 116": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 117": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 118": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 119": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 120": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 121": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 122": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 123": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 124": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 125": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 126": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 127": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 128": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 129": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 130": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 131": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 132": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 133": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 134": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 135": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 136": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 137": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 138": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 139": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 140": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 141": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 142": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 143": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 144": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 145": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 146": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 147": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 148": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 149": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 150": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 151": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 152": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 153": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 154": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 155": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 156": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 157": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 158": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 159": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 160": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 161": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 162": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 163": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 164": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 165": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 166": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 167": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 168": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 169": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 170": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 171": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 172": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 173": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 174": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 175": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 176": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 177": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 178": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 179": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 180": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 181": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 182": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 183": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 184": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 185": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 186": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 187": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 188": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 189": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 190": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 191": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 192": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 193": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 194": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 195": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 196": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 197": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 198": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 199": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 200": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 201": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 202": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 203": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 204": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 205": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 206": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 207": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 208": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 209": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 210": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 211": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 212": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 213": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 214": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 215": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 216": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 217": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 218": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 219": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 220": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 221": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 222": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 223": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 224": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 225": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 226": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 227": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 228": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 229": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 230": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 231": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 232": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 233": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 234": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 235": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 236": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 237": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 238": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 239": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 240": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 241": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 242": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 243": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 244": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 245": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 246": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 247": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 248": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 249": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 250": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 251": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 252": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 253": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 254": { "status": "PASS" }, "Not throw: windows-1250 has a pointer 255": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 0": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 1": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 2": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 3": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 4": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 5": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 6": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 7": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 8": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 9": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 10": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 11": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 12": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 13": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 14": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 15": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 16": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 17": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 18": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 19": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 20": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 21": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 22": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 23": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 24": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 25": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 26": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 27": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 28": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 29": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 30": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 31": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 32": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 33": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 34": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 35": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 36": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 37": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 38": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 39": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 40": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 41": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 42": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 43": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 44": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 45": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 46": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 47": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 48": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 49": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 50": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 51": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 52": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 53": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 54": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 55": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 56": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 57": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 58": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 59": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 60": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 61": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 62": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 63": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 64": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 65": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 66": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 67": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 68": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 69": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 70": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 71": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 72": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 73": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 74": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 75": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 76": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 77": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 78": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 79": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 80": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 81": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 82": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 83": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 84": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 85": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 86": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 87": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 88": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 89": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 90": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 91": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 92": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 93": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 94": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 95": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 96": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 97": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 98": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 99": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 100": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 101": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 102": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 103": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 104": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 105": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 106": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 107": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 108": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 109": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 110": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 111": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 112": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 113": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 114": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 115": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 116": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 117": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 118": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 119": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 120": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 121": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 122": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 123": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 124": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 125": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 126": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 127": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 128": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 129": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 130": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 131": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 132": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 133": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 134": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 135": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 136": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 137": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 138": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 139": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 140": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 141": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 142": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 143": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 144": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 145": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 146": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 147": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 148": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 149": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 150": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 151": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 152": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 153": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 154": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 155": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 156": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 157": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 158": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 159": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 160": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 161": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 162": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 163": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 164": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 165": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 166": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 167": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 168": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 169": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 170": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 171": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 172": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 173": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 174": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 175": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 176": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 177": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 178": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 179": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 180": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 181": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 182": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 183": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 184": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 185": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 186": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 187": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 188": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 189": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 190": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 191": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 192": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 193": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 194": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 195": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 196": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 197": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 198": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 199": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 200": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 201": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 202": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 203": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 204": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 205": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 206": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 207": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 208": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 209": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 210": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 211": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 212": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 213": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 214": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 215": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 216": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 217": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 218": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 219": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 220": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 221": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 222": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 223": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 224": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 225": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 226": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 227": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 228": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 229": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 230": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 231": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 232": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 233": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 234": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 235": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 236": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 237": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 238": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 239": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 240": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 241": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 242": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 243": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 244": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 245": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 246": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 247": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 248": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 249": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 250": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 251": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 252": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 253": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 254": { "status": "PASS" }, "Not throw: windows-1251 has a pointer 255": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 0": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 1": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 2": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 3": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 4": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 5": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 6": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 7": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 8": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 9": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 10": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 11": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 12": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 13": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 14": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 15": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 16": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 17": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 18": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 19": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 20": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 21": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 22": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 23": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 24": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 25": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 26": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 27": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 28": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 29": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 30": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 31": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 32": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 33": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 34": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 35": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 36": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 37": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 38": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 39": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 40": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 41": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 42": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 43": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 44": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 45": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 46": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 47": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 48": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 49": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 50": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 51": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 52": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 53": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 54": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 55": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 56": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 57": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 58": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 59": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 60": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 61": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 62": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 63": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 64": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 65": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 66": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 67": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 68": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 69": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 70": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 71": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 72": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 73": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 74": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 75": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 76": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 77": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 78": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 79": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 80": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 81": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 82": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 83": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 84": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 85": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 86": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 87": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 88": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 89": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 90": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 91": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 92": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 93": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 94": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 95": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 96": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 97": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 98": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 99": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 100": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 101": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 102": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 103": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 104": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 105": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 106": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 107": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 108": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 109": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 110": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 111": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 112": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 113": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 114": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 115": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 116": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 117": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 118": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 119": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 120": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 121": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 122": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 123": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 124": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 125": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 126": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 127": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 128": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 129": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 130": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 131": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 132": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 133": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 134": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 135": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 136": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 137": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 138": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 139": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 140": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 141": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 142": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 143": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 144": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 145": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 146": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 147": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 148": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 149": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 150": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 151": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 152": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 153": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 154": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 155": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 156": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 157": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 158": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 159": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 160": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 161": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 162": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 163": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 164": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 165": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 166": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 167": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 168": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 169": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 170": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 171": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 172": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 173": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 174": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 175": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 176": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 177": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 178": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 179": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 180": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 181": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 182": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 183": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 184": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 185": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 186": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 187": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 188": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 189": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 190": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 191": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 192": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 193": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 194": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 195": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 196": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 197": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 198": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 199": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 200": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 201": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 202": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 203": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 204": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 205": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 206": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 207": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 208": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 209": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 210": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 211": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 212": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 213": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 214": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 215": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 216": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 217": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 218": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 219": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 220": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 221": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 222": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 223": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 224": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 225": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 226": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 227": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 228": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 229": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 230": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 231": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 232": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 233": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 234": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 235": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 236": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 237": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 238": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 239": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 240": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 241": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 242": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 243": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 244": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 245": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 246": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 247": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 248": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 249": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 250": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 251": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 252": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 253": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 254": { "status": "PASS" }, "Not throw: windows-1252 has a pointer 255": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 0": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 1": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 2": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 3": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 4": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 5": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 6": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 7": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 8": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 9": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 10": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 11": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 12": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 13": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 14": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 15": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 16": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 17": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 18": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 19": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 20": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 21": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 22": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 23": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 24": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 25": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 26": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 27": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 28": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 29": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 30": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 31": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 32": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 33": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 34": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 35": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 36": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 37": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 38": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 39": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 40": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 41": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 42": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 43": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 44": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 45": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 46": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 47": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 48": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 49": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 50": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 51": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 52": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 53": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 54": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 55": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 56": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 57": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 58": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 59": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 60": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 61": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 62": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 63": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 64": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 65": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 66": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 67": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 68": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 69": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 70": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 71": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 72": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 73": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 74": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 75": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 76": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 77": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 78": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 79": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 80": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 81": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 82": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 83": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 84": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 85": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 86": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 87": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 88": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 89": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 90": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 91": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 92": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 93": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 94": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 95": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 96": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 97": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 98": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 99": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 100": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 101": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 102": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 103": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 104": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 105": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 106": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 107": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 108": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 109": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 110": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 111": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 112": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 113": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 114": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 115": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 116": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 117": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 118": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 119": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 120": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 121": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 122": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 123": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 124": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 125": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 126": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 127": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 128": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 129": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 130": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 131": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 132": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 133": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 134": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 135": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 136": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 137": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 138": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 139": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 140": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 141": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 142": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 143": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 144": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 145": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 146": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 147": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 148": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 149": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 150": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 151": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 152": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 153": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 154": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 155": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 156": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 157": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 158": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 159": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 160": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 161": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 162": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 163": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 164": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 165": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 166": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 167": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 168": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 169": { "status": "PASS" }, "Throw due to fatal flag: windows-1253 doesn't have a pointer 170": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 171": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 172": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 173": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 174": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 175": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 176": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 177": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 178": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 179": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 180": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 181": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 182": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 183": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 184": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 185": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 186": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 187": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 188": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 189": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 190": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 191": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 192": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 193": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 194": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 195": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 196": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 197": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 198": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 199": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 200": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 201": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 202": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 203": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 204": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 205": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 206": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 207": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 208": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 209": { "status": "PASS" }, "Throw due to fatal flag: windows-1253 doesn't have a pointer 210": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 211": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 212": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 213": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 214": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 215": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 216": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 217": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 218": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 219": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 220": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 221": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 222": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 223": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 224": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 225": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 226": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 227": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 228": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 229": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 230": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 231": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 232": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 233": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 234": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 235": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 236": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 237": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 238": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 239": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 240": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 241": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 242": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 243": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 244": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 245": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 246": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 247": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 248": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 249": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 250": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 251": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 252": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 253": { "status": "PASS" }, "Not throw: windows-1253 has a pointer 254": { "status": "PASS" }, "Throw due to fatal flag: windows-1253 doesn't have a pointer 255": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 0": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 1": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 2": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 3": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 4": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 5": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 6": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 7": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 8": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 9": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 10": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 11": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 12": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 13": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 14": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 15": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 16": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 17": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 18": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 19": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 20": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 21": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 22": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 23": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 24": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 25": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 26": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 27": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 28": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 29": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 30": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 31": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 32": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 33": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 34": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 35": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 36": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 37": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 38": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 39": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 40": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 41": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 42": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 43": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 44": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 45": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 46": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 47": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 48": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 49": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 50": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 51": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 52": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 53": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 54": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 55": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 56": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 57": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 58": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 59": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 60": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 61": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 62": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 63": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 64": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 65": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 66": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 67": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 68": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 69": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 70": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 71": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 72": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 73": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 74": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 75": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 76": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 77": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 78": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 79": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 80": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 81": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 82": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 83": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 84": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 85": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 86": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 87": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 88": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 89": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 90": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 91": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 92": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 93": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 94": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 95": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 96": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 97": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 98": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 99": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 100": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 101": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 102": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 103": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 104": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 105": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 106": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 107": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 108": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 109": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 110": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 111": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 112": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 113": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 114": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 115": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 116": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 117": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 118": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 119": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 120": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 121": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 122": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 123": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 124": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 125": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 126": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 127": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 128": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 129": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 130": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 131": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 132": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 133": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 134": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 135": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 136": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 137": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 138": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 139": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 140": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 141": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 142": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 143": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 144": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 145": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 146": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 147": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 148": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 149": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 150": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 151": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 152": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 153": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 154": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 155": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 156": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 157": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 158": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 159": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 160": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 161": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 162": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 163": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 164": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 165": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 166": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 167": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 168": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 169": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 170": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 171": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 172": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 173": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 174": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 175": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 176": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 177": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 178": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 179": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 180": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 181": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 182": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 183": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 184": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 185": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 186": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 187": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 188": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 189": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 190": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 191": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 192": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 193": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 194": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 195": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 196": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 197": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 198": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 199": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 200": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 201": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 202": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 203": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 204": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 205": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 206": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 207": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 208": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 209": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 210": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 211": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 212": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 213": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 214": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 215": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 216": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 217": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 218": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 219": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 220": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 221": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 222": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 223": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 224": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 225": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 226": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 227": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 228": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 229": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 230": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 231": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 232": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 233": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 234": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 235": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 236": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 237": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 238": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 239": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 240": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 241": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 242": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 243": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 244": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 245": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 246": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 247": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 248": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 249": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 250": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 251": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 252": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 253": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 254": { "status": "PASS" }, "Not throw: windows-1254 has a pointer 255": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 0": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 1": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 2": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 3": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 4": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 5": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 6": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 7": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 8": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 9": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 10": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 11": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 12": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 13": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 14": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 15": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 16": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 17": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 18": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 19": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 20": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 21": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 22": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 23": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 24": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 25": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 26": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 27": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 28": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 29": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 30": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 31": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 32": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 33": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 34": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 35": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 36": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 37": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 38": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 39": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 40": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 41": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 42": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 43": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 44": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 45": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 46": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 47": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 48": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 49": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 50": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 51": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 52": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 53": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 54": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 55": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 56": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 57": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 58": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 59": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 60": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 61": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 62": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 63": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 64": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 65": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 66": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 67": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 68": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 69": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 70": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 71": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 72": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 73": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 74": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 75": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 76": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 77": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 78": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 79": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 80": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 81": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 82": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 83": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 84": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 85": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 86": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 87": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 88": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 89": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 90": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 91": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 92": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 93": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 94": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 95": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 96": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 97": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 98": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 99": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 100": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 101": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 102": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 103": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 104": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 105": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 106": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 107": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 108": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 109": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 110": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 111": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 112": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 113": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 114": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 115": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 116": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 117": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 118": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 119": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 120": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 121": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 122": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 123": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 124": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 125": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 126": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 127": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 128": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 129": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 130": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 131": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 132": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 133": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 134": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 135": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 136": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 137": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 138": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 139": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 140": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 141": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 142": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 143": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 144": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 145": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 146": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 147": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 148": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 149": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 150": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 151": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 152": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 153": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 154": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 155": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 156": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 157": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 158": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 159": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 160": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 161": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 162": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 163": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 164": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 165": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 166": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 167": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 168": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 169": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 170": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 171": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 172": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 173": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 174": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 175": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 176": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 177": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 178": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 179": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 180": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 181": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 182": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 183": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 184": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 185": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 186": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 187": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 188": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 189": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 190": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 191": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 192": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 193": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 194": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 195": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 196": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 197": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 198": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 199": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 200": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 201": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 202": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 203": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 204": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 205": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 206": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 207": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 208": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 209": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 210": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 211": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 212": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 213": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 214": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 215": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 216": { "status": "PASS" }, "Throw due to fatal flag: windows-1255 doesn't have a pointer 217": { "status": "PASS" }, "Throw due to fatal flag: windows-1255 doesn't have a pointer 218": { "status": "PASS" }, "Throw due to fatal flag: windows-1255 doesn't have a pointer 219": { "status": "PASS" }, "Throw due to fatal flag: windows-1255 doesn't have a pointer 220": { "status": "PASS" }, "Throw due to fatal flag: windows-1255 doesn't have a pointer 221": { "status": "PASS" }, "Throw due to fatal flag: windows-1255 doesn't have a pointer 222": { "status": "PASS" }, "Throw due to fatal flag: windows-1255 doesn't have a pointer 223": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 224": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 225": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 226": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 227": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 228": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 229": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 230": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 231": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 232": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 233": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 234": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 235": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 236": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 237": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 238": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 239": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 240": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 241": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 242": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 243": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 244": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 245": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 246": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 247": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 248": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 249": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 250": { "status": "PASS" }, "Throw due to fatal flag: windows-1255 doesn't have a pointer 251": { "status": "PASS" }, "Throw due to fatal flag: windows-1255 doesn't have a pointer 252": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 253": { "status": "PASS" }, "Not throw: windows-1255 has a pointer 254": { "status": "PASS" }, "Throw due to fatal flag: windows-1255 doesn't have a pointer 255": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 0": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 1": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 2": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 3": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 4": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 5": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 6": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 7": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 8": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 9": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 10": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 11": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 12": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 13": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 14": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 15": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 16": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 17": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 18": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 19": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 20": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 21": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 22": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 23": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 24": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 25": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 26": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 27": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 28": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 29": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 30": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 31": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 32": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 33": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 34": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 35": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 36": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 37": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 38": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 39": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 40": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 41": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 42": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 43": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 44": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 45": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 46": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 47": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 48": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 49": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 50": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 51": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 52": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 53": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 54": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 55": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 56": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 57": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 58": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 59": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 60": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 61": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 62": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 63": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 64": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 65": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 66": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 67": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 68": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 69": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 70": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 71": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 72": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 73": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 74": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 75": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 76": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 77": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 78": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 79": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 80": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 81": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 82": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 83": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 84": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 85": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 86": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 87": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 88": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 89": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 90": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 91": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 92": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 93": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 94": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 95": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 96": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 97": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 98": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 99": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 100": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 101": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 102": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 103": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 104": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 105": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 106": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 107": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 108": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 109": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 110": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 111": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 112": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 113": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 114": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 115": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 116": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 117": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 118": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 119": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 120": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 121": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 122": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 123": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 124": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 125": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 126": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 127": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 128": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 129": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 130": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 131": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 132": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 133": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 134": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 135": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 136": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 137": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 138": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 139": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 140": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 141": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 142": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 143": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 144": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 145": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 146": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 147": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 148": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 149": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 150": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 151": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 152": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 153": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 154": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 155": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 156": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 157": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 158": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 159": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 160": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 161": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 162": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 163": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 164": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 165": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 166": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 167": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 168": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 169": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 170": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 171": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 172": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 173": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 174": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 175": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 176": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 177": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 178": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 179": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 180": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 181": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 182": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 183": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 184": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 185": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 186": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 187": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 188": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 189": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 190": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 191": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 192": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 193": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 194": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 195": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 196": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 197": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 198": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 199": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 200": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 201": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 202": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 203": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 204": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 205": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 206": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 207": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 208": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 209": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 210": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 211": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 212": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 213": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 214": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 215": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 216": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 217": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 218": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 219": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 220": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 221": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 222": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 223": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 224": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 225": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 226": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 227": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 228": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 229": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 230": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 231": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 232": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 233": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 234": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 235": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 236": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 237": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 238": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 239": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 240": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 241": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 242": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 243": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 244": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 245": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 246": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 247": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 248": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 249": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 250": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 251": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 252": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 253": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 254": { "status": "PASS" }, "Not throw: windows-1256 has a pointer 255": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 0": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 1": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 2": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 3": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 4": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 5": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 6": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 7": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 8": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 9": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 10": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 11": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 12": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 13": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 14": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 15": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 16": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 17": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 18": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 19": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 20": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 21": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 22": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 23": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 24": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 25": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 26": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 27": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 28": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 29": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 30": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 31": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 32": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 33": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 34": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 35": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 36": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 37": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 38": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 39": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 40": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 41": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 42": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 43": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 44": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 45": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 46": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 47": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 48": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 49": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 50": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 51": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 52": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 53": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 54": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 55": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 56": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 57": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 58": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 59": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 60": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 61": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 62": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 63": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 64": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 65": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 66": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 67": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 68": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 69": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 70": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 71": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 72": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 73": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 74": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 75": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 76": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 77": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 78": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 79": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 80": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 81": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 82": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 83": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 84": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 85": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 86": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 87": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 88": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 89": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 90": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 91": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 92": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 93": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 94": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 95": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 96": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 97": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 98": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 99": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 100": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 101": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 102": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 103": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 104": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 105": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 106": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 107": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 108": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 109": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 110": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 111": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 112": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 113": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 114": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 115": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 116": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 117": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 118": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 119": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 120": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 121": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 122": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 123": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 124": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 125": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 126": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 127": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 128": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 129": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 130": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 131": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 132": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 133": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 134": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 135": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 136": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 137": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 138": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 139": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 140": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 141": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 142": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 143": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 144": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 145": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 146": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 147": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 148": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 149": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 150": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 151": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 152": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 153": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 154": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 155": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 156": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 157": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 158": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 159": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 160": { "status": "PASS" }, "Throw due to fatal flag: windows-1257 doesn't have a pointer 161": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 162": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 163": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 164": { "status": "PASS" }, "Throw due to fatal flag: windows-1257 doesn't have a pointer 165": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 166": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 167": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 168": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 169": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 170": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 171": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 172": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 173": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 174": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 175": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 176": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 177": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 178": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 179": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 180": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 181": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 182": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 183": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 184": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 185": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 186": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 187": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 188": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 189": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 190": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 191": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 192": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 193": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 194": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 195": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 196": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 197": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 198": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 199": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 200": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 201": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 202": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 203": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 204": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 205": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 206": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 207": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 208": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 209": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 210": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 211": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 212": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 213": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 214": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 215": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 216": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 217": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 218": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 219": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 220": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 221": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 222": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 223": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 224": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 225": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 226": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 227": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 228": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 229": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 230": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 231": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 232": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 233": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 234": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 235": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 236": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 237": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 238": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 239": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 240": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 241": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 242": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 243": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 244": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 245": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 246": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 247": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 248": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 249": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 250": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 251": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 252": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 253": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 254": { "status": "PASS" }, "Not throw: windows-1257 has a pointer 255": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 0": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 1": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 2": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 3": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 4": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 5": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 6": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 7": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 8": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 9": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 10": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 11": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 12": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 13": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 14": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 15": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 16": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 17": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 18": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 19": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 20": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 21": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 22": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 23": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 24": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 25": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 26": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 27": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 28": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 29": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 30": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 31": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 32": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 33": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 34": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 35": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 36": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 37": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 38": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 39": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 40": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 41": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 42": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 43": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 44": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 45": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 46": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 47": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 48": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 49": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 50": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 51": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 52": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 53": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 54": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 55": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 56": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 57": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 58": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 59": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 60": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 61": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 62": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 63": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 64": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 65": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 66": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 67": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 68": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 69": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 70": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 71": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 72": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 73": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 74": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 75": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 76": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 77": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 78": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 79": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 80": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 81": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 82": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 83": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 84": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 85": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 86": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 87": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 88": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 89": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 90": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 91": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 92": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 93": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 94": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 95": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 96": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 97": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 98": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 99": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 100": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 101": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 102": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 103": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 104": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 105": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 106": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 107": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 108": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 109": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 110": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 111": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 112": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 113": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 114": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 115": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 116": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 117": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 118": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 119": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 120": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 121": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 122": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 123": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 124": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 125": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 126": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 127": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 128": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 129": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 130": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 131": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 132": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 133": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 134": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 135": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 136": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 137": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 138": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 139": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 140": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 141": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 142": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 143": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 144": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 145": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 146": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 147": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 148": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 149": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 150": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 151": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 152": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 153": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 154": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 155": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 156": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 157": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 158": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 159": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 160": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 161": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 162": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 163": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 164": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 165": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 166": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 167": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 168": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 169": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 170": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 171": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 172": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 173": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 174": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 175": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 176": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 177": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 178": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 179": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 180": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 181": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 182": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 183": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 184": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 185": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 186": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 187": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 188": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 189": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 190": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 191": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 192": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 193": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 194": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 195": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 196": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 197": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 198": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 199": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 200": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 201": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 202": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 203": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 204": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 205": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 206": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 207": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 208": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 209": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 210": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 211": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 212": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 213": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 214": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 215": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 216": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 217": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 218": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 219": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 220": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 221": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 222": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 223": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 224": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 225": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 226": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 227": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 228": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 229": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 230": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 231": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 232": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 233": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 234": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 235": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 236": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 237": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 238": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 239": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 240": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 241": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 242": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 243": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 244": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 245": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 246": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 247": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 248": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 249": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 250": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 251": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 252": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 253": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 254": { "status": "PASS" }, "Not throw: windows-1258 has a pointer 255": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 0": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 1": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 2": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 3": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 4": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 5": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 6": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 7": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 8": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 9": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 10": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 11": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 12": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 13": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 14": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 15": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 16": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 17": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 18": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 19": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 20": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 21": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 22": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 23": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 24": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 25": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 26": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 27": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 28": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 29": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 30": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 31": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 32": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 33": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 34": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 35": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 36": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 37": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 38": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 39": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 40": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 41": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 42": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 43": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 44": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 45": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 46": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 47": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 48": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 49": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 50": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 51": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 52": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 53": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 54": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 55": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 56": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 57": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 58": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 59": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 60": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 61": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 62": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 63": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 64": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 65": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 66": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 67": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 68": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 69": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 70": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 71": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 72": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 73": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 74": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 75": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 76": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 77": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 78": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 79": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 80": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 81": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 82": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 83": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 84": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 85": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 86": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 87": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 88": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 89": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 90": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 91": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 92": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 93": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 94": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 95": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 96": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 97": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 98": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 99": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 100": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 101": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 102": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 103": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 104": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 105": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 106": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 107": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 108": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 109": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 110": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 111": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 112": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 113": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 114": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 115": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 116": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 117": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 118": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 119": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 120": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 121": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 122": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 123": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 124": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 125": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 126": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 127": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 128": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 129": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 130": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 131": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 132": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 133": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 134": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 135": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 136": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 137": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 138": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 139": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 140": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 141": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 142": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 143": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 144": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 145": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 146": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 147": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 148": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 149": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 150": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 151": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 152": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 153": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 154": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 155": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 156": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 157": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 158": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 159": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 160": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 161": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 162": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 163": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 164": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 165": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 166": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 167": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 168": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 169": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 170": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 171": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 172": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 173": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 174": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 175": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 176": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 177": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 178": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 179": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 180": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 181": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 182": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 183": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 184": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 185": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 186": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 187": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 188": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 189": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 190": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 191": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 192": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 193": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 194": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 195": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 196": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 197": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 198": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 199": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 200": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 201": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 202": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 203": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 204": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 205": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 206": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 207": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 208": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 209": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 210": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 211": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 212": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 213": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 214": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 215": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 216": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 217": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 218": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 219": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 220": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 221": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 222": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 223": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 224": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 225": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 226": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 227": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 228": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 229": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 230": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 231": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 232": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 233": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 234": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 235": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 236": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 237": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 238": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 239": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 240": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 241": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 242": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 243": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 244": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 245": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 246": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 247": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 248": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 249": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 250": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 251": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 252": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 253": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 254": { "status": "PASS" }, "Not throw: x-mac-cyrillic has a pointer 255": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-fatal-streaming.any.js.json ================================================ { "Fatal flag, non-streaming cases": { "status": "PASS" }, "Fatal flag, streaming cases": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-fatal.any.js.json ================================================ { "Fatal flag: utf-8 - invalid code": { "status": "PASS" }, "Fatal flag: utf-8 - ends early": { "status": "PASS" }, "Fatal flag: utf-8 - ends early 2": { "status": "PASS" }, "Fatal flag: utf-8 - invalid trail": { "status": "PASS" }, "Fatal flag: utf-8 - invalid trail 2": { "status": "PASS" }, "Fatal flag: utf-8 - invalid trail 3": { "status": "PASS" }, "Fatal flag: utf-8 - invalid trail 4": { "status": "PASS" }, "Fatal flag: utf-8 - invalid trail 5": { "status": "PASS" }, "Fatal flag: utf-8 - invalid trail 6": { "status": "PASS" }, "Fatal flag: utf-8 - > 0x10FFFF": { "status": "PASS" }, "Fatal flag: utf-8 - obsolete lead byte": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+0000 - 2 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+0000 - 3 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+0000 - 4 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+0000 - 5 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+0000 - 6 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+007F - 2 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+007F - 3 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+007F - 4 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+007F - 5 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+007F - 6 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+07FF - 3 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+07FF - 4 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+07FF - 5 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+07FF - 6 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+FFFF - 4 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+FFFF - 5 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+FFFF - 6 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+10FFFF - 5 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - overlong U+10FFFF - 6 bytes": { "status": "PASS" }, "Fatal flag: utf-8 - lead surrogate": { "status": "PASS" }, "Fatal flag: utf-8 - trail surrogate": { "status": "PASS" }, "Fatal flag: utf-8 - surrogate pair": { "status": "PASS" }, "Fatal flag: utf-16le - truncated code unit": { "status": "PASS" }, "The fatal attribute of TextDecoder": { "status": "PASS" }, "Error seen with fatal does not prevent future decodes": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-ignorebom.any.js.json ================================================ { "BOM is ignored if ignoreBOM option is specified: utf-8": { "status": "PASS" }, "BOM is ignored if ignoreBOM option is specified: utf-16le": { "status": "PASS" }, "BOM is ignored if ignoreBOM option is specified: utf-16be": { "status": "PASS" }, "The ignoreBOM attribute of TextDecoder": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-labels.any.js.json ================================================ { "unicode-1-1-utf-8 => UTF-8": { "status": "PASS" }, "unicode11utf8 => UTF-8": { "status": "PASS" }, "unicode20utf8 => UTF-8": { "status": "PASS" }, "utf-8 => UTF-8": { "status": "PASS" }, "utf8 => UTF-8": { "status": "PASS" }, "x-unicode20utf8 => UTF-8": { "status": "PASS" }, "866 => IBM866": { "status": "PASS" }, "cp866 => IBM866": { "status": "PASS" }, "csibm866 => IBM866": { "status": "PASS" }, "ibm866 => IBM866": { "status": "PASS" }, "csisolatin2 => ISO-8859-2": { "status": "PASS" }, "iso-8859-2 => ISO-8859-2": { "status": "PASS" }, "iso-ir-101 => ISO-8859-2": { "status": "PASS" }, "iso8859-2 => ISO-8859-2": { "status": "PASS" }, "iso88592 => ISO-8859-2": { "status": "PASS" }, "iso_8859-2 => ISO-8859-2": { "status": "PASS" }, "iso_8859-2:1987 => ISO-8859-2": { "status": "PASS" }, "l2 => ISO-8859-2": { "status": "PASS" }, "latin2 => ISO-8859-2": { "status": "PASS" }, "csisolatin3 => ISO-8859-3": { "status": "PASS" }, "iso-8859-3 => ISO-8859-3": { "status": "PASS" }, "iso-ir-109 => ISO-8859-3": { "status": "PASS" }, "iso8859-3 => ISO-8859-3": { "status": "PASS" }, "iso88593 => ISO-8859-3": { "status": "PASS" }, "iso_8859-3 => ISO-8859-3": { "status": "PASS" }, "iso_8859-3:1988 => ISO-8859-3": { "status": "PASS" }, "l3 => ISO-8859-3": { "status": "PASS" }, "latin3 => ISO-8859-3": { "status": "PASS" }, "csisolatin4 => ISO-8859-4": { "status": "PASS" }, "iso-8859-4 => ISO-8859-4": { "status": "PASS" }, "iso-ir-110 => ISO-8859-4": { "status": "PASS" }, "iso8859-4 => ISO-8859-4": { "status": "PASS" }, "iso88594 => ISO-8859-4": { "status": "PASS" }, "iso_8859-4 => ISO-8859-4": { "status": "PASS" }, "iso_8859-4:1988 => ISO-8859-4": { "status": "PASS" }, "l4 => ISO-8859-4": { "status": "PASS" }, "latin4 => ISO-8859-4": { "status": "PASS" }, "csisolatincyrillic => ISO-8859-5": { "status": "PASS" }, "cyrillic => ISO-8859-5": { "status": "PASS" }, "iso-8859-5 => ISO-8859-5": { "status": "PASS" }, "iso-ir-144 => ISO-8859-5": { "status": "PASS" }, "iso8859-5 => ISO-8859-5": { "status": "PASS" }, "iso88595 => ISO-8859-5": { "status": "PASS" }, "iso_8859-5 => ISO-8859-5": { "status": "PASS" }, "iso_8859-5:1988 => ISO-8859-5": { "status": "PASS" }, "arabic => ISO-8859-6": { "status": "PASS" }, "asmo-708 => ISO-8859-6": { "status": "PASS" }, "csiso88596e => ISO-8859-6": { "status": "PASS" }, "csiso88596i => ISO-8859-6": { "status": "PASS" }, "csisolatinarabic => ISO-8859-6": { "status": "PASS" }, "ecma-114 => ISO-8859-6": { "status": "PASS" }, "iso-8859-6 => ISO-8859-6": { "status": "PASS" }, "iso-8859-6-e => ISO-8859-6": { "status": "PASS" }, "iso-8859-6-i => ISO-8859-6": { "status": "PASS" }, "iso-ir-127 => ISO-8859-6": { "status": "PASS" }, "iso8859-6 => ISO-8859-6": { "status": "PASS" }, "iso88596 => ISO-8859-6": { "status": "PASS" }, "iso_8859-6 => ISO-8859-6": { "status": "PASS" }, "iso_8859-6:1987 => ISO-8859-6": { "status": "PASS" }, "csisolatingreek => ISO-8859-7": { "status": "PASS" }, "ecma-118 => ISO-8859-7": { "status": "PASS" }, "elot_928 => ISO-8859-7": { "status": "PASS" }, "greek => ISO-8859-7": { "status": "PASS" }, "greek8 => ISO-8859-7": { "status": "PASS" }, "iso-8859-7 => ISO-8859-7": { "status": "PASS" }, "iso-ir-126 => ISO-8859-7": { "status": "PASS" }, "iso8859-7 => ISO-8859-7": { "status": "PASS" }, "iso88597 => ISO-8859-7": { "status": "PASS" }, "iso_8859-7 => ISO-8859-7": { "status": "PASS" }, "iso_8859-7:1987 => ISO-8859-7": { "status": "PASS" }, "sun_eu_greek => ISO-8859-7": { "status": "PASS" }, "csiso88598e => ISO-8859-8": { "status": "PASS" }, "csisolatinhebrew => ISO-8859-8": { "status": "PASS" }, "hebrew => ISO-8859-8": { "status": "PASS" }, "iso-8859-8 => ISO-8859-8": { "status": "PASS" }, "iso-8859-8-e => ISO-8859-8": { "status": "PASS" }, "iso-ir-138 => ISO-8859-8": { "status": "PASS" }, "iso8859-8 => ISO-8859-8": { "status": "PASS" }, "iso88598 => ISO-8859-8": { "status": "PASS" }, "iso_8859-8 => ISO-8859-8": { "status": "PASS" }, "iso_8859-8:1988 => ISO-8859-8": { "status": "PASS" }, "visual => ISO-8859-8": { "status": "PASS" }, "csiso88598i => ISO-8859-8-I": { "status": "PASS" }, "iso-8859-8-i => ISO-8859-8-I": { "status": "PASS" }, "logical => ISO-8859-8-I": { "status": "PASS" }, "csisolatin6 => ISO-8859-10": { "status": "PASS" }, "iso-8859-10 => ISO-8859-10": { "status": "PASS" }, "iso-ir-157 => ISO-8859-10": { "status": "PASS" }, "iso8859-10 => ISO-8859-10": { "status": "PASS" }, "iso885910 => ISO-8859-10": { "status": "PASS" }, "l6 => ISO-8859-10": { "status": "PASS" }, "latin6 => ISO-8859-10": { "status": "PASS" }, "iso-8859-13 => ISO-8859-13": { "status": "PASS" }, "iso8859-13 => ISO-8859-13": { "status": "PASS" }, "iso885913 => ISO-8859-13": { "status": "PASS" }, "iso-8859-14 => ISO-8859-14": { "status": "PASS" }, "iso8859-14 => ISO-8859-14": { "status": "PASS" }, "iso885914 => ISO-8859-14": { "status": "PASS" }, "csisolatin9 => ISO-8859-15": { "status": "PASS" }, "iso-8859-15 => ISO-8859-15": { "status": "PASS" }, "iso8859-15 => ISO-8859-15": { "status": "PASS" }, "iso885915 => ISO-8859-15": { "status": "PASS" }, "iso_8859-15 => ISO-8859-15": { "status": "PASS" }, "l9 => ISO-8859-15": { "status": "PASS" }, "iso-8859-16 => ISO-8859-16": { "status": "PASS" }, "cskoi8r => KOI8-R": { "status": "PASS" }, "koi => KOI8-R": { "status": "PASS" }, "koi8 => KOI8-R": { "status": "PASS" }, "koi8-r => KOI8-R": { "status": "PASS" }, "koi8_r => KOI8-R": { "status": "PASS" }, "koi8-ru => KOI8-U": { "status": "PASS" }, "koi8-u => KOI8-U": { "status": "PASS" }, "csmacintosh => macintosh": { "status": "PASS" }, "mac => macintosh": { "status": "PASS" }, "macintosh => macintosh": { "status": "PASS" }, "x-mac-roman => macintosh": { "status": "PASS" }, "dos-874 => windows-874": { "status": "PASS" }, "iso-8859-11 => windows-874": { "status": "PASS" }, "iso8859-11 => windows-874": { "status": "PASS" }, "iso885911 => windows-874": { "status": "PASS" }, "tis-620 => windows-874": { "status": "PASS" }, "windows-874 => windows-874": { "status": "PASS" }, "cp1250 => windows-1250": { "status": "PASS" }, "windows-1250 => windows-1250": { "status": "PASS" }, "x-cp1250 => windows-1250": { "status": "PASS" }, "cp1251 => windows-1251": { "status": "PASS" }, "windows-1251 => windows-1251": { "status": "PASS" }, "x-cp1251 => windows-1251": { "status": "PASS" }, "ansi_x3.4-1968 => windows-1252": { "status": "PASS" }, "ascii => windows-1252": { "status": "PASS" }, "cp1252 => windows-1252": { "status": "PASS" }, "cp819 => windows-1252": { "status": "PASS" }, "csisolatin1 => windows-1252": { "status": "PASS" }, "ibm819 => windows-1252": { "status": "PASS" }, "iso-8859-1 => windows-1252": { "status": "PASS" }, "iso-ir-100 => windows-1252": { "status": "PASS" }, "iso8859-1 => windows-1252": { "status": "PASS" }, "iso88591 => windows-1252": { "status": "PASS" }, "iso_8859-1 => windows-1252": { "status": "PASS" }, "iso_8859-1:1987 => windows-1252": { "status": "PASS" }, "l1 => windows-1252": { "status": "PASS" }, "latin1 => windows-1252": { "status": "PASS" }, "us-ascii => windows-1252": { "status": "PASS" }, "windows-1252 => windows-1252": { "status": "PASS" }, "x-cp1252 => windows-1252": { "status": "PASS" }, "cp1253 => windows-1253": { "status": "PASS" }, "windows-1253 => windows-1253": { "status": "PASS" }, "x-cp1253 => windows-1253": { "status": "PASS" }, "cp1254 => windows-1254": { "status": "PASS" }, "csisolatin5 => windows-1254": { "status": "PASS" }, "iso-8859-9 => windows-1254": { "status": "PASS" }, "iso-ir-148 => windows-1254": { "status": "PASS" }, "iso8859-9 => windows-1254": { "status": "PASS" }, "iso88599 => windows-1254": { "status": "PASS" }, "iso_8859-9 => windows-1254": { "status": "PASS" }, "iso_8859-9:1989 => windows-1254": { "status": "PASS" }, "l5 => windows-1254": { "status": "PASS" }, "latin5 => windows-1254": { "status": "PASS" }, "windows-1254 => windows-1254": { "status": "PASS" }, "x-cp1254 => windows-1254": { "status": "PASS" }, "cp1255 => windows-1255": { "status": "PASS" }, "windows-1255 => windows-1255": { "status": "PASS" }, "x-cp1255 => windows-1255": { "status": "PASS" }, "cp1256 => windows-1256": { "status": "PASS" }, "windows-1256 => windows-1256": { "status": "PASS" }, "x-cp1256 => windows-1256": { "status": "PASS" }, "cp1257 => windows-1257": { "status": "PASS" }, "windows-1257 => windows-1257": { "status": "PASS" }, "x-cp1257 => windows-1257": { "status": "PASS" }, "cp1258 => windows-1258": { "status": "PASS" }, "windows-1258 => windows-1258": { "status": "PASS" }, "x-cp1258 => windows-1258": { "status": "PASS" }, "x-mac-cyrillic => x-mac-cyrillic": { "status": "PASS" }, "x-mac-ukrainian => x-mac-cyrillic": { "status": "PASS" }, "chinese => GBK": { "status": "PASS" }, "csgb2312 => GBK": { "status": "PASS" }, "csiso58gb231280 => GBK": { "status": "PASS" }, "gb2312 => GBK": { "status": "PASS" }, "gb_2312 => GBK": { "status": "PASS" }, "gb_2312-80 => GBK": { "status": "PASS" }, "gbk => GBK": { "status": "PASS" }, "iso-ir-58 => GBK": { "status": "PASS" }, "x-gbk => GBK": { "status": "PASS" }, "gb18030 => gb18030": { "status": "PASS" }, "big5 => Big5": { "status": "PASS" }, "big5-hkscs => Big5": { "status": "PASS" }, "cn-big5 => Big5": { "status": "PASS" }, "csbig5 => Big5": { "status": "PASS" }, "x-x-big5 => Big5": { "status": "PASS" }, "cseucpkdfmtjapanese => EUC-JP": { "status": "PASS" }, "euc-jp => EUC-JP": { "status": "PASS" }, "x-euc-jp => EUC-JP": { "status": "PASS" }, "csiso2022jp => ISO-2022-JP": { "status": "PASS" }, "iso-2022-jp => ISO-2022-JP": { "status": "PASS" }, "csshiftjis => Shift_JIS": { "status": "PASS" }, "ms932 => Shift_JIS": { "status": "PASS" }, "ms_kanji => Shift_JIS": { "status": "PASS" }, "shift-jis => Shift_JIS": { "status": "PASS" }, "shift_jis => Shift_JIS": { "status": "PASS" }, "sjis => Shift_JIS": { "status": "PASS" }, "windows-31j => Shift_JIS": { "status": "PASS" }, "x-sjis => Shift_JIS": { "status": "PASS" }, "cseuckr => EUC-KR": { "status": "PASS" }, "csksc56011987 => EUC-KR": { "status": "PASS" }, "euc-kr => EUC-KR": { "status": "PASS" }, "iso-ir-149 => EUC-KR": { "status": "PASS" }, "korean => EUC-KR": { "status": "PASS" }, "ks_c_5601-1987 => EUC-KR": { "status": "PASS" }, "ks_c_5601-1989 => EUC-KR": { "status": "PASS" }, "ksc5601 => EUC-KR": { "status": "PASS" }, "ksc_5601 => EUC-KR": { "status": "PASS" }, "windows-949 => EUC-KR": { "status": "PASS" }, "unicodefffe => UTF-16BE": { "status": "PASS" }, "utf-16be => UTF-16BE": { "status": "PASS" }, "csunicode => UTF-16LE": { "status": "PASS" }, "iso-10646-ucs-2 => UTF-16LE": { "status": "PASS" }, "ucs-2 => UTF-16LE": { "status": "PASS" }, "unicode => UTF-16LE": { "status": "PASS" }, "unicodefeff => UTF-16LE": { "status": "PASS" }, "utf-16 => UTF-16LE": { "status": "PASS" }, "utf-16le => UTF-16LE": { "status": "PASS" }, "x-user-defined => x-user-defined": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-streaming.any.js.json ================================================ { "Streaming decode: utf-8, 1 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-8, 2 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-8, 3 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-8, 4 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-8, 5 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-16le, 1 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-16le, 2 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-16le, 3 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-16le, 4 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-16le, 5 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-16be, 1 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-16be, 2 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-16be, 3 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-16be, 4 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-16be, 5 byte window (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: UTF-8 chunk tests (ArrayBuffer)": { "status": "PASS" }, "Streaming decode: utf-8, 1 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-8, 2 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-8, 3 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-8, 4 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-8, 5 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-16le, 1 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-16le, 2 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-16le, 3 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-16le, 4 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-16le, 5 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-16be, 1 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-16be, 2 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-16be, 3 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-16be, 4 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: utf-16be, 5 byte window (SharedArrayBuffer)": { "status": "FAIL" }, "Streaming decode: UTF-8 chunk tests (SharedArrayBuffer)": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textdecoder-utf16-surrogates.any.js.json ================================================ { "utf-16le - lone surrogate lead": { "status": "PASS" }, "utf-16le - lone surrogate lead (fatal flag set)": { "status": "PASS" }, "utf-16le - lone surrogate trail": { "status": "PASS" }, "utf-16le - lone surrogate trail (fatal flag set)": { "status": "PASS" }, "utf-16le - unmatched surrogate lead": { "status": "PASS" }, "utf-16le - unmatched surrogate lead (fatal flag set)": { "status": "PASS" }, "utf-16le - unmatched surrogate trail": { "status": "PASS" }, "utf-16le - unmatched surrogate trail (fatal flag set)": { "status": "PASS" }, "utf-16le - swapped surrogate pair": { "status": "PASS" }, "utf-16le - swapped surrogate pair (fatal flag set)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textencoder-constructor-non-utf.any.js.json ================================================ { "Encoding argument supported for decode: UTF-8": { "status": "PASS" }, "Encoding argument not considered for encode: UTF-8": { "status": "PASS" }, "Encoding argument supported for decode: IBM866": { "status": "PASS" }, "Encoding argument not considered for encode: IBM866": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-2": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-2": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-3": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-3": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-4": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-4": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-5": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-5": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-6": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-6": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-7": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-7": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-8": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-8": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-8-I": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-8-I": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-10": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-10": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-13": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-13": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-14": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-14": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-15": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-15": { "status": "PASS" }, "Encoding argument supported for decode: ISO-8859-16": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-8859-16": { "status": "PASS" }, "Encoding argument supported for decode: KOI8-R": { "status": "PASS" }, "Encoding argument not considered for encode: KOI8-R": { "status": "PASS" }, "Encoding argument supported for decode: KOI8-U": { "status": "PASS" }, "Encoding argument not considered for encode: KOI8-U": { "status": "PASS" }, "Encoding argument supported for decode: macintosh": { "status": "PASS" }, "Encoding argument not considered for encode: macintosh": { "status": "PASS" }, "Encoding argument supported for decode: windows-874": { "status": "PASS" }, "Encoding argument not considered for encode: windows-874": { "status": "PASS" }, "Encoding argument supported for decode: windows-1250": { "status": "PASS" }, "Encoding argument not considered for encode: windows-1250": { "status": "PASS" }, "Encoding argument supported for decode: windows-1251": { "status": "PASS" }, "Encoding argument not considered for encode: windows-1251": { "status": "PASS" }, "Encoding argument supported for decode: windows-1252": { "status": "PASS" }, "Encoding argument not considered for encode: windows-1252": { "status": "PASS" }, "Encoding argument supported for decode: windows-1253": { "status": "PASS" }, "Encoding argument not considered for encode: windows-1253": { "status": "PASS" }, "Encoding argument supported for decode: windows-1254": { "status": "PASS" }, "Encoding argument not considered for encode: windows-1254": { "status": "PASS" }, "Encoding argument supported for decode: windows-1255": { "status": "PASS" }, "Encoding argument not considered for encode: windows-1255": { "status": "PASS" }, "Encoding argument supported for decode: windows-1256": { "status": "PASS" }, "Encoding argument not considered for encode: windows-1256": { "status": "PASS" }, "Encoding argument supported for decode: windows-1257": { "status": "PASS" }, "Encoding argument not considered for encode: windows-1257": { "status": "PASS" }, "Encoding argument supported for decode: windows-1258": { "status": "PASS" }, "Encoding argument not considered for encode: windows-1258": { "status": "PASS" }, "Encoding argument supported for decode: x-mac-cyrillic": { "status": "PASS" }, "Encoding argument not considered for encode: x-mac-cyrillic": { "status": "PASS" }, "Encoding argument supported for decode: GBK": { "status": "PASS" }, "Encoding argument not considered for encode: GBK": { "status": "PASS" }, "Encoding argument supported for decode: gb18030": { "status": "PASS" }, "Encoding argument not considered for encode: gb18030": { "status": "PASS" }, "Encoding argument supported for decode: Big5": { "status": "PASS" }, "Encoding argument not considered for encode: Big5": { "status": "PASS" }, "Encoding argument supported for decode: EUC-JP": { "status": "PASS" }, "Encoding argument not considered for encode: EUC-JP": { "status": "PASS" }, "Encoding argument supported for decode: ISO-2022-JP": { "status": "PASS" }, "Encoding argument not considered for encode: ISO-2022-JP": { "status": "PASS" }, "Encoding argument supported for decode: Shift_JIS": { "status": "PASS" }, "Encoding argument not considered for encode: Shift_JIS": { "status": "PASS" }, "Encoding argument supported for decode: EUC-KR": { "status": "PASS" }, "Encoding argument not considered for encode: EUC-KR": { "status": "PASS" }, "Encoding argument not considered for encode: replacement": { "status": "PASS" }, "Encoding argument supported for decode: UTF-16BE": { "status": "PASS" }, "Encoding argument not considered for encode: UTF-16BE": { "status": "PASS" }, "Encoding argument supported for decode: UTF-16LE": { "status": "PASS" }, "Encoding argument not considered for encode: UTF-16LE": { "status": "PASS" }, "Encoding argument supported for decode: x-user-defined": { "status": "PASS" }, "Encoding argument not considered for encode: x-user-defined": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/textencoder-utf16-surrogates.any.js.json ================================================ { "USVString handling: lone surrogate lead": { "status": "PASS" }, "USVString handling: lone surrogate trail": { "status": "PASS" }, "USVString handling: unmatched surrogate lead": { "status": "PASS" }, "USVString handling: unmatched surrogate trail": { "status": "PASS" }, "USVString handling: swapped surrogate pair": { "status": "PASS" }, "USVString handling: properly encoded MUSICAL SYMBOL G CLEF (U+1D11E)": { "status": "PASS" }, "USVString default": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/encoding/unsupported-encodings.any.js.json ================================================ { "UTF-7 should not be supported": { "status": "FAIL" }, "utf-7 should not be supported": { "status": "FAIL" }, "UTF-32 with BOM should decode as UTF-16LE": { "status": "FAIL" }, "UTF-32 with no BOM should decode as UTF-8": { "status": "FAIL" }, "utf-32 with BOM should decode as UTF-16LE": { "status": "FAIL" }, "utf-32 with no BOM should decode as UTF-8": { "status": "FAIL" }, "UTF-32LE with BOM should decode as UTF-16LE": { "status": "FAIL" }, "UTF-32LE with no BOM should decode as UTF-8": { "status": "FAIL" }, "utf-32le with BOM should decode as UTF-16LE": { "status": "FAIL" }, "utf-32le with no BOM should decode as UTF-8": { "status": "FAIL" }, "UTF-32be with no BOM should decode as UTF-8": { "status": "FAIL" }, "UTF-32be with BOM should decode as UTF-8": { "status": "FAIL" }, "utf-32be with no BOM should decode as UTF-8": { "status": "FAIL" }, "utf-32be with BOM should decode as UTF-8": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/abort/general.any.js.json ================================================ { "Aborting rejects with AbortError": { "status": "FAIL" }, "Aborting rejects with abort reason": { "status": "FAIL" }, "Aborting rejects with AbortError - no-cors": { "status": "FAIL" }, "TypeError from request constructor takes priority - RequestInit's window is not null": { "status": "PASS" }, "TypeError from request constructor takes priority - Input URL is not valid": { "status": "FAIL" }, "TypeError from request constructor takes priority - Input URL has credentials": { "status": "PASS" }, "TypeError from request constructor takes priority - RequestInit's mode is navigate": { "status": "PASS" }, "TypeError from request constructor takes priority - RequestInit's referrer is invalid": { "status": "PASS" }, "TypeError from request constructor takes priority - RequestInit's method is invalid": { "status": "FAIL" }, "TypeError from request constructor takes priority - RequestInit's method is forbidden": { "status": "PASS" }, "TypeError from request constructor takes priority - RequestInit's mode is no-cors and method is not simple": { "status": "PASS" }, "TypeError from request constructor takes priority - RequestInit's cache mode is only-if-cached and mode is not same-origin": { "status": "PASS" }, "TypeError from request constructor takes priority - Request with cache mode: only-if-cached and fetch mode cors": { "status": "PASS" }, "TypeError from request constructor takes priority - Request with cache mode: only-if-cached and fetch mode no-cors": { "status": "PASS" }, "TypeError from request constructor takes priority - Bad referrerPolicy init parameter value": { "status": "PASS" }, "TypeError from request constructor takes priority - Bad mode init parameter value": { "status": "PASS" }, "TypeError from request constructor takes priority - Bad credentials init parameter value": { "status": "PASS" }, "TypeError from request constructor takes priority - Bad cache init parameter value": { "status": "PASS" }, "TypeError from request constructor takes priority - Bad redirect init parameter value": { "status": "PASS" }, "Request objects have a signal property": { "status": "FAIL" }, "Signal on request object": { "status": "FAIL" }, "Signal on request object should also have abort reason": { "status": "FAIL" }, "Signal on request object created from request object": { "status": "FAIL" }, "Signal on request object created from request object, with signal on second request": { "status": "FAIL" }, "Signal on request object created from request object, with signal on second request overriding another": { "status": "FAIL" }, "Signal retained after unrelated properties are overridden by fetch": { "status": "FAIL" }, "Signal removed by setting to null": { "status": "FAIL" }, "Already aborted signal rejects immediately": { "status": "FAIL" }, "Request is still 'used' if signal is aborted before fetching": { "status": "FAIL" }, "response.arrayBuffer() rejects if already aborted": { "status": "FAIL" }, "response.blob() rejects if already aborted": { "status": "FAIL" }, "response.bytes() rejects if already aborted": { "status": "FAIL" }, "response.formData() rejects if already aborted": { "status": "FAIL" }, "response.json() rejects if already aborted": { "status": "FAIL" }, "response.text() rejects if already aborted": { "status": "FAIL" }, "Call text() twice on aborted response": { "status": "FAIL" }, "Already aborted signal does not make request": { "status": "FAIL" }, "Already aborted signal can be used for many fetches": { "status": "FAIL" }, "Signal can be used to abort other fetches, even if another fetch succeeded before aborting": { "status": "FAIL" }, "Underlying connection is closed when aborting after receiving response": { "status": "FAIL" }, "Underlying connection is closed when aborting after receiving response - no-cors": { "status": "FAIL" }, "Fetch aborted & connection closed when aborted after calling response.arrayBuffer()": { "status": "FAIL" }, "Fetch aborted & connection closed when aborted after calling response.blob()": { "status": "FAIL" }, "Fetch aborted & connection closed when aborted after calling response.bytes()": { "status": "FAIL" }, "Fetch aborted & connection closed when aborted after calling response.formData()": { "status": "FAIL" }, "Fetch aborted & connection closed when aborted after calling response.json()": { "status": "FAIL" }, "Fetch aborted & connection closed when aborted after calling response.text()": { "status": "FAIL" }, "Stream errors once aborted. Underlying connection closed.": { "status": "FAIL" }, "Stream errors once aborted, after reading. Underlying connection closed.": { "status": "FAIL" }, "Stream will not error if body is empty. It's closed with an empty queue before it errors.": { "status": "FAIL" }, "Readable stream synchronously cancels with AbortError if aborted before reading": { "status": "FAIL" }, "Signal state is cloned": { "status": "FAIL" }, "Clone aborts with original controller": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/abort/request.any.js.json ================================================ { "Calling arrayBuffer() on an aborted request": { "status": "FAIL" }, "Aborting a request after calling arrayBuffer()": { "status": "FAIL" }, "Calling arrayBuffer() on an aborted consumed empty request": { "status": "FAIL" }, "Calling arrayBuffer() on an aborted consumed nonempty request": { "status": "FAIL" }, "Calling blob() on an aborted request": { "status": "FAIL" }, "Aborting a request after calling blob()": { "status": "FAIL" }, "Calling blob() on an aborted consumed empty request": { "status": "FAIL" }, "Calling blob() on an aborted consumed nonempty request": { "status": "FAIL" }, "Calling formData() on an aborted request": { "status": "FAIL" }, "Aborting a request after calling formData()": { "status": "FAIL" }, "Calling formData() on an aborted consumed nonempty request": { "status": "FAIL" }, "Calling json() on an aborted request": { "status": "FAIL" }, "Aborting a request after calling json()": { "status": "FAIL" }, "Calling json() on an aborted consumed nonempty request": { "status": "FAIL" }, "Calling text() on an aborted request": { "status": "FAIL" }, "Aborting a request after calling text()": { "status": "FAIL" }, "Calling text() on an aborted consumed empty request": { "status": "FAIL" }, "Calling text() on an aborted consumed nonempty request": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/accept-header.any.js.json ================================================ { "Request through fetch should have 'accept' header with value '*/*'": { "status": "FAIL" }, "Request through fetch should have 'accept' header with value 'custom/*'": { "status": "FAIL" }, "Request through fetch should have a 'accept-language' header": { "status": "FAIL" }, "Request through fetch should have 'accept-language' header with value 'bzh'": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/conditional-get.any.js.json ================================================ { "Testing conditional GET with ETags": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/header-value-combining.any.js.json ================================================ { "response.headers.get('content-length') expects 0": { "status": "FAIL" }, "response.headers.get('content-length') expects 0, 0": { "status": "FAIL" }, "response.headers.get('double-trouble') expects , ": { "status": "FAIL" }, "response.headers.get('foo-test') expects 1, 2, 3": { "status": "FAIL" }, "response.headers.get('heya') expects , \u000b\f, 1, , , 2": { "status": "FAIL" }, "response.headers.get('www-authenticate') expects 1, 2, 3, 4": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/header-value-null-byte.any.js.json ================================================ { "Ensure fetch() rejects null bytes in headers": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/historical.any.js.json ================================================ { "Headers object no longer has a getAll() method": { "status": "PASS" }, "'type' getter should not exist on Request objects": { "status": "PASS" }, "Response object no longer has a trailer getter": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/http-response-code.any.js.json ================================================ { "Fetch on 425 response should not be retried for non TLS early data.": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/integrity.sub.any.js.json ================================================ { "Empty string integrity": { "status": "PASS" }, "SHA-256 integrity": { "status": "PASS" }, "SHA-384 integrity": { "status": "PASS" }, "SHA-512 integrity": { "status": "PASS" }, "SHA-512 integrity with missing padding": { "status": "PASS" }, "SHA-512 integrity base64url encoded": { "status": "PASS" }, "SHA-512 integrity base64url encoded with missing padding": { "status": "PASS" }, "Invalid integrity": { "status": "FAIL" }, "Multiple integrities: valid stronger than invalid": { "status": "PASS" }, "Multiple integrities: invalid stronger than valid": { "status": "FAIL" }, "Multiple integrities: invalid as strong as valid": { "status": "PASS" }, "Multiple integrities: both are valid": { "status": "PASS" }, "Multiple integrities: both are invalid": { "status": "FAIL" }, "CORS empty integrity": { "status": "PASS" }, "CORS SHA-512 integrity": { "status": "PASS" }, "CORS invalid integrity": { "status": "FAIL" }, "Empty string integrity for opaque response": { "status": "FAIL" }, "SHA-* integrity for opaque response": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/keepalive.any.js.json ================================================ { "[keepalive] simple GET request on 'load' [no payload]; setting up": { "status": "FAIL" }, "[keepalive] simple GET request on 'unload' [no payload]; setting up": { "status": "FAIL" }, "[keepalive] simple GET request on 'pagehide' [no payload]; setting up": { "status": "FAIL" }, "[keepalive] simple POST request on 'load' [no payload]; setting up": { "status": "FAIL" }, "[keepalive] simple POST request on 'unload' [no payload]; setting up": { "status": "FAIL" }, "[keepalive] simple POST request on 'pagehide' [no payload]; setting up": { "status": "FAIL" }, "simple keepalive test for web workers;": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/mode-same-origin.any.js.json ================================================ { "Fetch ../resources/top.txt with same-origin mode": { "status": "FAIL" }, "Fetch http://web-platform.test:8000/fetch/api/resources/top.txt with same-origin mode": { "status": "FAIL" }, "Fetch https://web-platform.test:8443/fetch/api/resources/top.txt with same-origin mode": { "status": "FAIL" }, "Fetch http://www1.web-platform.test:8000/fetch/api/resources/top.txt with same-origin mode": { "status": "FAIL" }, "Fetch /fetch/api/basic/../resources/redirect.py?location=../resources/top.txt with same-origin mode": { "status": "FAIL" }, "Fetch /fetch/api/basic/../resources/redirect.py?location=http://web-platform.test:8000/fetch/api/resources/top.txt with same-origin mode": { "status": "FAIL" }, "Fetch /fetch/api/basic/../resources/redirect.py?location=https://web-platform.test:8443/fetch/api/resources/top.txt with same-origin mode": { "status": "FAIL" }, "Fetch /fetch/api/basic/../resources/redirect.py?location=http://www1.web-platform.test:8000/fetch/api/resources/top.txt with same-origin mode": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/referrer.any.js.json ================================================ { "origin-when-cross-origin policy on a same-origin URL": { "status": "FAIL" }, "origin-when-cross-origin policy on a cross-origin URL": { "status": "FAIL" }, "origin-when-cross-origin policy on a cross-origin URL after same-origin redirection": { "status": "FAIL" }, "origin-when-cross-origin policy on a same-origin URL after cross-origin redirection": { "status": "FAIL" }, "Referrer with credentials should be stripped": { "status": "FAIL" }, "Referrer with fragment ID should be stripped": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/request-forbidden-headers.any.js.json ================================================ { "Accept-Charset is a forbidden request header": { "status": "FAIL" }, "Accept-Encoding is a forbidden request header": { "status": "FAIL" }, "Access-Control-Request-Headers is a forbidden request header": { "status": "FAIL" }, "Access-Control-Request-Method is a forbidden request header": { "status": "FAIL" }, "Connection is a forbidden request header": { "status": "FAIL" }, "Content-Length is a forbidden request header": { "status": "FAIL" }, "Cookie is a forbidden request header": { "status": "FAIL" }, "Cookie2 is a forbidden request header": { "status": "FAIL" }, "Date is a forbidden request header": { "status": "FAIL" }, "DNT is a forbidden request header": { "status": "FAIL" }, "Expect is a forbidden request header": { "status": "FAIL" }, "Host is a forbidden request header": { "status": "FAIL" }, "Keep-Alive is a forbidden request header": { "status": "FAIL" }, "Origin is a forbidden request header": { "status": "FAIL" }, "Referer is a forbidden request header": { "status": "FAIL" }, "TE is a forbidden request header": { "status": "FAIL" }, "Trailer is a forbidden request header": { "status": "FAIL" }, "Transfer-Encoding is a forbidden request header": { "status": "FAIL" }, "Upgrade is a forbidden request header": { "status": "FAIL" }, "Via is a forbidden request header": { "status": "FAIL" }, "Proxy- is a forbidden request header": { "status": "FAIL" }, "Proxy-Test is a forbidden request header": { "status": "FAIL" }, "Sec- is a forbidden request header": { "status": "FAIL" }, "Sec-Test is a forbidden request header": { "status": "FAIL" }, "header x-http-method-override is forbidden to use value TRACE": { "status": "FAIL" }, "header x-http-method is forbidden to use value TRACE": { "status": "FAIL" }, "header x-method-override is forbidden to use value TRACE": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is forbidden to use value TRACE": { "status": "FAIL" }, "header X-HTTP-METHOD is forbidden to use value TRACE": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is forbidden to use value TRACE": { "status": "FAIL" }, "header x-http-method-override is forbidden to use value TRACK": { "status": "FAIL" }, "header x-http-method is forbidden to use value TRACK": { "status": "FAIL" }, "header x-method-override is forbidden to use value TRACK": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is forbidden to use value TRACK": { "status": "FAIL" }, "header X-HTTP-METHOD is forbidden to use value TRACK": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is forbidden to use value TRACK": { "status": "FAIL" }, "header x-http-method-override is forbidden to use value CONNECT": { "status": "FAIL" }, "header x-http-method is forbidden to use value CONNECT": { "status": "FAIL" }, "header x-method-override is forbidden to use value CONNECT": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is forbidden to use value CONNECT": { "status": "FAIL" }, "header X-HTTP-METHOD is forbidden to use value CONNECT": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is forbidden to use value CONNECT": { "status": "FAIL" }, "header x-http-method-override is forbidden to use value trace": { "status": "FAIL" }, "header x-http-method is forbidden to use value trace": { "status": "FAIL" }, "header x-method-override is forbidden to use value trace": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is forbidden to use value trace": { "status": "FAIL" }, "header X-HTTP-METHOD is forbidden to use value trace": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is forbidden to use value trace": { "status": "FAIL" }, "header x-http-method-override is forbidden to use value track": { "status": "FAIL" }, "header x-http-method is forbidden to use value track": { "status": "FAIL" }, "header x-method-override is forbidden to use value track": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is forbidden to use value track": { "status": "FAIL" }, "header X-HTTP-METHOD is forbidden to use value track": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is forbidden to use value track": { "status": "FAIL" }, "header x-http-method-override is forbidden to use value connect": { "status": "FAIL" }, "header x-http-method is forbidden to use value connect": { "status": "FAIL" }, "header x-method-override is forbidden to use value connect": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is forbidden to use value connect": { "status": "FAIL" }, "header X-HTTP-METHOD is forbidden to use value connect": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is forbidden to use value connect": { "status": "FAIL" }, "header x-http-method-override is forbidden to use value trace,": { "status": "FAIL" }, "header x-http-method is forbidden to use value trace,": { "status": "FAIL" }, "header x-method-override is forbidden to use value trace,": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is forbidden to use value trace,": { "status": "FAIL" }, "header X-HTTP-METHOD is forbidden to use value trace,": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is forbidden to use value trace,": { "status": "FAIL" }, "header x-http-method-override is forbidden to use value GET,track ": { "status": "FAIL" }, "header x-http-method is forbidden to use value GET,track ": { "status": "FAIL" }, "header x-method-override is forbidden to use value GET,track ": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is forbidden to use value GET,track ": { "status": "FAIL" }, "header X-HTTP-METHOD is forbidden to use value GET,track ": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is forbidden to use value GET,track ": { "status": "FAIL" }, "header x-http-method-override is forbidden to use value connect": { "status": "FAIL" }, "header x-http-method is forbidden to use value connect": { "status": "FAIL" }, "header x-method-override is forbidden to use value connect": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is forbidden to use value connect": { "status": "FAIL" }, "header X-HTTP-METHOD is forbidden to use value connect": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is forbidden to use value connect": { "status": "FAIL" }, "header x-http-method-override is allowed to use value GETTRACE": { "status": "FAIL" }, "header x-http-method is allowed to use value GETTRACE": { "status": "FAIL" }, "header x-method-override is allowed to use value GETTRACE": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is allowed to use value GETTRACE": { "status": "FAIL" }, "header X-HTTP-METHOD is allowed to use value GETTRACE": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is allowed to use value GETTRACE": { "status": "FAIL" }, "header x-http-method-override is allowed to use value GET": { "status": "FAIL" }, "header x-http-method is allowed to use value GET": { "status": "FAIL" }, "header x-method-override is allowed to use value GET": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is allowed to use value GET": { "status": "FAIL" }, "header X-HTTP-METHOD is allowed to use value GET": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is allowed to use value GET": { "status": "FAIL" }, "header x-http-method-override is allowed to use value \",TRACE\",": { "status": "FAIL" }, "header x-http-method is allowed to use value \",TRACE\",": { "status": "FAIL" }, "header x-method-override is allowed to use value \",TRACE\",": { "status": "FAIL" }, "header X-HTTP-METHOD-OVERRIDE is allowed to use value \",TRACE\",": { "status": "FAIL" }, "header X-HTTP-METHOD is allowed to use value \",TRACE\",": { "status": "FAIL" }, "header X-METHOD-OVERRIDE is allowed to use value \",TRACE\",": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/request-head.any.js.json ================================================ { "Fetch with HEAD with body": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/request-headers-case.any.js.json ================================================ { "Multiple headers with the same name, different case (THIS-is-A-test first)": { "status": "FAIL" }, "Multiple headers with the same name, different case (THIS-IS-A-TEST first)": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/request-headers-nonascii.any.js.json ================================================ { "Non-ascii bytes in request headers": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/request-headers.any.js.json ================================================ { "Fetch with GET": { "status": "FAIL" }, "Fetch with HEAD": { "status": "FAIL" }, "Fetch with PUT without body": { "status": "FAIL" }, "Fetch with PUT with body": { "status": "FAIL" }, "Fetch with POST without body": { "status": "FAIL" }, "Fetch with POST with text body": { "status": "FAIL" }, "Fetch with POST with FormData body": { "status": "FAIL" }, "Fetch with POST with URLSearchParams body": { "status": "FAIL" }, "Fetch with POST with Blob body": { "status": "FAIL" }, "Fetch with POST with ArrayBuffer body": { "status": "FAIL" }, "Fetch with POST with Uint8Array body": { "status": "FAIL" }, "Fetch with POST with Int8Array body": { "status": "FAIL" }, "Fetch with POST with Float16Array body": { "status": "FAIL" }, "Fetch with POST with Float32Array body": { "status": "FAIL" }, "Fetch with POST with Float64Array body": { "status": "FAIL" }, "Fetch with POST with DataView body": { "status": "FAIL" }, "Fetch with POST with Blob body with mime type": { "status": "FAIL" }, "Fetch with Chicken": { "status": "FAIL" }, "Fetch with Chicken with body": { "status": "FAIL" }, "Fetch with GET and mode \"cors\" does not need an Origin header": { "status": "FAIL" }, "Fetch with POST and mode \"same-origin\" needs an Origin header": { "status": "FAIL" }, "Fetch with POST and mode \"no-cors\" needs an Origin header": { "status": "FAIL" }, "Fetch with PUT and mode \"same-origin\" needs an Origin header": { "status": "FAIL" }, "Fetch with TacO and mode \"same-origin\" needs an Origin header": { "status": "FAIL" }, "Fetch with TacO and mode \"cors\" needs an Origin header": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/request-referrer.any.js.json ================================================ { "about:client referrer": { "status": "FAIL" }, "url referrer": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/request-upload.any.js.json ================================================ { "Fetch with PUT with body": { "status": "PASS" }, "Fetch with POST with text body": { "status": "PASS" }, "Fetch with POST with URLSearchParams body": { "status": "PASS" }, "Fetch with POST with Blob body": { "status": "FAIL" }, "Fetch with POST with ArrayBuffer body": { "status": "PASS" }, "Fetch with POST with Uint8Array body": { "status": "PASS" }, "Fetch with POST with Int8Array body": { "status": "PASS" }, "Fetch with POST with Float16Array body": { "status": "PASS" }, "Fetch with POST with Float32Array body": { "status": "PASS" }, "Fetch with POST with Float64Array body": { "status": "PASS" }, "Fetch with POST with DataView body": { "status": "PASS" }, "Fetch with POST with Blob body with mime type": { "status": "FAIL" }, "Fetch with POST with ReadableStream containing String": { "status": "FAIL" }, "Fetch with POST with ReadableStream containing null": { "status": "FAIL" }, "Fetch with POST with ReadableStream containing number": { "status": "FAIL" }, "Fetch with POST with ReadableStream containing ArrayBuffer": { "status": "FAIL" }, "Fetch with POST with ReadableStream containing Blob": { "status": "FAIL" }, "Fetch with POST with text body on 421 response should be retried once on new connection.": { "status": "FAIL" }, "Streaming upload shouldn't work on Http/1.1.": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/response-null-body.any.js.json ================================================ { "Response.body is null for responses with status=204 (method=GET)": { "status": "PASS" }, "Response.body is null for responses with status=204 (method=POST)": { "status": "PASS" }, "Response.body is null for responses with status=204 (method=OPTIONS)": { "status": "PASS" }, "Response.body is null for responses with status=205 (method=GET)": { "status": "PASS" }, "Response.body is null for responses with status=205 (method=POST)": { "status": "PASS" }, "Response.body is null for responses with status=205 (method=OPTIONS)": { "status": "PASS" }, "Response.body is null for responses with status=304 (method=GET)": { "status": "PASS" }, "Response.body is null for responses with status=304 (method=POST)": { "status": "PASS" }, "Response.body is null for responses with status=304 (method=OPTIONS)": { "status": "PASS" }, "Response.body is null for responses with method=HEAD": { "status": "FAIL" }, "Null body status with subresource integrity should abort": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/response-url.sub.any.js.json ================================================ { "Testing response url getter with http://web-platform.test:8000/ada": { "status": "PASS" }, "Testing response url getter with http://web-platform.test:8000/#": { "status": "FAIL" }, "Testing response url getter with http://web-platform.test:8000/#ada": { "status": "FAIL" }, "Testing response url getter with http://web-platform.test:8000#ada": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/scheme-about.any.js.json ================================================ { "Fetching about:blank with method GET is KO": { "status": "PASS" }, "Fetching about:blank with method PUT is KO": { "status": "PASS" }, "Fetching about:blank with method POST is KO": { "status": "PASS" }, "Fetching about:invalid.com with method GET is KO": { "status": "PASS" }, "Fetching about:config with method GET is KO": { "status": "PASS" }, "Fetching about:unicorn with method GET is KO": { "status": "PASS" }, "Fetching about:blank with range header does not affect behavior": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/scheme-blob.sub.any.js.json ================================================ { "Fetching [GET] URL.createObjectURL(blob) is OK": { "status": "FAIL" }, "Fetching [GET] blob:http://www.web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching [POST] URL.createObjectURL(blob) is KO": { "status": "FAIL" }, "Fetching [OPTIONS] URL.createObjectURL(blob) is KO": { "status": "FAIL" }, "Fetching [HEAD] URL.createObjectURL(blob) is KO": { "status": "FAIL" }, "Fetching [PUT] URL.createObjectURL(blob) is KO": { "status": "FAIL" }, "Fetching [DELETE] URL.createObjectURL(blob) is KO": { "status": "FAIL" }, "Fetching [INVALID] URL.createObjectURL(blob) is KO": { "status": "FAIL" }, "Fetching [GET] blob:not-backed-by-a-blob/ is KO": { "status": "FAIL" }, "Fetching URL.createObjectURL(empty_blob) is OK": { "status": "FAIL" }, "Fetching URL.createObjectURL(empty_type_blob) is OK": { "status": "FAIL" }, "Fetching URL.createObjectURL(empty_data_blob) is OK": { "status": "FAIL" }, "Fetching URL.createObjectURL(invalid_type_blob) is OK": { "status": "FAIL" }, "Blob content is not sniffed for a content type [image/png]": { "status": "FAIL" }, "Blob content is not sniffed for a content type [text/xml]": { "status": "FAIL" }, "Set content type to the empty string for slice with invalid content type": { "status": "FAIL" }, "Set content type to the empty string for slice with no content type ": { "status": "FAIL" }, "Blob.slice should not sniff the content for a content type": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/scheme-data.any.js.json ================================================ { "Fetching data:,response%27s%20body is OK": { "status": "FAIL" }, "Fetching data:,response%27s%20body is OK (same-origin)": { "status": "FAIL" }, "Fetching data:,response%27s%20body is OK (cors)": { "status": "FAIL" }, "Fetching data:text/plain;base64,cmVzcG9uc2UncyBib[...] is OK": { "status": "FAIL" }, "Fetching data:image/png;base64,cmVzcG9uc2UncyBib2[...] is OK": { "status": "FAIL" }, "Fetching [POST] data:,response%27s%20body is OK": { "status": "FAIL" }, "Fetching [HEAD] data:,response%27s%20body is OK": { "status": "FAIL" }, "Fetching [GET] data:notAdataUrl.com is KO": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/scheme-others.sub.any.js.json ================================================ { "Fetching aaa://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching cap://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching cid://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching dav://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching dict://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching dns://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching geo://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching im://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching imap://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching ipp://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching ldap://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching mailto://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching nfs://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching pop://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching rtsp://web-platform.test:8000/ is KO": { "status": "FAIL" }, "Fetching snmp://web-platform.test:8000/ is KO": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/status.h2.any.js.json ================================================ { "statusText over H2 for status 200 should be the empty string": { "status": "FAIL" }, "statusText over H2 for status 210 should be the empty string": { "status": "PASS" }, "statusText over H2 for status 400 should be the empty string": { "status": "FAIL" }, "statusText over H2 for status 404 should be the empty string": { "status": "FAIL" }, "statusText over H2 for status 410 should be the empty string": { "status": "FAIL" }, "statusText over H2 for status 500 should be the empty string": { "status": "FAIL" }, "statusText over H2 for status 502 should be the empty string": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/stream-response.any.js.json ================================================ { "Stream response's body when content-type is present": { "status": "PASS" }, "Stream response's body when content-type is not present": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/stream-safe-creation.any.js.json ================================================ { "throwing Object.prototype.start accessor should not affect stream creation by 'fetch'": { "status": "PASS" }, "Object.prototype.start accessor returning invalid value should not affect stream creation by 'fetch'": { "status": "PASS" }, "throwing Object.prototype.type accessor should not affect stream creation by 'fetch'": { "status": "PASS" }, "Object.prototype.type accessor returning invalid value should not affect stream creation by 'fetch'": { "status": "PASS" }, "throwing Object.prototype.size accessor should not affect stream creation by 'fetch'": { "status": "PASS" }, "Object.prototype.size accessor returning invalid value should not affect stream creation by 'fetch'": { "status": "PASS" }, "throwing Object.prototype.highWaterMark accessor should not affect stream creation by 'fetch'": { "status": "PASS" }, "Object.prototype.highWaterMark accessor returning invalid value should not affect stream creation by 'fetch'": { "status": "PASS" }, "Object.prototype.start function which errors the stream should not affect stream creation by 'fetch'": { "status": "PASS" }, "throwing Object.prototype.start accessor should not affect stream creation by 'request'": { "status": "PASS" }, "Object.prototype.start accessor returning invalid value should not affect stream creation by 'request'": { "status": "PASS" }, "throwing Object.prototype.type accessor should not affect stream creation by 'request'": { "status": "PASS" }, "Object.prototype.type accessor returning invalid value should not affect stream creation by 'request'": { "status": "PASS" }, "throwing Object.prototype.size accessor should not affect stream creation by 'request'": { "status": "PASS" }, "Object.prototype.size accessor returning invalid value should not affect stream creation by 'request'": { "status": "PASS" }, "throwing Object.prototype.highWaterMark accessor should not affect stream creation by 'request'": { "status": "PASS" }, "Object.prototype.highWaterMark accessor returning invalid value should not affect stream creation by 'request'": { "status": "PASS" }, "Object.prototype.start function which errors the stream should not affect stream creation by 'request'": { "status": "PASS" }, "throwing Object.prototype.start accessor should not affect stream creation by 'response'": { "status": "PASS" }, "Object.prototype.start accessor returning invalid value should not affect stream creation by 'response'": { "status": "PASS" }, "throwing Object.prototype.type accessor should not affect stream creation by 'response'": { "status": "PASS" }, "Object.prototype.type accessor returning invalid value should not affect stream creation by 'response'": { "status": "PASS" }, "throwing Object.prototype.size accessor should not affect stream creation by 'response'": { "status": "PASS" }, "Object.prototype.size accessor returning invalid value should not affect stream creation by 'response'": { "status": "PASS" }, "throwing Object.prototype.highWaterMark accessor should not affect stream creation by 'response'": { "status": "PASS" }, "Object.prototype.highWaterMark accessor returning invalid value should not affect stream creation by 'response'": { "status": "PASS" }, "Object.prototype.start function which errors the stream should not affect stream creation by 'response'": { "status": "PASS" }, "throwing Object.prototype.start accessor should not affect stream creation by 'consumeEmptyResponse'": { "status": "PASS" }, "Object.prototype.start accessor returning invalid value should not affect stream creation by 'consumeEmptyResponse'": { "status": "PASS" }, "throwing Object.prototype.type accessor should not affect stream creation by 'consumeEmptyResponse'": { "status": "PASS" }, "Object.prototype.type accessor returning invalid value should not affect stream creation by 'consumeEmptyResponse'": { "status": "PASS" }, "throwing Object.prototype.size accessor should not affect stream creation by 'consumeEmptyResponse'": { "status": "PASS" }, "Object.prototype.size accessor returning invalid value should not affect stream creation by 'consumeEmptyResponse'": { "status": "PASS" }, "throwing Object.prototype.highWaterMark accessor should not affect stream creation by 'consumeEmptyResponse'": { "status": "PASS" }, "Object.prototype.highWaterMark accessor returning invalid value should not affect stream creation by 'consumeEmptyResponse'": { "status": "PASS" }, "Object.prototype.start function which errors the stream should not affect stream creation by 'consumeEmptyResponse'": { "status": "PASS" }, "throwing Object.prototype.start accessor should not affect stream creation by 'consumeNonEmptyResponse'": { "status": "PASS" }, "Object.prototype.start accessor returning invalid value should not affect stream creation by 'consumeNonEmptyResponse'": { "status": "PASS" }, "throwing Object.prototype.type accessor should not affect stream creation by 'consumeNonEmptyResponse'": { "status": "PASS" }, "Object.prototype.type accessor returning invalid value should not affect stream creation by 'consumeNonEmptyResponse'": { "status": "PASS" }, "throwing Object.prototype.size accessor should not affect stream creation by 'consumeNonEmptyResponse'": { "status": "PASS" }, "Object.prototype.size accessor returning invalid value should not affect stream creation by 'consumeNonEmptyResponse'": { "status": "PASS" }, "throwing Object.prototype.highWaterMark accessor should not affect stream creation by 'consumeNonEmptyResponse'": { "status": "PASS" }, "Object.prototype.highWaterMark accessor returning invalid value should not affect stream creation by 'consumeNonEmptyResponse'": { "status": "PASS" }, "Object.prototype.start function which errors the stream should not affect stream creation by 'consumeNonEmptyResponse'": { "status": "PASS" }, "throwing Object.prototype.start accessor should not affect stream creation by 'consumeEmptyRequest'": { "status": "PASS" }, "Object.prototype.start accessor returning invalid value should not affect stream creation by 'consumeEmptyRequest'": { "status": "PASS" }, "throwing Object.prototype.type accessor should not affect stream creation by 'consumeEmptyRequest'": { "status": "PASS" }, "Object.prototype.type accessor returning invalid value should not affect stream creation by 'consumeEmptyRequest'": { "status": "PASS" }, "throwing Object.prototype.size accessor should not affect stream creation by 'consumeEmptyRequest'": { "status": "PASS" }, "Object.prototype.size accessor returning invalid value should not affect stream creation by 'consumeEmptyRequest'": { "status": "PASS" }, "throwing Object.prototype.highWaterMark accessor should not affect stream creation by 'consumeEmptyRequest'": { "status": "PASS" }, "Object.prototype.highWaterMark accessor returning invalid value should not affect stream creation by 'consumeEmptyRequest'": { "status": "PASS" }, "Object.prototype.start function which errors the stream should not affect stream creation by 'consumeEmptyRequest'": { "status": "PASS" }, "throwing Object.prototype.start accessor should not affect stream creation by 'consumeNonEmptyRequest'": { "status": "PASS" }, "Object.prototype.start accessor returning invalid value should not affect stream creation by 'consumeNonEmptyRequest'": { "status": "PASS" }, "throwing Object.prototype.type accessor should not affect stream creation by 'consumeNonEmptyRequest'": { "status": "PASS" }, "Object.prototype.type accessor returning invalid value should not affect stream creation by 'consumeNonEmptyRequest'": { "status": "PASS" }, "throwing Object.prototype.size accessor should not affect stream creation by 'consumeNonEmptyRequest'": { "status": "PASS" }, "Object.prototype.size accessor returning invalid value should not affect stream creation by 'consumeNonEmptyRequest'": { "status": "PASS" }, "throwing Object.prototype.highWaterMark accessor should not affect stream creation by 'consumeNonEmptyRequest'": { "status": "PASS" }, "Object.prototype.highWaterMark accessor returning invalid value should not affect stream creation by 'consumeNonEmptyRequest'": { "status": "PASS" }, "Object.prototype.start function which errors the stream should not affect stream creation by 'consumeNonEmptyRequest'": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/basic/text-utf8.any.js.json ================================================ { "UTF-8 with BOM with Request.text()": { "status": "FAIL" }, "UTF-8 with BOM with Response.text()": { "status": "FAIL" }, "UTF-8 with BOM with fetched data (UTF-8 charset)": { "status": "FAIL" }, "UTF-8 with BOM with fetched data (UTF-16 charset)": { "status": "FAIL" }, "UTF-8 with BOM (Response object)": { "status": "PASS" }, "UTF-8 with BOM (Request object)": { "status": "PASS" }, "UTF-8 without BOM with Request.text()": { "status": "PASS" }, "UTF-8 without BOM with Response.text()": { "status": "PASS" }, "UTF-8 without BOM with fetched data (UTF-8 charset)": { "status": "PASS" }, "UTF-8 without BOM with fetched data (UTF-16 charset)": { "status": "PASS" }, "UTF-8 without BOM (Response object)": { "status": "PASS" }, "UTF-8 without BOM (Request object)": { "status": "PASS" }, "UTF-16BE with BOM decoded as UTF-8 with Request.text()": { "status": "FAIL" }, "UTF-16BE with BOM decoded as UTF-8 with Response.text()": { "status": "FAIL" }, "UTF-16BE with BOM decoded as UTF-8 with fetched data (UTF-8 charset)": { "status": "FAIL" }, "UTF-16BE with BOM decoded as UTF-8 with fetched data (UTF-16 charset)": { "status": "FAIL" }, "UTF-16BE with BOM decoded as UTF-8 (Response object)": { "status": "PASS" }, "UTF-16BE with BOM decoded as UTF-8 (Request object)": { "status": "PASS" }, "UTF-16LE with BOM decoded as UTF-8 with Request.text()": { "status": "FAIL" }, "UTF-16LE with BOM decoded as UTF-8 with Response.text()": { "status": "FAIL" }, "UTF-16LE with BOM decoded as UTF-8 with fetched data (UTF-8 charset)": { "status": "FAIL" }, "UTF-16LE with BOM decoded as UTF-8 with fetched data (UTF-16 charset)": { "status": "FAIL" }, "UTF-16LE with BOM decoded as UTF-8 (Response object)": { "status": "PASS" }, "UTF-16LE with BOM decoded as UTF-8 (Request object)": { "status": "PASS" }, "UTF-16 without BOM decoded as UTF-8 with Request.text()": { "status": "FAIL" }, "UTF-16 without BOM decoded as UTF-8 with Response.text()": { "status": "FAIL" }, "UTF-16 without BOM decoded as UTF-8 with fetched data (UTF-8 charset)": { "status": "FAIL" }, "UTF-16 without BOM decoded as UTF-8 with fetched data (UTF-16 charset)": { "status": "FAIL" }, "UTF-16 without BOM decoded as UTF-8 (Response object)": { "status": "PASS" }, "UTF-16 without BOM decoded as UTF-8 (Request object)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/body/cloned-any.js.json ================================================ { "FormData is cloned": { "status": "FAIL" }, "URLSearchParams is cloned": { "status": "PASS" }, "TypedArray is cloned": { "status": "PASS" }, "ArrayBuffer is cloned": { "status": "PASS" }, "Blob is cloned": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/body/formdata.any.js.json ================================================ { "Consume empty response.formData() as FormData": { "status": "PASS" }, "Consume empty request.formData() as FormData": { "status": "PASS" }, "Consume multipart/form-data headers case-insensitively": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/header-setcookie.any.js.json ================================================ { "Headers.prototype.get combines set-cookie headers in order": { "status": "PASS" }, "Headers iterator does not combine set-cookie headers": { "status": "PASS" }, "Headers iterator does not special case set-cookie2 headers": { "status": "PASS" }, "Headers iterator does not combine set-cookie & set-cookie2 headers": { "status": "PASS" }, "Headers iterator preserves set-cookie ordering": { "status": "PASS" }, "Headers iterator preserves per header ordering, but sorts keys alphabetically": { "status": "PASS" }, "Headers iterator preserves per header ordering, but sorts keys alphabetically (and ignores value ordering)": { "status": "PASS" }, "Headers iterator is correctly updated with set-cookie changes": { "status": "PASS" }, "Headers iterator is correctly updated with set-cookie changes #2": { "status": "PASS" }, "Headers.prototype.has works for set-cookie": { "status": "PASS" }, "Headers.prototype.append works for set-cookie": { "status": "PASS" }, "Headers.prototype.set works for set-cookie": { "status": "PASS" }, "Headers.prototype.delete works for set-cookie": { "status": "PASS" }, "Headers.prototype.getSetCookie with no headers present": { "status": "PASS" }, "Headers.prototype.getSetCookie with one header": { "status": "PASS" }, "Headers.prototype.getSetCookie with one header created from an object": { "status": "PASS" }, "Headers.prototype.getSetCookie with multiple headers": { "status": "PASS" }, "Headers.prototype.getSetCookie with an empty header": { "status": "PASS" }, "Headers.prototype.getSetCookie with two equal headers": { "status": "PASS" }, "Headers.prototype.getSetCookie ignores set-cookie2 headers": { "status": "PASS" }, "Headers.prototype.getSetCookie preserves header ordering": { "status": "PASS" }, "Adding Set-Cookie headers normalizes their value": { "status": "PASS" }, "Adding invalid Set-Cookie headers throws": { "status": "PASS" }, "Set-Cookie is a forbidden response header": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/header-values-normalize.any.js.json ================================================ { "fetch() with value %00": { "status": "PASS" }, "fetch() with value %01": { "status": "FAIL" }, "fetch() with value %02": { "status": "FAIL" }, "fetch() with value %03": { "status": "FAIL" }, "fetch() with value %04": { "status": "FAIL" }, "fetch() with value %05": { "status": "FAIL" }, "fetch() with value %06": { "status": "FAIL" }, "fetch() with value %07": { "status": "FAIL" }, "fetch() with value %08": { "status": "FAIL" }, "fetch() with value %09": { "status": "PASS" }, "fetch() with value %0A": { "status": "PASS" }, "fetch() with value %0D": { "status": "PASS" }, "fetch() with value %0E": { "status": "FAIL" }, "fetch() with value %0F": { "status": "FAIL" }, "fetch() with value %10": { "status": "FAIL" }, "fetch() with value %11": { "status": "FAIL" }, "fetch() with value %12": { "status": "FAIL" }, "fetch() with value %13": { "status": "FAIL" }, "fetch() with value %14": { "status": "FAIL" }, "fetch() with value %15": { "status": "FAIL" }, "fetch() with value %16": { "status": "FAIL" }, "fetch() with value %17": { "status": "FAIL" }, "fetch() with value %18": { "status": "FAIL" }, "fetch() with value %19": { "status": "FAIL" }, "fetch() with value %1A": { "status": "FAIL" }, "fetch() with value %1B": { "status": "FAIL" }, "fetch() with value %1C": { "status": "FAIL" }, "fetch() with value %1D": { "status": "FAIL" }, "fetch() with value %1E": { "status": "FAIL" }, "fetch() with value %1F": { "status": "FAIL" }, "fetch() with value %20": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/header-values.any.js.json ================================================ { "fetch() with value x%00x needs to throw": { "status": "PASS" }, "fetch() with value x%0Ax needs to throw": { "status": "PASS" }, "fetch() with value x%0Dx needs to throw": { "status": "PASS" }, "fetch() with all valid values": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/headers-basic.any.js.json ================================================ { "Create headers from no parameter": { "status": "PASS" }, "Create headers from undefined parameter": { "status": "PASS" }, "Create headers from empty object": { "status": "PASS" }, "Create headers with null should throw": { "status": "PASS" }, "Create headers with 1 should throw": { "status": "PASS" }, "Create headers with sequence": { "status": "PASS" }, "Create headers with record": { "status": "PASS" }, "Create headers with existing headers": { "status": "PASS" }, "Create headers with existing headers with custom iterator": { "status": "PASS" }, "Check append method": { "status": "PASS" }, "Check set method": { "status": "PASS" }, "Check has method": { "status": "PASS" }, "Check delete method": { "status": "PASS" }, "Check get method": { "status": "PASS" }, "Check keys method": { "status": "PASS" }, "Check values method": { "status": "PASS" }, "Check entries method": { "status": "PASS" }, "Check Symbol.iterator method": { "status": "PASS" }, "Check forEach method": { "status": "PASS" }, "Iteration skips elements removed while iterating": { "status": "PASS" }, "Removing elements already iterated over causes an element to be skipped during iteration": { "status": "PASS" }, "Appending a value pair during iteration causes it to be reached during iteration": { "status": "PASS" }, "Prepending a value pair before the current element position causes it to be skipped during iteration and adds the current element a second time": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/headers-casing.any.js.json ================================================ { "Create headers, names use characters with different case": { "status": "PASS" }, "Check append method, names use characters with different case": { "status": "PASS" }, "Check set method, names use characters with different case": { "status": "PASS" }, "Check delete method, names use characters with different case": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/headers-combine.any.js.json ================================================ { "Create headers using same name for different values": { "status": "PASS" }, "Check delete and has methods when using same name for different values": { "status": "PASS" }, "Check set methods when called with already used name": { "status": "PASS" }, "Check append methods when called with already used name": { "status": "PASS" }, "Iterate combined values": { "status": "PASS" }, "Iterate combined values in sorted order": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/headers-errors.any.js.json ================================================ { "Create headers giving an array having one string as init argument": { "status": "PASS" }, "Create headers giving an array having three strings as init argument": { "status": "PASS" }, "Create headers giving bad header name as init argument": { "status": "PASS" }, "Create headers giving bad header value as init argument": { "status": "PASS" }, "Check headers get with an invalid name invalidĀ": { "status": "PASS" }, "Check headers get with an invalid name [object Object]": { "status": "PASS" }, "Check headers delete with an invalid name invalidĀ": { "status": "PASS" }, "Check headers delete with an invalid name [object Object]": { "status": "PASS" }, "Check headers has with an invalid name invalidĀ": { "status": "PASS" }, "Check headers has with an invalid name [object Object]": { "status": "PASS" }, "Check headers set with an invalid name invalidĀ": { "status": "PASS" }, "Check headers set with an invalid name [object Object]": { "status": "PASS" }, "Check headers set with an invalid value invalidĀ": { "status": "PASS" }, "Check headers append with an invalid name invalidĀ": { "status": "PASS" }, "Check headers append with an invalid name [object Object]": { "status": "PASS" }, "Check headers append with an invalid value invalidĀ": { "status": "PASS" }, "Headers forEach throws if argument is not callable": { "status": "PASS" }, "Headers forEach loop should stop if callback is throwing exception": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/headers-no-cors.any.js.json ================================================ { "Loading data…": { "status": "PASS" }, "\"no-cors\" Headers object cannot have accept set to sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss, , sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have accept-language set to sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss, , sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have content-language set to sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss, , sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have accept set to , sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have accept-language set to , sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have content-language set to , sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have content-type set to text/plain;ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss, text/plain": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have accept/\" as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have accept/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678 as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have accept-language/\u0001 as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have accept-language/@ as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have authorization/basics as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have content-language/\u0001 as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have content-language/@ as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have content-type/text/html as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have content-type/text/plain; long=0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901 as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have range/bytes 0- as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have test/hi as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have dpr/2 as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have rtt/1.0 as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have downlink/-1.0 as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have ect/6g as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have save-data/on as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have viewport-width/100 as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have width/100 as header": { "status": "FAIL" }, "\"no-cors\" Headers object cannot have unknown/doesitmatter as header": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/headers-normalize.any.js.json ================================================ { "Create headers with not normalized values": { "status": "PASS" }, "Check append method with not normalized values": { "status": "PASS" }, "Check set method with not normalized values": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/headers-record.any.js.json ================================================ { "Passing nothing to Headers constructor": { "status": "PASS" }, "Passing undefined to Headers constructor": { "status": "PASS" }, "Passing null to Headers constructor": { "status": "PASS" }, "Basic operation with one property": { "status": "PASS" }, "Basic operation with one property and a proto": { "status": "PASS" }, "Correct operation ordering with two properties": { "status": "PASS" }, "Correct operation ordering with two properties one of which has an invalid name": { "status": "PASS" }, "Correct operation ordering with two properties one of which has an invalid value": { "status": "PASS" }, "Correct operation ordering with non-enumerable properties": { "status": "PASS" }, "Correct operation ordering with undefined descriptors": { "status": "PASS" }, "Correct operation ordering with repeated keys": { "status": "PASS" }, "Basic operation with Symbol keys": { "status": "PASS" }, "Operation with non-enumerable Symbol keys": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/headers/headers-structure.any.js.json ================================================ { "Headers has append method": { "status": "PASS" }, "Headers has delete method": { "status": "PASS" }, "Headers has get method": { "status": "PASS" }, "Headers has has method": { "status": "PASS" }, "Headers has set method": { "status": "PASS" }, "Headers has entries method": { "status": "PASS" }, "Headers has keys method": { "status": "PASS" }, "Headers has values method": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-back-to-original-origin.any.js.json ================================================ { "original => remote => original with mode: \"no-cors\"": { "status": "FAIL" }, "original => remote => original with mode: \"cors\"": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-count.any.js.json ================================================ { "Redirect 301 20 times": { "status": "FAIL" }, "Redirect 301 21 times": { "status": "FAIL" }, "Redirect 302 20 times": { "status": "FAIL" }, "Redirect 302 21 times": { "status": "FAIL" }, "Redirect 303 20 times": { "status": "FAIL" }, "Redirect 303 21 times": { "status": "FAIL" }, "Redirect 307 20 times": { "status": "FAIL" }, "Redirect 307 21 times": { "status": "FAIL" }, "Redirect 308 20 times": { "status": "FAIL" }, "Redirect 308 21 times": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-empty-location.any.js.json ================================================ { "redirect response with empty Location, follow mode": { "status": "FAIL" }, "redirect response with empty Location, manual mode": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-keepalive.any.js.json ================================================ { "[keepalive][new window][unload] same-origin redirect; setting up": { "status": "FAIL" }, "[keepalive][new window][unload] same-origin redirect + preflight; setting up": { "status": "FAIL" }, "[keepalive][new window][unload] cross-origin redirect; setting up": { "status": "FAIL" }, "[keepalive][new window][unload] cross-origin redirect + preflight; setting up": { "status": "FAIL" }, "[keepalive][new window][unload] redirect to file URL; setting up": { "status": "FAIL" }, "[keepalive][new window][unload] redirect to data URL; setting up": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-keepalive.https.any.js.json ================================================ { "[keepalive][iframe][load] mixed content redirect; setting up": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-location-escape.tentative.any.js.json ================================================ { "Redirect to escaped UTF-8": { "status": "FAIL" }, "Redirect to unescaped UTF-8": { "status": "FAIL" }, "Redirect to escaped and unescaped UTF-8": { "status": "FAIL" }, "Escaping produces double-percent": { "status": "FAIL" }, "Redirect to invalid UTF-8": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-location.any.js.json ================================================ { "Redirect 301 in \"follow\" mode without location": { "status": "PASS" }, "Redirect 301 in \"manual\" mode without location": { "status": "FAIL" }, "Redirect 301 in \"follow\" mode with valid location": { "status": "FAIL" }, "Redirect 301 in \"manual\" mode with valid location": { "status": "FAIL" }, "Redirect 301 in \"error\" mode with valid location": { "status": "FAIL" }, "Redirect 301 in \"follow\" mode with invalid location": { "status": "FAIL" }, "Redirect 301 in \"manual\" mode with invalid location": { "status": "FAIL" }, "Redirect 301 in \"error\" mode with invalid location": { "status": "FAIL" }, "Redirect 301 in \"follow\" mode with data location": { "status": "FAIL" }, "Redirect 301 in \"manual\" mode with data location": { "status": "FAIL" }, "Redirect 301 in \"error\" mode with data location": { "status": "FAIL" }, "Redirect 302 in \"follow\" mode without location": { "status": "PASS" }, "Redirect 302 in \"manual\" mode without location": { "status": "FAIL" }, "Redirect 302 in \"follow\" mode with valid location": { "status": "FAIL" }, "Redirect 302 in \"manual\" mode with valid location": { "status": "FAIL" }, "Redirect 302 in \"error\" mode with valid location": { "status": "FAIL" }, "Redirect 302 in \"follow\" mode with invalid location": { "status": "FAIL" }, "Redirect 302 in \"manual\" mode with invalid location": { "status": "FAIL" }, "Redirect 302 in \"error\" mode with invalid location": { "status": "FAIL" }, "Redirect 302 in \"follow\" mode with data location": { "status": "FAIL" }, "Redirect 302 in \"manual\" mode with data location": { "status": "FAIL" }, "Redirect 302 in \"error\" mode with data location": { "status": "FAIL" }, "Redirect 303 in \"follow\" mode without location": { "status": "PASS" }, "Redirect 303 in \"manual\" mode without location": { "status": "FAIL" }, "Redirect 303 in \"follow\" mode with valid location": { "status": "FAIL" }, "Redirect 303 in \"manual\" mode with valid location": { "status": "FAIL" }, "Redirect 303 in \"error\" mode with valid location": { "status": "FAIL" }, "Redirect 303 in \"follow\" mode with invalid location": { "status": "FAIL" }, "Redirect 303 in \"manual\" mode with invalid location": { "status": "FAIL" }, "Redirect 303 in \"error\" mode with invalid location": { "status": "FAIL" }, "Redirect 303 in \"follow\" mode with data location": { "status": "FAIL" }, "Redirect 303 in \"manual\" mode with data location": { "status": "FAIL" }, "Redirect 303 in \"error\" mode with data location": { "status": "FAIL" }, "Redirect 307 in \"follow\" mode without location": { "status": "PASS" }, "Redirect 307 in \"manual\" mode without location": { "status": "FAIL" }, "Redirect 307 in \"follow\" mode with valid location": { "status": "FAIL" }, "Redirect 307 in \"manual\" mode with valid location": { "status": "FAIL" }, "Redirect 307 in \"error\" mode with valid location": { "status": "FAIL" }, "Redirect 307 in \"follow\" mode with invalid location": { "status": "FAIL" }, "Redirect 307 in \"manual\" mode with invalid location": { "status": "FAIL" }, "Redirect 307 in \"error\" mode with invalid location": { "status": "FAIL" }, "Redirect 307 in \"follow\" mode with data location": { "status": "FAIL" }, "Redirect 307 in \"manual\" mode with data location": { "status": "FAIL" }, "Redirect 307 in \"error\" mode with data location": { "status": "FAIL" }, "Redirect 308 in \"follow\" mode without location": { "status": "PASS" }, "Redirect 308 in \"manual\" mode without location": { "status": "FAIL" }, "Redirect 308 in \"follow\" mode with valid location": { "status": "FAIL" }, "Redirect 308 in \"manual\" mode with valid location": { "status": "FAIL" }, "Redirect 308 in \"error\" mode with valid location": { "status": "FAIL" }, "Redirect 308 in \"follow\" mode with invalid location": { "status": "FAIL" }, "Redirect 308 in \"manual\" mode with invalid location": { "status": "FAIL" }, "Redirect 308 in \"error\" mode with invalid location": { "status": "FAIL" }, "Redirect 308 in \"follow\" mode with data location": { "status": "FAIL" }, "Redirect 308 in \"manual\" mode with data location": { "status": "FAIL" }, "Redirect 308 in \"error\" mode with data location": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-method.any.js.json ================================================ { "Response.redirected should be false on not-redirected responses": { "status": "PASS" }, "Redirect 301 with GET": { "status": "FAIL" }, "Redirect 301 with POST": { "status": "FAIL" }, "Redirect 301 with HEAD": { "status": "FAIL" }, "Redirect 302 with GET": { "status": "FAIL" }, "Redirect 302 with POST": { "status": "FAIL" }, "Redirect 302 with HEAD": { "status": "FAIL" }, "Redirect 303 with GET": { "status": "FAIL" }, "Redirect 303 with POST": { "status": "FAIL" }, "Redirect 303 with HEAD": { "status": "FAIL" }, "Redirect 303 with TESTING": { "status": "FAIL" }, "Redirect 307 with GET": { "status": "FAIL" }, "Redirect 307 with POST (string body)": { "status": "FAIL" }, "Redirect 307 with POST (blob body)": { "status": "FAIL" }, "Redirect 307 with HEAD": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-mode.any.js.json ================================================ { "same-origin redirect 301 in error redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 301 in error redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 301 in manual redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 301 in manual redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 301 in follow redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 301 in follow redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 302 in error redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 302 in error redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 302 in manual redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 302 in manual redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 302 in follow redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 302 in follow redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 303 in error redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 303 in error redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 303 in manual redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 303 in manual redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 303 in follow redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 303 in follow redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 307 in error redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 307 in error redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 307 in manual redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 307 in manual redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 307 in follow redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 307 in follow redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 308 in error redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 308 in error redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 308 in manual redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 308 in manual redirect and no-cors mode": { "status": "FAIL" }, "same-origin redirect 308 in follow redirect and cors mode": { "status": "FAIL" }, "same-origin redirect 308 in follow redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 301 in error redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 301 in error redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 301 in manual redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 301 in manual redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 301 in follow redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 301 in follow redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 302 in error redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 302 in error redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 302 in manual redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 302 in manual redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 302 in follow redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 302 in follow redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 303 in error redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 303 in error redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 303 in manual redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 303 in manual redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 303 in follow redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 303 in follow redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 307 in error redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 307 in error redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 307 in manual redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 307 in manual redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 307 in follow redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 307 in follow redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 308 in error redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 308 in error redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 308 in manual redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 308 in manual redirect and no-cors mode": { "status": "FAIL" }, "cross-origin redirect 308 in follow redirect and cors mode": { "status": "FAIL" }, "cross-origin redirect 308 in follow redirect and no-cors mode": { "status": "FAIL" }, "manual redirect with a CORS error should be rejected": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-origin.any.js.json ================================================ { "[GET] Redirect 301 Same origin to same origin": { "status": "FAIL" }, "[GET] Redirect 301 Same origin to other origin": { "status": "FAIL" }, "[GET] Redirect 301 Other origin to other origin": { "status": "FAIL" }, "[GET] Redirect 301 Other origin to same origin": { "status": "FAIL" }, "[POST] Redirect 301 Same origin to same origin": { "status": "FAIL" }, "[POST] Redirect 301 Same origin to other origin": { "status": "FAIL" }, "[POST] Redirect 301 Other origin to other origin": { "status": "FAIL" }, "[POST] Redirect 301 Other origin to same origin": { "status": "FAIL" }, "[GET] Redirect 302 Same origin to same origin": { "status": "FAIL" }, "[GET] Redirect 302 Same origin to other origin": { "status": "FAIL" }, "[GET] Redirect 302 Other origin to other origin": { "status": "FAIL" }, "[GET] Redirect 302 Other origin to same origin": { "status": "FAIL" }, "[POST] Redirect 302 Same origin to same origin": { "status": "FAIL" }, "[POST] Redirect 302 Same origin to other origin": { "status": "FAIL" }, "[POST] Redirect 302 Other origin to other origin": { "status": "FAIL" }, "[POST] Redirect 302 Other origin to same origin": { "status": "FAIL" }, "[GET] Redirect 303 Same origin to same origin": { "status": "FAIL" }, "[GET] Redirect 303 Same origin to other origin": { "status": "FAIL" }, "[GET] Redirect 303 Other origin to other origin": { "status": "FAIL" }, "[GET] Redirect 303 Other origin to same origin": { "status": "FAIL" }, "[POST] Redirect 303 Same origin to same origin": { "status": "FAIL" }, "[POST] Redirect 303 Same origin to other origin": { "status": "FAIL" }, "[POST] Redirect 303 Other origin to other origin": { "status": "FAIL" }, "[POST] Redirect 303 Other origin to same origin": { "status": "FAIL" }, "[GET] Redirect 307 Same origin to same origin": { "status": "FAIL" }, "[GET] Redirect 307 Same origin to other origin": { "status": "FAIL" }, "[GET] Redirect 307 Other origin to other origin": { "status": "FAIL" }, "[GET] Redirect 307 Other origin to same origin": { "status": "FAIL" }, "[POST] Redirect 307 Same origin to same origin": { "status": "FAIL" }, "[POST] Redirect 307 Same origin to other origin": { "status": "FAIL" }, "[POST] Redirect 307 Other origin to other origin": { "status": "FAIL" }, "[POST] Redirect 307 Other origin to same origin": { "status": "FAIL" }, "[GET] Redirect 308 Same origin to same origin": { "status": "FAIL" }, "[GET] Redirect 308 Same origin to other origin": { "status": "FAIL" }, "[GET] Redirect 308 Other origin to other origin": { "status": "FAIL" }, "[GET] Redirect 308 Other origin to same origin": { "status": "FAIL" }, "[POST] Redirect 308 Same origin to same origin": { "status": "FAIL" }, "[POST] Redirect 308 Same origin to other origin": { "status": "FAIL" }, "[POST] Redirect 308 Other origin to other origin": { "status": "FAIL" }, "[POST] Redirect 308 Other origin to same origin": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-referrer-override.any.js.json ================================================ { "Same origin redirection, no-referrer init, no-referrer redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer init, no-referrer redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer init, origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer init, origin redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer init, same-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer init, same-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer init, strict-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer init, strict-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer init, unsafe-url redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer init, unsafe-url redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer-when-downgrade init, no-referrer redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer-when-downgrade init, no-referrer redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer-when-downgrade init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer-when-downgrade init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer-when-downgrade init, origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer-when-downgrade init, origin redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer-when-downgrade init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer-when-downgrade init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer-when-downgrade init, same-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer-when-downgrade init, same-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer-when-downgrade init, strict-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer-when-downgrade init, strict-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer-when-downgrade init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer-when-downgrade init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, no-referrer-when-downgrade init, unsafe-url redirect header ": { "status": "FAIL" }, "Cross origin redirection, no-referrer-when-downgrade init, unsafe-url redirect header ": { "status": "FAIL" }, "Same origin redirection, origin init, no-referrer redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin init, no-referrer redirect header ": { "status": "FAIL" }, "Same origin redirection, origin init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Same origin redirection, origin init, origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin init, origin redirect header ": { "status": "FAIL" }, "Same origin redirection, origin init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, origin init, same-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin init, same-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, origin init, strict-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin init, strict-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, origin init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, origin init, unsafe-url redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin init, unsafe-url redirect header ": { "status": "FAIL" }, "Same origin redirection, origin-when-cross-origin init, no-referrer redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin-when-cross-origin init, no-referrer redirect header ": { "status": "FAIL" }, "Same origin redirection, origin-when-cross-origin init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin-when-cross-origin init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Same origin redirection, origin-when-cross-origin init, origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin-when-cross-origin init, origin redirect header ": { "status": "FAIL" }, "Same origin redirection, origin-when-cross-origin init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin-when-cross-origin init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, origin-when-cross-origin init, same-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin-when-cross-origin init, same-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, origin-when-cross-origin init, strict-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin-when-cross-origin init, strict-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, origin-when-cross-origin init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin-when-cross-origin init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, origin-when-cross-origin init, unsafe-url redirect header ": { "status": "FAIL" }, "Cross origin redirection, origin-when-cross-origin init, unsafe-url redirect header ": { "status": "FAIL" }, "Same origin redirection, same-origin init, no-referrer redirect header ": { "status": "FAIL" }, "Cross origin redirection, same-origin init, no-referrer redirect header ": { "status": "FAIL" }, "Same origin redirection, same-origin init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Cross origin redirection, same-origin init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Same origin redirection, same-origin init, origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, same-origin init, origin redirect header ": { "status": "FAIL" }, "Same origin redirection, same-origin init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, same-origin init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, same-origin init, same-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, same-origin init, same-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, same-origin init, strict-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, same-origin init, strict-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, same-origin init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, same-origin init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, same-origin init, unsafe-url redirect header ": { "status": "FAIL" }, "Cross origin redirection, same-origin init, unsafe-url redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin init, no-referrer redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin init, no-referrer redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin init, origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin init, origin redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin init, same-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin init, same-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin init, strict-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin init, strict-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin init, unsafe-url redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin init, unsafe-url redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin-when-cross-origin init, no-referrer redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin-when-cross-origin init, no-referrer redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin-when-cross-origin init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin-when-cross-origin init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin-when-cross-origin init, origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin-when-cross-origin init, origin redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin-when-cross-origin init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin-when-cross-origin init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin-when-cross-origin init, same-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin-when-cross-origin init, same-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin-when-cross-origin init, strict-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin-when-cross-origin init, strict-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin-when-cross-origin init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin-when-cross-origin init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, strict-origin-when-cross-origin init, unsafe-url redirect header ": { "status": "FAIL" }, "Cross origin redirection, strict-origin-when-cross-origin init, unsafe-url redirect header ": { "status": "FAIL" }, "Same origin redirection, unsafe-url init, no-referrer redirect header ": { "status": "FAIL" }, "Cross origin redirection, unsafe-url init, no-referrer redirect header ": { "status": "FAIL" }, "Same origin redirection, unsafe-url init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Cross origin redirection, unsafe-url init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Same origin redirection, unsafe-url init, origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, unsafe-url init, origin redirect header ": { "status": "FAIL" }, "Same origin redirection, unsafe-url init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, unsafe-url init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, unsafe-url init, same-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, unsafe-url init, same-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, unsafe-url init, strict-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, unsafe-url init, strict-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, unsafe-url init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, unsafe-url init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, unsafe-url init, unsafe-url redirect header ": { "status": "FAIL" }, "Cross origin redirection, unsafe-url init, unsafe-url redirect header ": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-referrer.any.js.json ================================================ { "Same origin redirection, empty init, unsafe-url redirect header ": { "status": "FAIL" }, "Same origin redirection, empty init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Same origin redirection, empty init, same-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, empty init, origin redirect header ": { "status": "FAIL" }, "Same origin redirection, empty init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, empty init, no-referrer redirect header ": { "status": "FAIL" }, "Same origin redirection, empty init, strict-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, empty init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Same origin redirection, empty redirect header, unsafe-url init ": { "status": "FAIL" }, "Same origin redirection, empty redirect header, no-referrer-when-downgrade init ": { "status": "FAIL" }, "Same origin redirection, empty redirect header, same-origin init ": { "status": "FAIL" }, "Same origin redirection, empty redirect header, origin init ": { "status": "FAIL" }, "Same origin redirection, empty redirect header, origin-when-cross-origin init ": { "status": "FAIL" }, "Same origin redirection, empty redirect header, no-referrer init ": { "status": "FAIL" }, "Same origin redirection, empty redirect header, strict-origin init ": { "status": "FAIL" }, "Same origin redirection, empty redirect header, strict-origin-when-cross-origin init ": { "status": "FAIL" }, "Cross origin redirection, empty init, unsafe-url redirect header ": { "status": "FAIL" }, "Cross origin redirection, empty init, no-referrer-when-downgrade redirect header ": { "status": "FAIL" }, "Cross origin redirection, empty init, same-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, empty init, origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, empty init, origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, empty init, no-referrer redirect header ": { "status": "FAIL" }, "Cross origin redirection, empty init, strict-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, empty init, strict-origin-when-cross-origin redirect header ": { "status": "FAIL" }, "Cross origin redirection, empty redirect header, unsafe-url init ": { "status": "FAIL" }, "Cross origin redirection, empty redirect header, no-referrer-when-downgrade init ": { "status": "FAIL" }, "Cross origin redirection, empty redirect header, same-origin init ": { "status": "FAIL" }, "Cross origin redirection, empty redirect header, origin init ": { "status": "FAIL" }, "Cross origin redirection, empty redirect header, origin-when-cross-origin init ": { "status": "FAIL" }, "Cross origin redirection, empty redirect header, no-referrer init ": { "status": "FAIL" }, "Cross origin redirection, empty redirect header, strict-origin init ": { "status": "FAIL" }, "Cross origin redirection, empty redirect header, strict-origin-when-cross-origin init ": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-schemes.any.js.json ================================================ { "redirect-schemes": { "status": "FAIL" }, "redirect-schemes 1": { "status": "FAIL" }, "redirect-schemes 2": { "status": "FAIL" }, "redirect-schemes 3": { "status": "FAIL" }, "redirect-schemes 4": { "status": "FAIL" }, "redirect-schemes 5": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-to-dataurl.any.js.json ================================================ { "Testing data URL loading after same-origin redirection (cors mode)": { "status": "FAIL" }, "Testing data URL loading after same-origin redirection (no-cors mode)": { "status": "FAIL" }, "Testing data URL loading after same-origin redirection (same-origin mode)": { "status": "FAIL" }, "Testing data URL loading after cross-origin redirection (cors mode)": { "status": "FAIL" }, "Testing data URL loading after cross-origin redirection (no-cors mode)": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/redirect/redirect-upload.h2.any.js.json ================================================ { "Fetch upload streaming should be accepted on 303": { "status": "FAIL" }, "Fetch upload streaming should fail on 301": { "status": "FAIL" }, "Fetch upload streaming should fail on 302": { "status": "FAIL" }, "Fetch upload streaming should fail on 307": { "status": "FAIL" }, "Fetch upload streaming should fail on 308": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/forbidden-method.any.js.json ================================================ { "Request() with a forbidden method CONNECT must throw.": { "status": "FAIL" }, "Request() with a forbidden method TRACE must throw.": { "status": "FAIL" }, "Request() with a forbidden method TRACK must throw.": { "status": "FAIL" }, "Request() with a forbidden method connect must throw.": { "status": "FAIL" }, "Request() with a forbidden method trace must throw.": { "status": "FAIL" }, "Request() with a forbidden method track must throw.": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-bad-port.any.js.json ================================================ { "Request on bad port 1 should throw TypeError.": { "status": "PASS" }, "Request on bad port 7 should throw TypeError.": { "status": "PASS" }, "Request on bad port 9 should throw TypeError.": { "status": "PASS" }, "Request on bad port 11 should throw TypeError.": { "status": "PASS" }, "Request on bad port 13 should throw TypeError.": { "status": "PASS" }, "Request on bad port 15 should throw TypeError.": { "status": "PASS" }, "Request on bad port 17 should throw TypeError.": { "status": "PASS" }, "Request on bad port 19 should throw TypeError.": { "status": "PASS" }, "Request on bad port 20 should throw TypeError.": { "status": "PASS" }, "Request on bad port 21 should throw TypeError.": { "status": "PASS" }, "Request on bad port 22 should throw TypeError.": { "status": "PASS" }, "Request on bad port 23 should throw TypeError.": { "status": "PASS" }, "Request on bad port 25 should throw TypeError.": { "status": "PASS" }, "Request on bad port 37 should throw TypeError.": { "status": "PASS" }, "Request on bad port 42 should throw TypeError.": { "status": "PASS" }, "Request on bad port 43 should throw TypeError.": { "status": "PASS" }, "Request on bad port 53 should throw TypeError.": { "status": "PASS" }, "Request on bad port 69 should throw TypeError.": { "status": "PASS" }, "Request on bad port 77 should throw TypeError.": { "status": "PASS" }, "Request on bad port 79 should throw TypeError.": { "status": "PASS" }, "Request on bad port 87 should throw TypeError.": { "status": "PASS" }, "Request on bad port 95 should throw TypeError.": { "status": "PASS" }, "Request on bad port 101 should throw TypeError.": { "status": "PASS" }, "Request on bad port 102 should throw TypeError.": { "status": "PASS" }, "Request on bad port 103 should throw TypeError.": { "status": "PASS" }, "Request on bad port 104 should throw TypeError.": { "status": "PASS" }, "Request on bad port 109 should throw TypeError.": { "status": "PASS" }, "Request on bad port 110 should throw TypeError.": { "status": "PASS" }, "Request on bad port 111 should throw TypeError.": { "status": "PASS" }, "Request on bad port 113 should throw TypeError.": { "status": "PASS" }, "Request on bad port 115 should throw TypeError.": { "status": "PASS" }, "Request on bad port 117 should throw TypeError.": { "status": "PASS" }, "Request on bad port 119 should throw TypeError.": { "status": "PASS" }, "Request on bad port 123 should throw TypeError.": { "status": "PASS" }, "Request on bad port 135 should throw TypeError.": { "status": "PASS" }, "Request on bad port 137 should throw TypeError.": { "status": "PASS" }, "Request on bad port 139 should throw TypeError.": { "status": "PASS" }, "Request on bad port 143 should throw TypeError.": { "status": "PASS" }, "Request on bad port 161 should throw TypeError.": { "status": "PASS" }, "Request on bad port 179 should throw TypeError.": { "status": "PASS" }, "Request on bad port 389 should throw TypeError.": { "status": "PASS" }, "Request on bad port 427 should throw TypeError.": { "status": "PASS" }, "Request on bad port 465 should throw TypeError.": { "status": "PASS" }, "Request on bad port 512 should throw TypeError.": { "status": "PASS" }, "Request on bad port 513 should throw TypeError.": { "status": "PASS" }, "Request on bad port 514 should throw TypeError.": { "status": "PASS" }, "Request on bad port 515 should throw TypeError.": { "status": "PASS" }, "Request on bad port 526 should throw TypeError.": { "status": "PASS" }, "Request on bad port 530 should throw TypeError.": { "status": "PASS" }, "Request on bad port 531 should throw TypeError.": { "status": "PASS" }, "Request on bad port 532 should throw TypeError.": { "status": "PASS" }, "Request on bad port 540 should throw TypeError.": { "status": "PASS" }, "Request on bad port 548 should throw TypeError.": { "status": "PASS" }, "Request on bad port 554 should throw TypeError.": { "status": "PASS" }, "Request on bad port 556 should throw TypeError.": { "status": "PASS" }, "Request on bad port 563 should throw TypeError.": { "status": "PASS" }, "Request on bad port 587 should throw TypeError.": { "status": "PASS" }, "Request on bad port 601 should throw TypeError.": { "status": "PASS" }, "Request on bad port 636 should throw TypeError.": { "status": "PASS" }, "Request on bad port 989 should throw TypeError.": { "status": "PASS" }, "Request on bad port 990 should throw TypeError.": { "status": "PASS" }, "Request on bad port 993 should throw TypeError.": { "status": "PASS" }, "Request on bad port 995 should throw TypeError.": { "status": "PASS" }, "Request on bad port 1719 should throw TypeError.": { "status": "PASS" }, "Request on bad port 1720 should throw TypeError.": { "status": "PASS" }, "Request on bad port 1723 should throw TypeError.": { "status": "PASS" }, "Request on bad port 2049 should throw TypeError.": { "status": "PASS" }, "Request on bad port 3659 should throw TypeError.": { "status": "PASS" }, "Request on bad port 4045 should throw TypeError.": { "status": "PASS" }, "Request on bad port 4190 should throw TypeError.": { "status": "PASS" }, "Request on bad port 5060 should throw TypeError.": { "status": "PASS" }, "Request on bad port 5061 should throw TypeError.": { "status": "PASS" }, "Request on bad port 6000 should throw TypeError.": { "status": "PASS" }, "Request on bad port 6566 should throw TypeError.": { "status": "PASS" }, "Request on bad port 6665 should throw TypeError.": { "status": "PASS" }, "Request on bad port 6666 should throw TypeError.": { "status": "PASS" }, "Request on bad port 6667 should throw TypeError.": { "status": "PASS" }, "Request on bad port 6668 should throw TypeError.": { "status": "PASS" }, "Request on bad port 6669 should throw TypeError.": { "status": "PASS" }, "Request on bad port 6679 should throw TypeError.": { "status": "PASS" }, "Request on bad port 6697 should throw TypeError.": { "status": "PASS" }, "Request on bad port 10080 should throw TypeError.": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-cache-default-conditional.any.js.json ================================================ { "RequestCache \"default\" mode with an If-Modified-Since header (following a request without additional headers) is treated similarly to \"no-store\" with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Modified-Since header (following a request without additional headers) is treated similarly to \"no-store\" with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Modified-Since header (following a request without additional headers) is treated similarly to \"no-store\" with Etag and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Modified-Since header (following a request without additional headers) is treated similarly to \"no-store\" with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Modified-Since header is treated similarly to \"no-store\" with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Modified-Since header is treated similarly to \"no-store\" with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Modified-Since header is treated similarly to \"no-store\" with Etag and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Modified-Since header is treated similarly to \"no-store\" with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-None-Match header (following a request without additional headers) is treated similarly to \"no-store\" with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-None-Match header (following a request without additional headers) is treated similarly to \"no-store\" with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-None-Match header (following a request without additional headers) is treated similarly to \"no-store\" with Etag and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-None-Match header (following a request without additional headers) is treated similarly to \"no-store\" with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-None-Match header is treated similarly to \"no-store\" with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-None-Match header is treated similarly to \"no-store\" with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-None-Match header is treated similarly to \"no-store\" with Etag and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-None-Match header is treated similarly to \"no-store\" with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Unmodified-Since header (following a request without additional headers) is treated similarly to \"no-store\" with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Unmodified-Since header (following a request without additional headers) is treated similarly to \"no-store\" with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Unmodified-Since header (following a request without additional headers) is treated similarly to \"no-store\" with Etag and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Unmodified-Since header (following a request without additional headers) is treated similarly to \"no-store\" with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Unmodified-Since header is treated similarly to \"no-store\" with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Unmodified-Since header is treated similarly to \"no-store\" with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Unmodified-Since header is treated similarly to \"no-store\" with Etag and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Unmodified-Since header is treated similarly to \"no-store\" with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Match header (following a request without additional headers) is treated similarly to \"no-store\" with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Match header (following a request without additional headers) is treated similarly to \"no-store\" with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Match header (following a request without additional headers) is treated similarly to \"no-store\" with Etag and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Match header (following a request without additional headers) is treated similarly to \"no-store\" with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Match header is treated similarly to \"no-store\" with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Match header is treated similarly to \"no-store\" with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Match header is treated similarly to \"no-store\" with Etag and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Match header is treated similarly to \"no-store\" with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Range header (following a request without additional headers) is treated similarly to \"no-store\" with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Range header (following a request without additional headers) is treated similarly to \"no-store\" with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Range header (following a request without additional headers) is treated similarly to \"no-store\" with Etag and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Range header (following a request without additional headers) is treated similarly to \"no-store\" with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Range header is treated similarly to \"no-store\" with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Range header is treated similarly to \"no-store\" with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Range header is treated similarly to \"no-store\" with Etag and fresh response": { "status": "PASS" }, "RequestCache \"default\" mode with an If-Range header is treated similarly to \"no-store\" with Last-Modified and fresh response": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-cache-default.any.js.json ================================================ { "RequestCache \"default\" mode checks the cache for previously cached content and goes to the network for stale responses with Etag and stale response": { "status": "PASS" }, "RequestCache \"default\" mode checks the cache for previously cached content and goes to the network for stale responses with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"default\" mode checks the cache for previously cached content and avoids going to the network if a fresh response exists with Etag and fresh response": { "status": "FAIL" }, "RequestCache \"default\" mode checks the cache for previously cached content and avoids going to the network if a fresh response exists with Last-Modified and fresh response": { "status": "FAIL" }, "Responses with the \"Cache-Control: no-store\" header are not stored in the cache with Etag and stale response": { "status": "PASS" }, "Responses with the \"Cache-Control: no-store\" header are not stored in the cache with Last-Modified and stale response": { "status": "PASS" }, "Responses with the \"Cache-Control: no-store\" header are not stored in the cache with Etag and fresh response": { "status": "PASS" }, "Responses with the \"Cache-Control: no-store\" header are not stored in the cache with Last-Modified and fresh response": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-cache-force-cache.any.js.json ================================================ { "RequestCache \"force-cache\" mode checks the cache for previously cached content and avoid revalidation for stale responses with Etag and stale response": { "status": "FAIL" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and avoid revalidation for stale responses with Last-Modified and stale response": { "status": "FAIL" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and avoid revalidation for fresh responses with Etag and fresh response": { "status": "FAIL" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and avoid revalidation for fresh responses with Last-Modified and fresh response": { "status": "FAIL" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and goes to the network if a cached response is not found with Etag and stale response": { "status": "PASS" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and goes to the network if a cached response is not found with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and goes to the network if a cached response is not found with Etag and fresh response": { "status": "PASS" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and goes to the network if a cached response is not found with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and goes to the network if a cached response would vary with Etag and stale response": { "status": "PASS" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and goes to the network if a cached response would vary with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and goes to the network if a cached response would vary with Etag and fresh response": { "status": "PASS" }, "RequestCache \"force-cache\" mode checks the cache for previously cached content and goes to the network if a cached response would vary with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"force-cache\" stores the response in the cache if it goes to the network with Etag and stale response": { "status": "PASS" }, "RequestCache \"force-cache\" stores the response in the cache if it goes to the network with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"force-cache\" stores the response in the cache if it goes to the network with Etag and fresh response": { "status": "FAIL" }, "RequestCache \"force-cache\" stores the response in the cache if it goes to the network with Last-Modified and fresh response": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-cache-no-cache.any.js.json ================================================ { "RequestCache \"no-cache\" mode revalidates stale responses found in the cache with Etag and stale response": { "status": "PASS" }, "RequestCache \"no-cache\" mode revalidates stale responses found in the cache with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"no-cache\" mode revalidates fresh responses found in the cache with Etag and fresh response": { "status": "PASS" }, "RequestCache \"no-cache\" mode revalidates fresh responses found in the cache with Last-Modified and fresh response": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-cache-no-store.any.js.json ================================================ { "RequestCache \"no-store\" mode does not check the cache for previously cached content and goes to the network regardless with Etag and stale response": { "status": "PASS" }, "RequestCache \"no-store\" mode does not check the cache for previously cached content and goes to the network regardless with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"no-store\" mode does not check the cache for previously cached content and goes to the network regardless with Etag and fresh response": { "status": "PASS" }, "RequestCache \"no-store\" mode does not check the cache for previously cached content and goes to the network regardless with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"no-store\" mode does not store the response in the cache with Etag and stale response": { "status": "PASS" }, "RequestCache \"no-store\" mode does not store the response in the cache with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"no-store\" mode does not store the response in the cache with Etag and fresh response": { "status": "PASS" }, "RequestCache \"no-store\" mode does not store the response in the cache with Last-Modified and fresh response": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-cache-only-if-cached.any.js.json ================================================ { "RequestCache \"only-if-cached\" mode checks the cache for previously cached content and avoids revalidation for stale responses with Etag and stale response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" mode checks the cache for previously cached content and avoids revalidation for stale responses with Last-Modified and stale response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" mode checks the cache for previously cached content and avoids revalidation for fresh responses with Etag and fresh response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" mode checks the cache for previously cached content and avoids revalidation for fresh responses with Last-Modified and fresh response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" mode checks the cache for previously cached content and does not go to the network if a cached response is not found with Etag and fresh response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" mode checks the cache for previously cached content and does not go to the network if a cached response is not found with Last-Modified and fresh response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" (with \"same-origin\") uses cached same-origin redirects to same-origin content with Etag and fresh response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" (with \"same-origin\") uses cached same-origin redirects to same-origin content with Last-Modified and fresh response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" (with \"same-origin\") uses cached same-origin redirects to same-origin content with Etag and stale response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" (with \"same-origin\") uses cached same-origin redirects to same-origin content with Last-Modified and stale response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" (with \"same-origin\") does not follow redirects across origins and rejects with Etag and fresh response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" (with \"same-origin\") does not follow redirects across origins and rejects with Last-Modified and fresh response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" (with \"same-origin\") does not follow redirects across origins and rejects with Etag and stale response": { "status": "FAIL" }, "RequestCache \"only-if-cached\" (with \"same-origin\") does not follow redirects across origins and rejects with Last-Modified and stale response": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-cache-reload.any.js.json ================================================ { "RequestCache \"reload\" mode does not check the cache for previously cached content and goes to the network regardless with Etag and stale response": { "status": "PASS" }, "RequestCache \"reload\" mode does not check the cache for previously cached content and goes to the network regardless with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"reload\" mode does not check the cache for previously cached content and goes to the network regardless with Etag and fresh response": { "status": "PASS" }, "RequestCache \"reload\" mode does not check the cache for previously cached content and goes to the network regardless with Last-Modified and fresh response": { "status": "PASS" }, "RequestCache \"reload\" mode does store the response in the cache with Etag and stale response": { "status": "PASS" }, "RequestCache \"reload\" mode does store the response in the cache with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"reload\" mode does store the response in the cache with Etag and fresh response": { "status": "FAIL" }, "RequestCache \"reload\" mode does store the response in the cache with Last-Modified and fresh response": { "status": "FAIL" }, "RequestCache \"reload\" mode does store the response in the cache even if a previous response is already stored with Etag and stale response": { "status": "PASS" }, "RequestCache \"reload\" mode does store the response in the cache even if a previous response is already stored with Last-Modified and stale response": { "status": "PASS" }, "RequestCache \"reload\" mode does store the response in the cache even if a previous response is already stored with Etag and fresh response": { "status": "FAIL" }, "RequestCache \"reload\" mode does store the response in the cache even if a previous response is already stored with Last-Modified and fresh response": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-constructor-init-body-override.any.js.json ================================================ { "Check that the body of a new request can be overridden when created from an existing Request object": { "status": "PASS" }, "Check that the body of a new request can be duplicated from an existing Request object": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-consume-empty.any.js.json ================================================ { "Consume request's body as text": { "status": "PASS" }, "Consume request's body as blob": { "status": "PASS" }, "Consume request's body as arrayBuffer": { "status": "PASS" }, "Consume request's body as json (error case)": { "status": "PASS" }, "Consume request's body as formData with correct multipart type (error case)": { "status": "FAIL" }, "Consume request's body as formData with correct urlencoded type": { "status": "PASS" }, "Consume request's body as formData without correct type (error case)": { "status": "PASS" }, "Consume empty blob request body as arrayBuffer": { "status": "PASS" }, "Consume empty text request body as arrayBuffer": { "status": "PASS" }, "Consume empty blob request body as text": { "status": "PASS" }, "Consume empty text request body as text": { "status": "PASS" }, "Consume empty URLSearchParams request body as text": { "status": "PASS" }, "Consume empty FormData request body as text": { "status": "PASS" }, "Consume empty ArrayBuffer request body as text": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-consume.any.js.json ================================================ { "Consume String request's body as text": { "status": "PASS" }, "Consume String request's body as blob": { "status": "PASS" }, "Consume String request's body as arrayBuffer": { "status": "PASS" }, "Consume String request's body as bytes": { "status": "FAIL" }, "Consume String request's body as JSON": { "status": "PASS" }, "Consume ArrayBuffer request's body as text": { "status": "PASS" }, "Consume ArrayBuffer request's body as blob": { "status": "PASS" }, "Consume ArrayBuffer request's body as arrayBuffer": { "status": "PASS" }, "Consume ArrayBuffer request's body as bytes": { "status": "FAIL" }, "Consume ArrayBuffer request's body as JSON": { "status": "PASS" }, "Consume Uint8Array request's body as text": { "status": "PASS" }, "Consume Uint8Array request's body as blob": { "status": "PASS" }, "Consume Uint8Array request's body as arrayBuffer": { "status": "PASS" }, "Consume Uint8Array request's body as bytes": { "status": "FAIL" }, "Consume Uint8Array request's body as JSON": { "status": "PASS" }, "Consume Int8Array request's body as text": { "status": "PASS" }, "Consume Int8Array request's body as blob": { "status": "PASS" }, "Consume Int8Array request's body as arrayBuffer": { "status": "PASS" }, "Consume Int8Array request's body as bytes": { "status": "FAIL" }, "Consume Int8Array request's body as JSON": { "status": "PASS" }, "Consume Float32Array request's body as text": { "status": "PASS" }, "Consume Float32Array request's body as blob": { "status": "PASS" }, "Consume Float32Array request's body as arrayBuffer": { "status": "PASS" }, "Consume Float32Array request's body as bytes": { "status": "FAIL" }, "Consume Float32Array request's body as JSON": { "status": "PASS" }, "Consume DataView request's body as text": { "status": "PASS" }, "Consume DataView request's body as blob": { "status": "PASS" }, "Consume DataView request's body as arrayBuffer": { "status": "PASS" }, "Consume DataView request's body as bytes": { "status": "FAIL" }, "Consume DataView request's body as JSON": { "status": "PASS" }, "Consume FormData request's body as FormData": { "status": "PASS" }, "Consume blob response's body as blob": { "status": "PASS" }, "Consume blob response's body as text": { "status": "PASS" }, "Consume blob response's body as json": { "status": "PASS" }, "Consume blob response's body as arrayBuffer": { "status": "PASS" }, "Consume blob response's body as bytes": { "status": "FAIL" }, "Consume blob response's body as blob (empty blob as input)": { "status": "PASS" }, "Consume JSON from text: '\"null\"'": { "status": "PASS" }, "Consume JSON from text: '\"1\"'": { "status": "PASS" }, "Consume JSON from text: '\"true\"'": { "status": "PASS" }, "Consume JSON from text: '\"\\\"string\\\"\"'": { "status": "PASS" }, "Trying to consume bad JSON text as JSON: 'undefined'": { "status": "PASS" }, "Trying to consume bad JSON text as JSON: '{'": { "status": "PASS" }, "Trying to consume bad JSON text as JSON: 'a'": { "status": "PASS" }, "Trying to consume bad JSON text as JSON: '['": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-disturbed.any.js.json ================================================ { "Request's body: initial state": { "status": "FAIL" }, "Request without body cannot be disturbed": { "status": "PASS" }, "Check cloning a disturbed request": { "status": "FAIL" }, "Check creating a new request from a disturbed request": { "status": "FAIL" }, "Check creating a new request with a new body from a disturbed request": { "status": "FAIL" }, "Input request used for creating new request became disturbed": { "status": "FAIL" }, "Input request used for creating new request became disturbed even if body is not used": { "status": "FAIL" }, "Check consuming a disturbed request": { "status": "FAIL" }, "Request construction failure should not set \"bodyUsed\"": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-error.any.js.json ================================================ { "RequestInit's window is not null": { "status": "FAIL" }, "Input URL is not valid": { "status": "PASS" }, "Input URL has credentials": { "status": "FAIL" }, "RequestInit's mode is navigate": { "status": "FAIL" }, "RequestInit's referrer is invalid": { "status": "FAIL" }, "RequestInit's method is invalid": { "status": "FAIL" }, "RequestInit's method is forbidden": { "status": "FAIL" }, "RequestInit's mode is no-cors and method is not simple": { "status": "FAIL" }, "RequestInit's cache mode is only-if-cached and mode is not same-origin": { "status": "FAIL" }, "Request with cache mode: only-if-cached and fetch mode cors": { "status": "FAIL" }, "Request with cache mode: only-if-cached and fetch mode no-cors": { "status": "FAIL" }, "Bad referrerPolicy init parameter value": { "status": "FAIL" }, "Bad mode init parameter value": { "status": "FAIL" }, "Bad credentials init parameter value": { "status": "FAIL" }, "Bad cache init parameter value": { "status": "FAIL" }, "Bad redirect init parameter value": { "status": "FAIL" }, "request-error": { "status": "PASS" }, "Request should get its content-type from the init request": { "status": "PASS" }, "Request should not get its content-type from the init request if init headers are provided": { "status": "PASS" }, "Request should get its content-type from the body if none is provided": { "status": "PASS" }, "Request should get its content-type from init headers if one is provided": { "status": "PASS" }, "Request with cache mode: only-if-cached and fetch mode: same-origin": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-headers.any.js.json ================================================ { "Adding valid request header \"Content-Type: OK\"": { "status": "PASS" }, "Adding valid request header \"Potato: OK\"": { "status": "PASS" }, "Adding valid request header \"proxy: OK\"": { "status": "PASS" }, "Adding valid request header \"proxya: OK\"": { "status": "PASS" }, "Adding valid request header \"sec: OK\"": { "status": "PASS" }, "Adding valid request header \"secb: OK\"": { "status": "PASS" }, "Adding valid request header \"Set-Cookie2: OK\"": { "status": "PASS" }, "Adding valid request header \"User-Agent: OK\"": { "status": "PASS" }, "Adding invalid request header \"Accept-Charset: KO\"": { "status": "FAIL" }, "Adding invalid request header \"accept-charset: KO\"": { "status": "FAIL" }, "Adding invalid request header \"ACCEPT-ENCODING: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Accept-Encoding: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Access-Control-Request-Headers: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Access-Control-Request-Method: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Connection: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Content-Length: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Cookie: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Cookie2: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Date: KO\"": { "status": "FAIL" }, "Adding invalid request header \"DNT: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Expect: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Host: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Keep-Alive: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Origin: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Referer: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Set-Cookie: KO\"": { "status": "FAIL" }, "Adding invalid request header \"TE: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Trailer: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Transfer-Encoding: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Upgrade: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Via: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Proxy-: KO\"": { "status": "FAIL" }, "Adding invalid request header \"proxy-a: KO\"": { "status": "FAIL" }, "Adding invalid request header \"Sec-: KO\"": { "status": "FAIL" }, "Adding invalid request header \"sec-b: KO\"": { "status": "FAIL" }, "Adding valid no-cors request header \"Accept: OK\"": { "status": "PASS" }, "Adding valid no-cors request header \"Accept-Language: OK\"": { "status": "PASS" }, "Adding valid no-cors request header \"content-language: OK\"": { "status": "PASS" }, "Adding valid no-cors request header \"content-type: application/x-www-form-urlencoded\"": { "status": "PASS" }, "Adding valid no-cors request header \"content-type: application/x-www-form-urlencoded;charset=UTF-8\"": { "status": "PASS" }, "Adding valid no-cors request header \"content-type: multipart/form-data\"": { "status": "PASS" }, "Adding valid no-cors request header \"content-type: multipart/form-data;charset=UTF-8\"": { "status": "PASS" }, "Adding valid no-cors request header \"content-TYPE: text/plain\"": { "status": "PASS" }, "Adding valid no-cors request header \"CONTENT-type: text/plain;charset=UTF-8\"": { "status": "PASS" }, "Adding invalid no-cors request header \"Content-Type: KO\"": { "status": "FAIL" }, "Adding invalid no-cors request header \"Potato: KO\"": { "status": "FAIL" }, "Adding invalid no-cors request header \"proxy: KO\"": { "status": "FAIL" }, "Adding invalid no-cors request header \"proxya: KO\"": { "status": "FAIL" }, "Adding invalid no-cors request header \"sec: KO\"": { "status": "FAIL" }, "Adding invalid no-cors request header \"secb: KO\"": { "status": "FAIL" }, "Adding invalid no-cors request header \"Empty-Value: \"": { "status": "FAIL" }, "Check that request constructor is filtering headers provided as init parameter": { "status": "FAIL" }, "Check that no-cors request constructor is filtering headers provided as init parameter": { "status": "FAIL" }, "Check that no-cors request constructor is filtering headers provided as part of request parameter": { "status": "FAIL" }, "Request should get its content-type from the init request": { "status": "PASS" }, "Request should not get its content-type from the init request if init headers are provided": { "status": "PASS" }, "Request should get its content-type from the body if none is provided": { "status": "PASS" }, "Request should get its content-type from init headers if one is provided": { "status": "PASS" }, "Testing request header creations with various objects": { "status": "PASS" }, "Testing empty Request Content-Type header": { "status": "PASS" }, "Test that Request.headers has the [SameObject] extended attribute": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-init-002.any.js.json ================================================ { "Initialize Request with headers values": { "status": "PASS" }, "Initialize Request's body with \"undefined\", undefined": { "status": "PASS" }, "Initialize Request's body with \"null\", null": { "status": "PASS" }, "Initialize Request's body with \"[object Blob]\", application/octet-binary": { "status": "PASS" }, "Initialize Request's body with \"[object Object]\", multipart/form-data": { "status": "PASS" }, "Initialize Request's body with \"This is a USVString\", text/plain;charset=UTF-8": { "status": "PASS" }, "Initialize Request's body with \"hi!\", text/plain;charset=UTF-8": { "status": "PASS" }, "Initialize Request's body with \"name=value\", application/x-www-form-urlencoded;charset=UTF-8": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-init-contenttype.any.js.json ================================================ { "Default Content-Type for Request with empty body": { "status": "PASS" }, "Default Content-Type for Request with Blob body (no type set)": { "status": "PASS" }, "Default Content-Type for Request with Blob body (empty type)": { "status": "PASS" }, "Default Content-Type for Request with Blob body (set type)": { "status": "PASS" }, "Default Content-Type for Request with buffer source body": { "status": "PASS" }, "Default Content-Type for Request with FormData body": { "status": "PASS" }, "Default Content-Type for Request with URLSearchParams body": { "status": "PASS" }, "Default Content-Type for Request with string body": { "status": "PASS" }, "Default Content-Type for Request with ReadableStream body": { "status": "PASS" }, "Can override Content-Type for Request with empty body": { "status": "PASS" }, "Can override Content-Type for Request with Blob body (no type set)": { "status": "PASS" }, "Can override Content-Type for Request with Blob body (empty type)": { "status": "PASS" }, "Can override Content-Type for Request with Blob body (set type)": { "status": "PASS" }, "Can override Content-Type for Request with buffer source body": { "status": "PASS" }, "Can override Content-Type for Request with FormData body": { "status": "PASS" }, "Can override Content-Type for Request with URLSearchParams body": { "status": "PASS" }, "Can override Content-Type for Request with string body": { "status": "PASS" }, "Can override Content-Type for Request with ReadableStream body": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-init-priority.any.js.json ================================================ { "new Request() with a 'high' priority does not throw an error": { "status": "PASS" }, "new Request() with a 'low' priority does not throw an error": { "status": "PASS" }, "new Request() with a 'auto' priority does not throw an error": { "status": "PASS" }, "new Request() throws a TypeError if any of RequestInit's members' values are invalid": { "status": "FAIL" }, "fetch() with a 'high' priority completes successfully": { "status": "PASS" }, "fetch() with a 'low' priority completes successfully": { "status": "PASS" }, "fetch() with a 'auto' priority completes successfully": { "status": "PASS" }, "fetch() with an invalid priority returns a rejected promise with a TypeError": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-init-stream.any.js.json ================================================ { "Constructing a Request with a stream holds the original object.": { "status": "PASS" }, "Constructing a Request with a stream on which getReader() is called": { "status": "PASS" }, "Constructing a Request with a stream on which read() is called": { "status": "PASS" }, "Constructing a Request with a stream on which read() and releaseLock() are called": { "status": "PASS" }, "Constructing a Request with a Request on which body.getReader() is called": { "status": "FAIL" }, "Constructing a Request with a Request on which body.getReader().read() is called": { "status": "FAIL" }, "Constructing a Request with a Request on which read() and releaseLock() are called": { "status": "FAIL" }, "It is OK to omit .duplex when the body is null.": { "status": "PASS" }, "It is OK to omit .duplex when the body is a string.": { "status": "PASS" }, "It is OK to omit .duplex when the body is a Uint8Array.": { "status": "PASS" }, "It is OK to omit .duplex when the body is a Blob.": { "status": "PASS" }, "It is error to omit .duplex when the body is a ReadableStream.": { "status": "FAIL" }, "It is OK to set .duplex = 'half' when the body is null.": { "status": "PASS" }, "It is OK to set .duplex = 'half' when the body is a string.": { "status": "PASS" }, "It is OK to set .duplex = 'half' when the body is a Uint8Array.": { "status": "PASS" }, "It is OK to set .duplex = 'half' when the body is a Blob.": { "status": "PASS" }, "It is OK to set .duplex = 'half' when the body is a ReadableStream.": { "status": "PASS" }, "It is error to set .duplex = 'full' when the body is null.": { "status": "FAIL" }, "It is error to set .duplex = 'full' when the body is a string.": { "status": "FAIL" }, "It is error to set .duplex = 'full' when the body is a Uint8Array.": { "status": "FAIL" }, "It is error to set .duplex = 'full' when the body is a Blob.": { "status": "FAIL" }, "It is error to set .duplex = 'full' when the body is a ReadableStream.": { "status": "FAIL" }, "It is OK to omit duplex when init.body is not given and input.body is given.": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-keepalive.any.js.json ================================================ { "keepalive flag": { "status": "FAIL" }, "keepalive flag with stream body": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/request/request-structure.any.js.json ================================================ { "Request has clone method": { "status": "PASS" }, "Request has arrayBuffer method": { "status": "PASS" }, "Request has blob method": { "status": "PASS" }, "Request has formData method": { "status": "PASS" }, "Request has json method": { "status": "PASS" }, "Request has text method": { "status": "PASS" }, "Check method attribute": { "status": "PASS" }, "Check url attribute": { "status": "PASS" }, "Check headers attribute": { "status": "PASS" }, "Check destination attribute": { "status": "FAIL" }, "Check referrer attribute": { "status": "FAIL" }, "Check referrerPolicy attribute": { "status": "FAIL" }, "Check mode attribute": { "status": "FAIL" }, "Check credentials attribute": { "status": "FAIL" }, "Check cache attribute": { "status": "FAIL" }, "Check redirect attribute": { "status": "FAIL" }, "Check integrity attribute": { "status": "FAIL" }, "Check isReloadNavigation attribute": { "status": "FAIL" }, "Check isHistoryNavigation attribute": { "status": "FAIL" }, "Check duplex attribute": { "status": "FAIL" }, "Check bodyUsed attribute": { "status": "PASS" }, "Request does not expose priority attribute": { "status": "PASS" }, "Request does not expose internalpriority attribute": { "status": "PASS" }, "Request does not expose blocking attribute": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/json.any.js.json ================================================ { "Ensure the correct JSON parser is used": { "status": "FAIL" }, "Ensure UTF-16 results in an error": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-blob-realm.any.js.json ================================================ { "realm of the Uint8Array from Response bytes()": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-cancel-stream.any.js.json ================================================ { "Cancelling a starting blob Response stream": { "status": "PASS" }, "Cancelling a loading blob Response stream": { "status": "PASS" }, "Cancelling a closed blob Response stream": { "status": "PASS" }, "Cancelling a starting Response stream": { "status": "PASS" }, "Cancelling a loading Response stream": { "status": "PASS" }, "Cancelling a closed Response stream": { "status": "PASS" }, "Accessing .body after canceling it": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-consume-empty.any.js.json ================================================ { "Consume response's body as text": { "status": "PASS" }, "Consume response's body as blob": { "status": "PASS" }, "Consume response's body as arrayBuffer": { "status": "PASS" }, "Consume response's body as json (error case)": { "status": "PASS" }, "Consume response's body as formData with correct multipart type (error case)": { "status": "FAIL" }, "Consume response's body as formData with correct urlencoded type": { "status": "PASS" }, "Consume response's body as formData without correct type (error case)": { "status": "PASS" }, "Consume empty blob response body as arrayBuffer": { "status": "PASS" }, "Consume empty text response body as arrayBuffer": { "status": "PASS" }, "Consume empty blob response body as text": { "status": "PASS" }, "Consume empty text response body as text": { "status": "PASS" }, "Consume empty URLSearchParams response body as text": { "status": "PASS" }, "Consume empty FormData response body as text": { "status": "PASS" }, "Consume empty ArrayBuffer response body as text": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-consume-stream.any.js.json ================================================ { "Read empty text response's body as readableStream": { "status": "PASS" }, "Read empty blob response's body as readableStream": { "status": "PASS" }, "Read blob response's body as readableStream with mode=undefined": { "status": "PASS" }, "Read text response's body as readableStream with mode=undefined": { "status": "PASS" }, "Read URLSearchParams response's body as readableStream with mode=undefined": { "status": "PASS" }, "Read array buffer response's body as readableStream with mode=undefined": { "status": "PASS" }, "Read form data response's body as readableStream with mode=undefined": { "status": "PASS" }, "Read blob response's body as readableStream with mode=byob": { "status": "FAIL" }, "Read text response's body as readableStream with mode=byob": { "status": "FAIL" }, "Read URLSearchParams response's body as readableStream with mode=byob": { "status": "FAIL" }, "Read array buffer response's body as readableStream with mode=byob": { "status": "FAIL" }, "Read form data response's body as readableStream with mode=byob": { "status": "FAIL" }, "Getting an error Response stream": { "status": "FAIL" }, "Getting a redirect Response stream": { "status": "PASS" }, "Reading with offset from Response stream": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-error-from-stream.any.js.json ================================================ { "ReadableStreamDefaultReader Promise receives ReadableStream start() Error": { "status": "PASS" }, "ReadableStreamDefaultReader Promise receives ReadableStream pull() Error": { "status": "PASS" }, "ReadableStream start() Error propagates to Response.arrayBuffer() Promise": { "status": "PASS" }, "ReadableStream start() Error propagates to Response.blob() Promise": { "status": "PASS" }, "ReadableStream start() Error propagates to Response.bytes() Promise": { "status": "FAIL" }, "ReadableStream start() Error propagates to Response.formData() Promise": { "status": "PASS" }, "ReadableStream start() Error propagates to Response.json() Promise": { "status": "PASS" }, "ReadableStream start() Error propagates to Response.text() Promise": { "status": "PASS" }, "ReadableStream pull() Error propagates to Response.arrayBuffer() Promise": { "status": "PASS" }, "ReadableStream pull() Error propagates to Response.blob() Promise": { "status": "PASS" }, "ReadableStream pull() Error propagates to Response.bytes() Promise": { "status": "FAIL" }, "ReadableStream pull() Error propagates to Response.formData() Promise": { "status": "PASS" }, "ReadableStream pull() Error propagates to Response.json() Promise": { "status": "PASS" }, "ReadableStream pull() Error propagates to Response.text() Promise": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-error.any.js.json ================================================ { "Throws RangeError when responseInit's status is 0": { "status": "PASS" }, "Throws RangeError when responseInit's status is 100": { "status": "PASS" }, "Throws RangeError when responseInit's status is 199": { "status": "PASS" }, "Throws RangeError when responseInit's status is 600": { "status": "PASS" }, "Throws RangeError when responseInit's status is 1000": { "status": "PASS" }, "Throws TypeError when responseInit's statusText is \n": { "status": "PASS" }, "Throws TypeError when responseInit's statusText is Ā": { "status": "PASS" }, "Throws TypeError when building a response with body and a body status of 204": { "status": "PASS" }, "Throws TypeError when building a response with body and a body status of 205": { "status": "PASS" }, "Throws TypeError when building a response with body and a body status of 304": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-from-stream.any.js.json ================================================ { "Constructing a Response with a stream on which getReader() is called": { "status": "PASS" }, "Constructing a Response with a stream on which read() is called": { "status": "PASS" }, "Constructing a Response with a stream on which read() and releaseLock() are called": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-headers-guard.any.js.json ================================================ { "Ensure response headers are immutable": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-init-001.any.js.json ================================================ { "Check default value for type attribute": { "status": "PASS" }, "Check default value for url attribute": { "status": "PASS" }, "Check default value for ok attribute": { "status": "PASS" }, "Check default value for status attribute": { "status": "PASS" }, "Check default value for statusText attribute": { "status": "PASS" }, "Check default value for body attribute": { "status": "PASS" }, "Check status init values and associated getter": { "status": "PASS" }, "Check statusText init values and associated getter": { "status": "PASS" }, "Test that Response.headers has the [SameObject] extended attribute": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-init-002.any.js.json ================================================ { "Initialize Response with headers values": { "status": "PASS" }, "Initialize Response's body with application/octet-binary": { "status": "PASS" }, "Initialize Response's body with multipart/form-data": { "status": "PASS" }, "Initialize Response's body with application/x-www-form-urlencoded;charset=UTF-8": { "status": "PASS" }, "Initialize Response's body with text/plain;charset=UTF-8": { "status": "PASS" }, "Read Response's body as readableStream": { "status": "PASS" }, "Testing empty Response Content-Type header": { "status": "PASS" }, "Testing null Response body": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-init-contenttype.any.js.json ================================================ { "Default Content-Type for Response with empty body": { "status": "PASS" }, "Default Content-Type for Response with Blob body (no type set)": { "status": "PASS" }, "Default Content-Type for Response with Blob body (empty type)": { "status": "PASS" }, "Default Content-Type for Response with Blob body (set type)": { "status": "PASS" }, "Default Content-Type for Response with buffer source body": { "status": "PASS" }, "Default Content-Type for Response with FormData body": { "status": "PASS" }, "Default Content-Type for Response with URLSearchParams body": { "status": "PASS" }, "Default Content-Type for Response with string body": { "status": "PASS" }, "Default Content-Type for Response with ReadableStream body": { "status": "PASS" }, "Can override Content-Type for Response with empty body": { "status": "PASS" }, "Can override Content-Type for Response with Blob body (no type set)": { "status": "PASS" }, "Can override Content-Type for Response with Blob body (empty type)": { "status": "PASS" }, "Can override Content-Type for Response with Blob body (set type)": { "status": "PASS" }, "Can override Content-Type for Response with buffer source body": { "status": "PASS" }, "Can override Content-Type for Response with FormData body": { "status": "PASS" }, "Can override Content-Type for Response with URLSearchParams body": { "status": "PASS" }, "Can override Content-Type for Response with string body": { "status": "PASS" }, "Can override Content-Type for Response with ReadableStream body": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-static-error.any.js.json ================================================ { "Check response returned by static method error()": { "status": "FAIL" }, "the 'guard' of the Headers instance should be immutable": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-static-json.any.js.json ================================================ { "Check response returned by static json() with init undefined": { "status": "PASS" }, "Check response returned by static json() with init {\"status\":400}": { "status": "PASS" }, "Check response returned by static json() with init {\"statusText\":\"foo\"}": { "status": "PASS" }, "Check response returned by static json() with init {\"headers\":{}}": { "status": "PASS" }, "Check response returned by static json() with init {\"headers\":{\"content-type\":\"foo/bar\"}}": { "status": "PASS" }, "Check response returned by static json() with init {\"headers\":{\"x-foo\":\"bar\"}}": { "status": "PASS" }, "Throws TypeError when calling static json() with a status of 204": { "status": "PASS" }, "Throws TypeError when calling static json() with a status of 205": { "status": "PASS" }, "Throws TypeError when calling static json() with a status of 304": { "status": "PASS" }, "Check static json() encodes JSON objects correctly": { "status": "PASS" }, "Check static json() throws when data is not encodable": { "status": "PASS" }, "Check static json() throws when data is circular": { "status": "PASS" }, "Check static json() propagates JSON serializer errors": { "status": "PASS" }, "Check response returned by static json() with input 𝌆": { "status": "PASS" }, "Check response returned by static json() with input U+df06U+d834": { "status": "PASS" }, "Check response returned by static json() with input U+dead": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-static-redirect.any.js.json ================================================ { "Check default redirect response": { "status": "PASS" }, "Check response returned by static method redirect(), status = 301": { "status": "PASS" }, "Check response returned by static method redirect(), status = 302": { "status": "PASS" }, "Check response returned by static method redirect(), status = 303": { "status": "PASS" }, "Check response returned by static method redirect(), status = 307": { "status": "PASS" }, "Check response returned by static method redirect(), status = 308": { "status": "PASS" }, "Check error returned when giving invalid url to redirect()": { "status": "PASS" }, "Check error returned when giving invalid status to redirect(), status = 200": { "status": "PASS" }, "Check error returned when giving invalid status to redirect(), status = 309": { "status": "PASS" }, "Check error returned when giving invalid status to redirect(), status = 400": { "status": "PASS" }, "Check error returned when giving invalid status to redirect(), status = 500": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-stream-bad-chunk.any.js.json ================================================ { "ReadableStream with non-Uint8Array chunk passed to Response.arrayBuffer() causes TypeError": { "status": "PASS" }, "ReadableStream with non-Uint8Array chunk passed to Response.blob() causes TypeError": { "status": "PASS" }, "ReadableStream with non-Uint8Array chunk passed to Response.bytes() causes TypeError": { "status": "FAIL" }, "ReadableStream with non-Uint8Array chunk passed to Response.formData() causes TypeError": { "status": "PASS" }, "ReadableStream with non-Uint8Array chunk passed to Response.json() causes TypeError": { "status": "PASS" }, "ReadableStream with non-Uint8Array chunk passed to Response.text() causes TypeError": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-stream-disturbed-1.any.js.json ================================================ { "Getting blob after getting the Response body - not disturbed, not locked (body source: fetch)": { "status": "PASS" }, "Getting text after getting the Response body - not disturbed, not locked (body source: fetch)": { "status": "PASS" }, "Getting json after getting the Response body - not disturbed, not locked (body source: fetch)": { "status": "PASS" }, "Getting arrayBuffer after getting the Response body - not disturbed, not locked (body source: fetch)": { "status": "PASS" }, "Getting blob after getting the Response body - not disturbed, not locked (body source: stream)": { "status": "PASS" }, "Getting text after getting the Response body - not disturbed, not locked (body source: stream)": { "status": "PASS" }, "Getting json after getting the Response body - not disturbed, not locked (body source: stream)": { "status": "PASS" }, "Getting arrayBuffer after getting the Response body - not disturbed, not locked (body source: stream)": { "status": "PASS" }, "Getting blob after getting the Response body - not disturbed, not locked (body source: string)": { "status": "PASS" }, "Getting text after getting the Response body - not disturbed, not locked (body source: string)": { "status": "PASS" }, "Getting json after getting the Response body - not disturbed, not locked (body source: string)": { "status": "PASS" }, "Getting arrayBuffer after getting the Response body - not disturbed, not locked (body source: string)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-stream-disturbed-2.any.js.json ================================================ { "Getting blob after getting a locked Response body (body source: fetch)": { "status": "PASS" }, "Getting text after getting a locked Response body (body source: fetch)": { "status": "PASS" }, "Getting json after getting a locked Response body (body source: fetch)": { "status": "PASS" }, "Getting arrayBuffer after getting a locked Response body (body source: fetch)": { "status": "PASS" }, "Getting blob after getting a locked Response body (body source: stream)": { "status": "PASS" }, "Getting text after getting a locked Response body (body source: stream)": { "status": "PASS" }, "Getting json after getting a locked Response body (body source: stream)": { "status": "PASS" }, "Getting arrayBuffer after getting a locked Response body (body source: stream)": { "status": "PASS" }, "Getting blob after getting a locked Response body (body source: string)": { "status": "PASS" }, "Getting text after getting a locked Response body (body source: string)": { "status": "PASS" }, "Getting json after getting a locked Response body (body source: string)": { "status": "PASS" }, "Getting arrayBuffer after getting a locked Response body (body source: string)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-stream-disturbed-3.any.js.json ================================================ { "Getting blob after reading the Response body (body source: fetch)": { "status": "PASS" }, "Getting text after reading the Response body (body source: fetch)": { "status": "PASS" }, "Getting json after reading the Response body (body source: fetch)": { "status": "PASS" }, "Getting arrayBuffer after reading the Response body (body source: fetch)": { "status": "PASS" }, "Getting blob after reading the Response body (body source: stream)": { "status": "PASS" }, "Getting text after reading the Response body (body source: stream)": { "status": "PASS" }, "Getting json after reading the Response body (body source: stream)": { "status": "PASS" }, "Getting arrayBuffer after reading the Response body (body source: stream)": { "status": "PASS" }, "Getting blob after reading the Response body (body source: string)": { "status": "PASS" }, "Getting text after reading the Response body (body source: string)": { "status": "PASS" }, "Getting json after reading the Response body (body source: string)": { "status": "PASS" }, "Getting arrayBuffer after reading the Response body (body source: string)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-stream-disturbed-4.any.js.json ================================================ { "Getting blob after cancelling the Response body (body source: fetch)": { "status": "PASS" }, "Getting text after cancelling the Response body (body source: fetch)": { "status": "PASS" }, "Getting json after cancelling the Response body (body source: fetch)": { "status": "PASS" }, "Getting arrayBuffer after cancelling the Response body (body source: fetch)": { "status": "PASS" }, "Getting blob after cancelling the Response body (body source: stream)": { "status": "PASS" }, "Getting text after cancelling the Response body (body source: stream)": { "status": "PASS" }, "Getting json after cancelling the Response body (body source: stream)": { "status": "PASS" }, "Getting arrayBuffer after cancelling the Response body (body source: stream)": { "status": "PASS" }, "Getting blob after cancelling the Response body (body source: string)": { "status": "PASS" }, "Getting text after cancelling the Response body (body source: string)": { "status": "PASS" }, "Getting json after cancelling the Response body (body source: string)": { "status": "PASS" }, "Getting arrayBuffer after cancelling the Response body (body source: string)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-stream-disturbed-5.any.js.json ================================================ { "Getting a body reader after consuming as blob (body source: fetch)": { "status": "FAIL" }, "Getting a body reader after consuming as text (body source: fetch)": { "status": "FAIL" }, "Getting a body reader after consuming as json (body source: fetch)": { "status": "FAIL" }, "Getting a body reader after consuming as arrayBuffer (body source: fetch)": { "status": "FAIL" }, "Getting a body reader after consuming as blob (body source: stream)": { "status": "FAIL" }, "Getting a body reader after consuming as text (body source: stream)": { "status": "FAIL" }, "Getting a body reader after consuming as json (body source: stream)": { "status": "FAIL" }, "Getting a body reader after consuming as arrayBuffer (body source: stream)": { "status": "FAIL" }, "Getting a body reader after consuming as blob (body source: string)": { "status": "FAIL" }, "Getting a body reader after consuming as text (body source: string)": { "status": "FAIL" }, "Getting a body reader after consuming as json (body source: string)": { "status": "FAIL" }, "Getting a body reader after consuming as arrayBuffer (body source: string)": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-stream-disturbed-6.any.js.json ================================================ { "A non-closed stream on which read() has been called": { "status": "FAIL" }, "A non-closed stream on which cancel() has been called": { "status": "FAIL" }, "A closed stream on which read() has been called": { "status": "FAIL" }, "An errored stream on which read() has been called": { "status": "FAIL" }, "An errored stream on which cancel() has been called": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-stream-disturbed-by-pipe.any.js.json ================================================ { "using pipeTo on Response body should disturb it synchronously": { "status": "FAIL" }, "using pipeThrough on Response body should disturb it synchronously": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/api/response/response-stream-with-broken-then.any.js.json ================================================ { "Attempt to inject {done: false, value: bye} via Object.prototype.then.": { "status": "PASS" }, "Attempt to inject value: undefined via Object.prototype.then.": { "status": "PASS" }, "Attempt to inject undefined via Object.prototype.then.": { "status": "PASS" }, "Attempt to inject 8.2 via Object.prototype.then.": { "status": "PASS" }, "intercepting arraybuffer to text conversion via Object.prototype.then should not be possible": { "status": "PASS" }, "intercepting arraybuffer to body readable stream conversion via Object.prototype.then should not be possible": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/content-type/multipart-malformed.any.js.json ================================================ { "Invalid form data should not crash the browser": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/content-type/multipart.window.js.json ================================================ { "multipart": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/data-urls/base64.any.js.json ================================================ { "Setup.": { "status": "PASS" }, "data: URL base64 handling: \"\"": { "status": "FAIL" }, "data: URL base64 handling: \"abcd\"": { "status": "FAIL" }, "data: URL base64 handling: \" abcd\"": { "status": "FAIL" }, "data: URL base64 handling: \"abcd \"": { "status": "FAIL" }, "data: URL base64 handling: \" abcd===\"": { "status": "FAIL" }, "data: URL base64 handling: \"abcd=== \"": { "status": "PASS" }, "data: URL base64 handling: \"abcd ===\"": { "status": "FAIL" }, "data: URL base64 handling: \"a\"": { "status": "PASS" }, "data: URL base64 handling: \"ab\"": { "status": "FAIL" }, "data: URL base64 handling: \"abc\"": { "status": "FAIL" }, "data: URL base64 handling: \"abcde\"": { "status": "PASS" }, "data: URL base64 handling: \"𐀀\"": { "status": "FAIL" }, "data: URL base64 handling: \"=\"": { "status": "PASS" }, "data: URL base64 handling: \"==\"": { "status": "PASS" }, "data: URL base64 handling: \"===\"": { "status": "PASS" }, "data: URL base64 handling: \"====\"": { "status": "PASS" }, "data: URL base64 handling: \"=====\"": { "status": "PASS" }, "data: URL base64 handling: \"a=\"": { "status": "PASS" }, "data: URL base64 handling: \"a==\"": { "status": "PASS" }, "data: URL base64 handling: \"a===\"": { "status": "PASS" }, "data: URL base64 handling: \"a====\"": { "status": "PASS" }, "data: URL base64 handling: \"a=====\"": { "status": "PASS" }, "data: URL base64 handling: \"ab=\"": { "status": "PASS" }, "data: URL base64 handling: \"ab==\"": { "status": "FAIL" }, "data: URL base64 handling: \"ab===\"": { "status": "PASS" }, "data: URL base64 handling: \"ab====\"": { "status": "PASS" }, "data: URL base64 handling: \"ab=====\"": { "status": "PASS" }, "data: URL base64 handling: \"abc=\"": { "status": "FAIL" }, "data: URL base64 handling: \"abc==\"": { "status": "PASS" }, "data: URL base64 handling: \"abc===\"": { "status": "PASS" }, "data: URL base64 handling: \"abc====\"": { "status": "PASS" }, "data: URL base64 handling: \"abc=====\"": { "status": "PASS" }, "data: URL base64 handling: \"abcd=\"": { "status": "PASS" }, "data: URL base64 handling: \"abcd==\"": { "status": "PASS" }, "data: URL base64 handling: \"abcd===\"": { "status": "PASS" }, "data: URL base64 handling: \"abcd====\"": { "status": "PASS" }, "data: URL base64 handling: \"abcd=====\"": { "status": "PASS" }, "data: URL base64 handling: \"abcde=\"": { "status": "PASS" }, "data: URL base64 handling: \"abcde==\"": { "status": "PASS" }, "data: URL base64 handling: \"abcde===\"": { "status": "PASS" }, "data: URL base64 handling: \"abcde====\"": { "status": "PASS" }, "data: URL base64 handling: \"abcde=====\"": { "status": "PASS" }, "data: URL base64 handling: \"=a\"": { "status": "PASS" }, "data: URL base64 handling: \"=a=\"": { "status": "PASS" }, "data: URL base64 handling: \"a=b\"": { "status": "PASS" }, "data: URL base64 handling: \"a=b=\"": { "status": "PASS" }, "data: URL base64 handling: \"ab=c\"": { "status": "PASS" }, "data: URL base64 handling: \"ab=c=\"": { "status": "PASS" }, "data: URL base64 handling: \"abc=d\"": { "status": "PASS" }, "data: URL base64 handling: \"abc=d=\"": { "status": "PASS" }, "data: URL base64 handling: \"ab\\vcd\"": { "status": "FAIL" }, "data: URL base64 handling: \"ab cd\"": { "status": "FAIL" }, "data: URL base64 handling: \"ab、cd\"": { "status": "FAIL" }, "data: URL base64 handling: \"ab\\tcd\"": { "status": "FAIL" }, "data: URL base64 handling: \"ab\\ncd\"": { "status": "FAIL" }, "data: URL base64 handling: \"ab\\fcd\"": { "status": "FAIL" }, "data: URL base64 handling: \"ab\\rcd\"": { "status": "FAIL" }, "data: URL base64 handling: \"ab cd\"": { "status": "FAIL" }, "data: URL base64 handling: \"ab cd\"": { "status": "FAIL" }, "data: URL base64 handling: \"ab\\t\\n\\f\\r cd\"": { "status": "FAIL" }, "data: URL base64 handling: \" \\t\\n\\f\\r ab\\t\\n\\f\\r cd\\t\\n\\f\\r \"": { "status": "FAIL" }, "data: URL base64 handling: \"ab\\t\\n\\f\\r =\\t\\n\\f\\r =\\t\\n\\f\\r \"": { "status": "FAIL" }, "data: URL base64 handling: \"A\"": { "status": "PASS" }, "data: URL base64 handling: \"/A\"": { "status": "FAIL" }, "data: URL base64 handling: \"//A\"": { "status": "FAIL" }, "data: URL base64 handling: \"///A\"": { "status": "FAIL" }, "data: URL base64 handling: \"////A\"": { "status": "FAIL" }, "data: URL base64 handling: \"/\"": { "status": "FAIL" }, "data: URL base64 handling: \"A/\"": { "status": "FAIL" }, "data: URL base64 handling: \"AA/\"": { "status": "FAIL" }, "data: URL base64 handling: \"AAAA/\"": { "status": "FAIL" }, "data: URL base64 handling: \"AAA/\"": { "status": "FAIL" }, "data: URL base64 handling: \"\\0nonsense\"": { "status": "FAIL" }, "data: URL base64 handling: \"abcd\\0nonsense\"": { "status": "FAIL" }, "data: URL base64 handling: \"YQ\"": { "status": "FAIL" }, "data: URL base64 handling: \"YR\"": { "status": "FAIL" }, "data: URL base64 handling: \"~~\"": { "status": "PASS" }, "data: URL base64 handling: \"..\"": { "status": "PASS" }, "data: URL base64 handling: \"--\"": { "status": "PASS" }, "data: URL base64 handling: \"__\"": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/fetch/data-urls/processing.any.js.json ================================================ { "Setup.": { "status": "PASS" }, "\"data://test/,X\"": { "status": "FAIL" }, "\"data://test:test/,X\"": { "status": "PASS" }, "\"data:,X\"": { "status": "FAIL" }, "\"data:\"": { "status": "PASS" }, "\"data:text/html\"": { "status": "FAIL" }, "\"data:text/html ;charset=x \"": { "status": "FAIL" }, "\"data:,\"": { "status": "FAIL" }, "\"data:,X#X\"": { "status": "FAIL" }, "\"data:,%FF\"": { "status": "FAIL" }, "\"data:text/plain,X\"": { "status": "FAIL" }, "\"data:text/plain ,X\"": { "status": "FAIL" }, "\"data:text/plain%20,X\"": { "status": "FAIL" }, "\"data:text/plain\\f,X\"": { "status": "FAIL" }, "\"data:text/plain%0C,X\"": { "status": "FAIL" }, "\"data:text/plain;,X\"": { "status": "FAIL" }, "\"data:;x=x;charset=x,X\"": { "status": "FAIL" }, "\"data:;x=x,X\"": { "status": "FAIL" }, "\"data:text/plain;charset=windows-1252,%C2%B1\"": { "status": "FAIL" }, "\"data:text/plain;Charset=UTF-8,%C2%B1\"": { "status": "FAIL" }, "\"data:text/plain;charset=windows-1252,áñçə💩\"": { "status": "FAIL" }, "\"data:text/plain;charset=UTF-8,áñçə💩\"": { "status": "FAIL" }, "\"data:image/gif,%C2%B1\"": { "status": "FAIL" }, "\"data:IMAGE/gif,%C2%B1\"": { "status": "FAIL" }, "\"data:IMAGE/gif;hi=x,%C2%B1\"": { "status": "FAIL" }, "\"data:IMAGE/gif;CHARSET=x,%C2%B1\"": { "status": "FAIL" }, "\"data: ,%FF\"": { "status": "FAIL" }, "\"data:%20,%FF\"": { "status": "FAIL" }, "\"data:\\f,%FF\"": { "status": "FAIL" }, "\"data:%1F,%FF\"": { "status": "FAIL" }, "\"data:\\0,%FF\"": { "status": "FAIL" }, "\"data:%00,%FF\"": { "status": "FAIL" }, "\"data:text/html ,X\"": { "status": "FAIL" }, "\"data:text / html,X\"": { "status": "FAIL" }, "\"data:†,X\"": { "status": "FAIL" }, "\"data:†/†,X\"": { "status": "FAIL" }, "\"data:X,X\"": { "status": "FAIL" }, "\"data:image/png,X X\"": { "status": "FAIL" }, "\"data:application/javascript,X X\"": { "status": "FAIL" }, "\"data:application/xml,X X\"": { "status": "FAIL" }, "\"data:text/javascript,X X\"": { "status": "FAIL" }, "\"data:text/plain,X X\"": { "status": "FAIL" }, "\"data:unknown/unknown,X X\"": { "status": "FAIL" }, "\"data:text/plain;a=\\\",\\\",X\"": { "status": "FAIL" }, "\"data:text/plain;a=%2C,X\"": { "status": "FAIL" }, "\"data:;base64;base64,WA\"": { "status": "FAIL" }, "\"data:x/x;base64;base64,WA\"": { "status": "FAIL" }, "\"data:x/x;base64;charset=x,WA\"": { "status": "FAIL" }, "\"data:x/x;base64;charset=x;base64,WA\"": { "status": "FAIL" }, "\"data:x/x;base64;base64x,WA\"": { "status": "FAIL" }, "\"data:;base64,W%20A\"": { "status": "FAIL" }, "\"data:;base64,W%0CA\"": { "status": "FAIL" }, "\"data:x;base64x,WA\"": { "status": "FAIL" }, "\"data:x;base64;x,WA\"": { "status": "FAIL" }, "\"data:x;base64=x,WA\"": { "status": "FAIL" }, "\"data:; base64,WA\"": { "status": "FAIL" }, "\"data:; base64,WA\"": { "status": "FAIL" }, "\"data: ;charset=x ; base64,WA\"": { "status": "FAIL" }, "\"data:;base64;,WA\"": { "status": "FAIL" }, "\"data:;base64 ,WA\"": { "status": "FAIL" }, "\"data:;base64 ,WA\"": { "status": "FAIL" }, "\"data:;base 64,WA\"": { "status": "FAIL" }, "\"data:;BASe64,WA\"": { "status": "FAIL" }, "\"data:;%62ase64,WA\"": { "status": "FAIL" }, "\"data:%3Bbase64,WA\"": { "status": "FAIL" }, "\"data:;charset=x,X\"": { "status": "FAIL" }, "\"data:; charset=x,X\"": { "status": "FAIL" }, "\"data:;charset =x,X\"": { "status": "FAIL" }, "\"data:;charset= x,X\"": { "status": "FAIL" }, "\"data:;charset=,X\"": { "status": "FAIL" }, "\"data:;charset,X\"": { "status": "FAIL" }, "\"data:;charset=\\\"x\\\",X\"": { "status": "FAIL" }, "\"data:;CHARSET=\\\"X\\\",X\"": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/hr-time/basic.any.js.json ================================================ { "self.performance.now() is a function that returns a number": { "status": "PASS" }, "self.performance.now() returns a positive number": { "status": "PASS" }, "self.performance.now() difference is not negative": { "status": "PASS" }, "High resolution time has approximately the right relative magnitude": { "status": "PASS" }, "Performance interface extends EventTarget.": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/hr-time/idlharness.any.js.json ================================================ { "idl_test setup": { "status": "PASS" }, "idl_test validation": { "status": "PASS" }, "Partial interface mixin WindowOrWorkerGlobalScope: original interface mixin defined": { "status": "PASS" }, "Partial interface mixin WindowOrWorkerGlobalScope: member names are unique": { "status": "PASS" }, "Partial interface Window: member names are unique": { "status": "PASS" }, "Window includes GlobalEventHandlers: member names are unique": { "status": "PASS" }, "Window includes WindowEventHandlers: member names are unique": { "status": "PASS" }, "Window includes WindowOrWorkerGlobalScope: member names are unique": { "status": "PASS" }, "WorkerGlobalScope includes WindowOrWorkerGlobalScope: member names are unique": { "status": "PASS" }, "Window includes AnimationFrameProvider: member names are unique": { "status": "PASS" }, "Window includes WindowSessionStorage: member names are unique": { "status": "PASS" }, "Window includes WindowLocalStorage: member names are unique": { "status": "PASS" }, "Performance interface: existence and properties of interface object": { "status": "FAIL" }, "Performance interface object length": { "status": "PASS" }, "Performance interface object name": { "status": "PASS" }, "Performance interface: existence and properties of interface prototype object": { "status": "FAIL" }, "Performance interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "Performance interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "Performance interface: operation now()": { "status": "PASS" }, "Performance interface: attribute timeOrigin": { "status": "FAIL" }, "Performance interface: operation toJSON()": { "status": "FAIL" }, "Performance must be primary interface of performance": { "status": "PASS" }, "Stringification of performance": { "status": "FAIL" }, "Performance interface: performance must inherit property \"now()\" with the proper type": { "status": "FAIL" }, "Performance interface: performance must inherit property \"timeOrigin\" with the proper type": { "status": "FAIL" }, "Performance interface: performance must inherit property \"toJSON()\" with the proper type": { "status": "FAIL" }, "Performance interface: default toJSON operation on performance": { "status": "FAIL" }, "Window interface: attribute performance": { "status": "FAIL" }, "WorkerGlobalScope interface: self must not have property \"performance\"": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/hr-time/monotonic-clock.any.js.json ================================================ { "self.performance.now() returns a positive number": { "status": "PASS" }, "self.performance.now() difference is not negative": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/html/webappapis/atob/base64.any.js.json ================================================ { "btoa(\"עברית\") must raise INVALID_CHARACTER_ERR": { "status": "FAIL" }, "btoa(\"\") == \"\"": { "status": "PASS" }, "btoa(\"ab\") == \"YWI=\"": { "status": "PASS" }, "btoa(\"abc\") == \"YWJj\"": { "status": "PASS" }, "btoa(\"abcd\") == \"YWJjZA==\"": { "status": "PASS" }, "btoa(\"abcde\") == \"YWJjZGU=\"": { "status": "PASS" }, "btoa(\"ÿÿÀ\") == \"///A\"": { "status": "PASS" }, "btoa(\"\\0a\") == \"AGE=\"": { "status": "PASS" }, "btoa(\"a\\0b\") == \"YQBi\"": { "status": "PASS" }, "btoa(undefined) == \"dW5kZWZpbmVk\"": { "status": "PASS" }, "btoa(null) == \"bnVsbA==\"": { "status": "PASS" }, "btoa(7) == \"Nw==\"": { "status": "PASS" }, "btoa(12) == \"MTI=\"": { "status": "PASS" }, "btoa(1.5) == \"MS41\"": { "status": "PASS" }, "btoa(true) == \"dHJ1ZQ==\"": { "status": "PASS" }, "btoa(false) == \"ZmFsc2U=\"": { "status": "PASS" }, "btoa(NaN) == \"TmFO\"": { "status": "PASS" }, "btoa(Infinity) == \"SW5maW5pdHk=\"": { "status": "PASS" }, "btoa(-Infinity) == \"LUluZmluaXR5\"": { "status": "PASS" }, "btoa(0) == \"MA==\"": { "status": "PASS" }, "btoa(-0) == \"MA==\"": { "status": "PASS" }, "btoa(object \"foo\") == \"Zm9v\"": { "status": "PASS" }, "btoa(\"\\0\") == \"AA==\"": { "status": "PASS" }, "btoa(\"\\x01\") == \"AQ==\"": { "status": "PASS" }, "btoa(\"\\x02\") == \"Ag==\"": { "status": "PASS" }, "btoa(\"\\x03\") == \"Aw==\"": { "status": "PASS" }, "btoa(\"\\x04\") == \"BA==\"": { "status": "PASS" }, "btoa(\"\\x05\") == \"BQ==\"": { "status": "PASS" }, "btoa(\"\\x06\") == \"Bg==\"": { "status": "PASS" }, "btoa(\"\\x07\") == \"Bw==\"": { "status": "PASS" }, "btoa(\"\\b\") == \"CA==\"": { "status": "PASS" }, "btoa(\"\\t\") == \"CQ==\"": { "status": "PASS" }, "btoa(\"\\n\") == \"Cg==\"": { "status": "PASS" }, "btoa(\"\\v\") == \"Cw==\"": { "status": "PASS" }, "btoa(\"\\f\") == \"DA==\"": { "status": "PASS" }, "btoa(\"\\r\") == \"DQ==\"": { "status": "PASS" }, "btoa(\"\\x0e\") == \"Dg==\"": { "status": "PASS" }, "btoa(\"\\x0f\") == \"Dw==\"": { "status": "PASS" }, "btoa(\"\\x10\") == \"EA==\"": { "status": "PASS" }, "btoa(\"\\x11\") == \"EQ==\"": { "status": "PASS" }, "btoa(\"\\x12\") == \"Eg==\"": { "status": "PASS" }, "btoa(\"\\x13\") == \"Ew==\"": { "status": "PASS" }, "btoa(\"\\x14\") == \"FA==\"": { "status": "PASS" }, "btoa(\"\\x15\") == \"FQ==\"": { "status": "PASS" }, "btoa(\"\\x16\") == \"Fg==\"": { "status": "PASS" }, "btoa(\"\\x17\") == \"Fw==\"": { "status": "PASS" }, "btoa(\"\\x18\") == \"GA==\"": { "status": "PASS" }, "btoa(\"\\x19\") == \"GQ==\"": { "status": "PASS" }, "btoa(\"\\x1a\") == \"Gg==\"": { "status": "PASS" }, "btoa(\"\\x1b\") == \"Gw==\"": { "status": "PASS" }, "btoa(\"\\x1c\") == \"HA==\"": { "status": "PASS" }, "btoa(\"\\x1d\") == \"HQ==\"": { "status": "PASS" }, "btoa(\"\\x1e\") == \"Hg==\"": { "status": "PASS" }, "btoa(\"\\x1f\") == \"Hw==\"": { "status": "PASS" }, "btoa(\" \") == \"IA==\"": { "status": "PASS" }, "btoa(\"!\") == \"IQ==\"": { "status": "PASS" }, "btoa(\"\\\"\") == \"Ig==\"": { "status": "PASS" }, "btoa(\"#\") == \"Iw==\"": { "status": "PASS" }, "btoa(\"$\") == \"JA==\"": { "status": "PASS" }, "btoa(\"%\") == \"JQ==\"": { "status": "PASS" }, "btoa(\"&\") == \"Jg==\"": { "status": "PASS" }, "btoa(\"'\") == \"Jw==\"": { "status": "PASS" }, "btoa(\"(\") == \"KA==\"": { "status": "PASS" }, "btoa(\")\") == \"KQ==\"": { "status": "PASS" }, "btoa(\"*\") == \"Kg==\"": { "status": "PASS" }, "btoa(\"+\") == \"Kw==\"": { "status": "PASS" }, "btoa(\",\") == \"LA==\"": { "status": "PASS" }, "btoa(\"-\") == \"LQ==\"": { "status": "PASS" }, "btoa(\".\") == \"Lg==\"": { "status": "PASS" }, "btoa(\"/\") == \"Lw==\"": { "status": "PASS" }, "btoa(\"0\") == \"MA==\"": { "status": "PASS" }, "btoa(\"1\") == \"MQ==\"": { "status": "PASS" }, "btoa(\"2\") == \"Mg==\"": { "status": "PASS" }, "btoa(\"3\") == \"Mw==\"": { "status": "PASS" }, "btoa(\"4\") == \"NA==\"": { "status": "PASS" }, "btoa(\"5\") == \"NQ==\"": { "status": "PASS" }, "btoa(\"6\") == \"Ng==\"": { "status": "PASS" }, "btoa(\"7\") == \"Nw==\"": { "status": "PASS" }, "btoa(\"8\") == \"OA==\"": { "status": "PASS" }, "btoa(\"9\") == \"OQ==\"": { "status": "PASS" }, "btoa(\":\") == \"Og==\"": { "status": "PASS" }, "btoa(\";\") == \"Ow==\"": { "status": "PASS" }, "btoa(\"<\") == \"PA==\"": { "status": "PASS" }, "btoa(\"=\") == \"PQ==\"": { "status": "PASS" }, "btoa(\">\") == \"Pg==\"": { "status": "PASS" }, "btoa(\"?\") == \"Pw==\"": { "status": "PASS" }, "btoa(\"@\") == \"QA==\"": { "status": "PASS" }, "btoa(\"A\") == \"QQ==\"": { "status": "PASS" }, "btoa(\"B\") == \"Qg==\"": { "status": "PASS" }, "btoa(\"C\") == \"Qw==\"": { "status": "PASS" }, "btoa(\"D\") == \"RA==\"": { "status": "PASS" }, "btoa(\"E\") == \"RQ==\"": { "status": "PASS" }, "btoa(\"F\") == \"Rg==\"": { "status": "PASS" }, "btoa(\"G\") == \"Rw==\"": { "status": "PASS" }, "btoa(\"H\") == \"SA==\"": { "status": "PASS" }, "btoa(\"I\") == \"SQ==\"": { "status": "PASS" }, "btoa(\"J\") == \"Sg==\"": { "status": "PASS" }, "btoa(\"K\") == \"Sw==\"": { "status": "PASS" }, "btoa(\"L\") == \"TA==\"": { "status": "PASS" }, "btoa(\"M\") == \"TQ==\"": { "status": "PASS" }, "btoa(\"N\") == \"Tg==\"": { "status": "PASS" }, "btoa(\"O\") == \"Tw==\"": { "status": "PASS" }, "btoa(\"P\") == \"UA==\"": { "status": "PASS" }, "btoa(\"Q\") == \"UQ==\"": { "status": "PASS" }, "btoa(\"R\") == \"Ug==\"": { "status": "PASS" }, "btoa(\"S\") == \"Uw==\"": { "status": "PASS" }, "btoa(\"T\") == \"VA==\"": { "status": "PASS" }, "btoa(\"U\") == \"VQ==\"": { "status": "PASS" }, "btoa(\"V\") == \"Vg==\"": { "status": "PASS" }, "btoa(\"W\") == \"Vw==\"": { "status": "PASS" }, "btoa(\"X\") == \"WA==\"": { "status": "PASS" }, "btoa(\"Y\") == \"WQ==\"": { "status": "PASS" }, "btoa(\"Z\") == \"Wg==\"": { "status": "PASS" }, "btoa(\"[\") == \"Ww==\"": { "status": "PASS" }, "btoa(\"\\\\\") == \"XA==\"": { "status": "PASS" }, "btoa(\"]\") == \"XQ==\"": { "status": "PASS" }, "btoa(\"^\") == \"Xg==\"": { "status": "PASS" }, "btoa(\"_\") == \"Xw==\"": { "status": "PASS" }, "btoa(\"`\") == \"YA==\"": { "status": "PASS" }, "btoa(\"a\") == \"YQ==\"": { "status": "PASS" }, "btoa(\"b\") == \"Yg==\"": { "status": "PASS" }, "btoa(\"c\") == \"Yw==\"": { "status": "PASS" }, "btoa(\"d\") == \"ZA==\"": { "status": "PASS" }, "btoa(\"e\") == \"ZQ==\"": { "status": "PASS" }, "btoa(\"f\") == \"Zg==\"": { "status": "PASS" }, "btoa(\"g\") == \"Zw==\"": { "status": "PASS" }, "btoa(\"h\") == \"aA==\"": { "status": "PASS" }, "btoa(\"i\") == \"aQ==\"": { "status": "PASS" }, "btoa(\"j\") == \"ag==\"": { "status": "PASS" }, "btoa(\"k\") == \"aw==\"": { "status": "PASS" }, "btoa(\"l\") == \"bA==\"": { "status": "PASS" }, "btoa(\"m\") == \"bQ==\"": { "status": "PASS" }, "btoa(\"n\") == \"bg==\"": { "status": "PASS" }, "btoa(\"o\") == \"bw==\"": { "status": "PASS" }, "btoa(\"p\") == \"cA==\"": { "status": "PASS" }, "btoa(\"q\") == \"cQ==\"": { "status": "PASS" }, "btoa(\"r\") == \"cg==\"": { "status": "PASS" }, "btoa(\"s\") == \"cw==\"": { "status": "PASS" }, "btoa(\"t\") == \"dA==\"": { "status": "PASS" }, "btoa(\"u\") == \"dQ==\"": { "status": "PASS" }, "btoa(\"v\") == \"dg==\"": { "status": "PASS" }, "btoa(\"w\") == \"dw==\"": { "status": "PASS" }, "btoa(\"x\") == \"eA==\"": { "status": "PASS" }, "btoa(\"y\") == \"eQ==\"": { "status": "PASS" }, "btoa(\"z\") == \"eg==\"": { "status": "PASS" }, "btoa(\"{\") == \"ew==\"": { "status": "PASS" }, "btoa(\"|\") == \"fA==\"": { "status": "PASS" }, "btoa(\"}\") == \"fQ==\"": { "status": "PASS" }, "btoa(\"~\") == \"fg==\"": { "status": "PASS" }, "btoa(\"\") == \"fw==\"": { "status": "PASS" }, "btoa(\"€\") == \"gA==\"": { "status": "PASS" }, "btoa(\"\") == \"gQ==\"": { "status": "PASS" }, "btoa(\"‚\") == \"gg==\"": { "status": "PASS" }, "btoa(\"ƒ\") == \"gw==\"": { "status": "PASS" }, "btoa(\"„\") == \"hA==\"": { "status": "PASS" }, "btoa(\"…\") == \"hQ==\"": { "status": "PASS" }, "btoa(\"†\") == \"hg==\"": { "status": "PASS" }, "btoa(\"‡\") == \"hw==\"": { "status": "PASS" }, "btoa(\"ˆ\") == \"iA==\"": { "status": "PASS" }, "btoa(\"‰\") == \"iQ==\"": { "status": "PASS" }, "btoa(\"Š\") == \"ig==\"": { "status": "PASS" }, "btoa(\"‹\") == \"iw==\"": { "status": "PASS" }, "btoa(\"Œ\") == \"jA==\"": { "status": "PASS" }, "btoa(\"\") == \"jQ==\"": { "status": "PASS" }, "btoa(\"Ž\") == \"jg==\"": { "status": "PASS" }, "btoa(\"\") == \"jw==\"": { "status": "PASS" }, "btoa(\"\") == \"kA==\"": { "status": "PASS" }, "btoa(\"‘\") == \"kQ==\"": { "status": "PASS" }, "btoa(\"’\") == \"kg==\"": { "status": "PASS" }, "btoa(\"“\") == \"kw==\"": { "status": "PASS" }, "btoa(\"”\") == \"lA==\"": { "status": "PASS" }, "btoa(\"•\") == \"lQ==\"": { "status": "PASS" }, "btoa(\"–\") == \"lg==\"": { "status": "PASS" }, "btoa(\"—\") == \"lw==\"": { "status": "PASS" }, "btoa(\"˜\") == \"mA==\"": { "status": "PASS" }, "btoa(\"™\") == \"mQ==\"": { "status": "PASS" }, "btoa(\"š\") == \"mg==\"": { "status": "PASS" }, "btoa(\"›\") == \"mw==\"": { "status": "PASS" }, "btoa(\"œ\") == \"nA==\"": { "status": "PASS" }, "btoa(\"\") == \"nQ==\"": { "status": "PASS" }, "btoa(\"ž\") == \"ng==\"": { "status": "PASS" }, "btoa(\"Ÿ\") == \"nw==\"": { "status": "PASS" }, "btoa(\" \") == \"oA==\"": { "status": "PASS" }, "btoa(\"¡\") == \"oQ==\"": { "status": "PASS" }, "btoa(\"¢\") == \"og==\"": { "status": "PASS" }, "btoa(\"£\") == \"ow==\"": { "status": "PASS" }, "btoa(\"¤\") == \"pA==\"": { "status": "PASS" }, "btoa(\"¥\") == \"pQ==\"": { "status": "PASS" }, "btoa(\"¦\") == \"pg==\"": { "status": "PASS" }, "btoa(\"§\") == \"pw==\"": { "status": "PASS" }, "btoa(\"¨\") == \"qA==\"": { "status": "PASS" }, "btoa(\"©\") == \"qQ==\"": { "status": "PASS" }, "btoa(\"ª\") == \"qg==\"": { "status": "PASS" }, "btoa(\"«\") == \"qw==\"": { "status": "PASS" }, "btoa(\"¬\") == \"rA==\"": { "status": "PASS" }, "btoa(\"­\") == \"rQ==\"": { "status": "PASS" }, "btoa(\"®\") == \"rg==\"": { "status": "PASS" }, "btoa(\"¯\") == \"rw==\"": { "status": "PASS" }, "btoa(\"°\") == \"sA==\"": { "status": "PASS" }, "btoa(\"±\") == \"sQ==\"": { "status": "PASS" }, "btoa(\"²\") == \"sg==\"": { "status": "PASS" }, "btoa(\"³\") == \"sw==\"": { "status": "PASS" }, "btoa(\"´\") == \"tA==\"": { "status": "PASS" }, "btoa(\"µ\") == \"tQ==\"": { "status": "PASS" }, "btoa(\"¶\") == \"tg==\"": { "status": "PASS" }, "btoa(\"·\") == \"tw==\"": { "status": "PASS" }, "btoa(\"¸\") == \"uA==\"": { "status": "PASS" }, "btoa(\"¹\") == \"uQ==\"": { "status": "PASS" }, "btoa(\"º\") == \"ug==\"": { "status": "PASS" }, "btoa(\"»\") == \"uw==\"": { "status": "PASS" }, "btoa(\"¼\") == \"vA==\"": { "status": "PASS" }, "btoa(\"½\") == \"vQ==\"": { "status": "PASS" }, "btoa(\"¾\") == \"vg==\"": { "status": "PASS" }, "btoa(\"¿\") == \"vw==\"": { "status": "PASS" }, "btoa(\"À\") == \"wA==\"": { "status": "PASS" }, "btoa(\"Á\") == \"wQ==\"": { "status": "PASS" }, "btoa(\"Â\") == \"wg==\"": { "status": "PASS" }, "btoa(\"Ã\") == \"ww==\"": { "status": "PASS" }, "btoa(\"Ä\") == \"xA==\"": { "status": "PASS" }, "btoa(\"Å\") == \"xQ==\"": { "status": "PASS" }, "btoa(\"Æ\") == \"xg==\"": { "status": "PASS" }, "btoa(\"Ç\") == \"xw==\"": { "status": "PASS" }, "btoa(\"È\") == \"yA==\"": { "status": "PASS" }, "btoa(\"É\") == \"yQ==\"": { "status": "PASS" }, "btoa(\"Ê\") == \"yg==\"": { "status": "PASS" }, "btoa(\"Ë\") == \"yw==\"": { "status": "PASS" }, "btoa(\"Ì\") == \"zA==\"": { "status": "PASS" }, "btoa(\"Í\") == \"zQ==\"": { "status": "PASS" }, "btoa(\"Î\") == \"zg==\"": { "status": "PASS" }, "btoa(\"Ï\") == \"zw==\"": { "status": "PASS" }, "btoa(\"Ð\") == \"0A==\"": { "status": "PASS" }, "btoa(\"Ñ\") == \"0Q==\"": { "status": "PASS" }, "btoa(\"Ò\") == \"0g==\"": { "status": "PASS" }, "btoa(\"Ó\") == \"0w==\"": { "status": "PASS" }, "btoa(\"Ô\") == \"1A==\"": { "status": "PASS" }, "btoa(\"Õ\") == \"1Q==\"": { "status": "PASS" }, "btoa(\"Ö\") == \"1g==\"": { "status": "PASS" }, "btoa(\"×\") == \"1w==\"": { "status": "PASS" }, "btoa(\"Ø\") == \"2A==\"": { "status": "PASS" }, "btoa(\"Ù\") == \"2Q==\"": { "status": "PASS" }, "btoa(\"Ú\") == \"2g==\"": { "status": "PASS" }, "btoa(\"Û\") == \"2w==\"": { "status": "PASS" }, "btoa(\"Ü\") == \"3A==\"": { "status": "PASS" }, "btoa(\"Ý\") == \"3Q==\"": { "status": "PASS" }, "btoa(\"Þ\") == \"3g==\"": { "status": "PASS" }, "btoa(\"ß\") == \"3w==\"": { "status": "PASS" }, "btoa(\"à\") == \"4A==\"": { "status": "PASS" }, "btoa(\"á\") == \"4Q==\"": { "status": "PASS" }, "btoa(\"â\") == \"4g==\"": { "status": "PASS" }, "btoa(\"ã\") == \"4w==\"": { "status": "PASS" }, "btoa(\"ä\") == \"5A==\"": { "status": "PASS" }, "btoa(\"å\") == \"5Q==\"": { "status": "PASS" }, "btoa(\"æ\") == \"5g==\"": { "status": "PASS" }, "btoa(\"ç\") == \"5w==\"": { "status": "PASS" }, "btoa(\"è\") == \"6A==\"": { "status": "PASS" }, "btoa(\"é\") == \"6Q==\"": { "status": "PASS" }, "btoa(\"ê\") == \"6g==\"": { "status": "PASS" }, "btoa(\"ë\") == \"6w==\"": { "status": "PASS" }, "btoa(\"ì\") == \"7A==\"": { "status": "PASS" }, "btoa(\"í\") == \"7Q==\"": { "status": "PASS" }, "btoa(\"î\") == \"7g==\"": { "status": "PASS" }, "btoa(\"ï\") == \"7w==\"": { "status": "PASS" }, "btoa(\"ð\") == \"8A==\"": { "status": "PASS" }, "btoa(\"ñ\") == \"8Q==\"": { "status": "PASS" }, "btoa(\"ò\") == \"8g==\"": { "status": "PASS" }, "btoa(\"ó\") == \"8w==\"": { "status": "PASS" }, "btoa(\"ô\") == \"9A==\"": { "status": "PASS" }, "btoa(\"õ\") == \"9Q==\"": { "status": "PASS" }, "btoa(\"ö\") == \"9g==\"": { "status": "PASS" }, "btoa(\"÷\") == \"9w==\"": { "status": "PASS" }, "btoa(\"ø\") == \"+A==\"": { "status": "PASS" }, "btoa(\"ù\") == \"+Q==\"": { "status": "PASS" }, "btoa(\"ú\") == \"+g==\"": { "status": "PASS" }, "btoa(\"û\") == \"+w==\"": { "status": "PASS" }, "btoa(\"ü\") == \"/A==\"": { "status": "PASS" }, "btoa(\"ý\") == \"/Q==\"": { "status": "PASS" }, "btoa(\"þ\") == \"/g==\"": { "status": "PASS" }, "btoa(\"ÿ\") == \"/w==\"": { "status": "PASS" }, "btoa(\"Ā\") must raise INVALID_CHARACTER_ERR": { "status": "FAIL" }, "btoa(\"ā\") must raise INVALID_CHARACTER_ERR": { "status": "FAIL" }, "btoa(\"✐\") must raise INVALID_CHARACTER_ERR": { "status": "FAIL" }, "btoa(\"\\ufffe\") must raise INVALID_CHARACTER_ERR": { "status": "FAIL" }, "btoa(\"\\uffff\") must raise INVALID_CHARACTER_ERR": { "status": "FAIL" }, "btoa(\"𐀀\") must raise INVALID_CHARACTER_ERR": { "status": "FAIL" }, "btoa(first 256 code points concatenated)": { "status": "PASS" }, "atob() setup.": { "status": "PASS" }, "atob(\"\")": { "status": "PASS" }, "atob(\"abcd\")": { "status": "PASS" }, "atob(\" abcd\")": { "status": "PASS" }, "atob(\"abcd \")": { "status": "PASS" }, "atob(\" abcd===\")": { "status": "FAIL" }, "atob(\"abcd=== \")": { "status": "FAIL" }, "atob(\"abcd ===\")": { "status": "FAIL" }, "atob(\"a\")": { "status": "FAIL" }, "atob(\"ab\")": { "status": "PASS" }, "atob(\"abc\")": { "status": "PASS" }, "atob(\"abcde\")": { "status": "FAIL" }, "atob(\"𐀀\")": { "status": "FAIL" }, "atob(\"=\")": { "status": "FAIL" }, "atob(\"==\")": { "status": "FAIL" }, "atob(\"===\")": { "status": "FAIL" }, "atob(\"====\")": { "status": "FAIL" }, "atob(\"=====\")": { "status": "FAIL" }, "atob(\"a=\")": { "status": "FAIL" }, "atob(\"a==\")": { "status": "FAIL" }, "atob(\"a===\")": { "status": "FAIL" }, "atob(\"a====\")": { "status": "FAIL" }, "atob(\"a=====\")": { "status": "FAIL" }, "atob(\"ab=\")": { "status": "FAIL" }, "atob(\"ab==\")": { "status": "PASS" }, "atob(\"ab===\")": { "status": "FAIL" }, "atob(\"ab====\")": { "status": "FAIL" }, "atob(\"ab=====\")": { "status": "FAIL" }, "atob(\"abc=\")": { "status": "PASS" }, "atob(\"abc==\")": { "status": "FAIL" }, "atob(\"abc===\")": { "status": "FAIL" }, "atob(\"abc====\")": { "status": "FAIL" }, "atob(\"abc=====\")": { "status": "FAIL" }, "atob(\"abcd=\")": { "status": "FAIL" }, "atob(\"abcd==\")": { "status": "FAIL" }, "atob(\"abcd===\")": { "status": "FAIL" }, "atob(\"abcd====\")": { "status": "FAIL" }, "atob(\"abcd=====\")": { "status": "FAIL" }, "atob(\"abcde=\")": { "status": "FAIL" }, "atob(\"abcde==\")": { "status": "FAIL" }, "atob(\"abcde===\")": { "status": "FAIL" }, "atob(\"abcde====\")": { "status": "FAIL" }, "atob(\"abcde=====\")": { "status": "FAIL" }, "atob(\"=a\")": { "status": "FAIL" }, "atob(\"=a=\")": { "status": "FAIL" }, "atob(\"a=b\")": { "status": "FAIL" }, "atob(\"a=b=\")": { "status": "FAIL" }, "atob(\"ab=c\")": { "status": "FAIL" }, "atob(\"ab=c=\")": { "status": "FAIL" }, "atob(\"abc=d\")": { "status": "FAIL" }, "atob(\"abc=d=\")": { "status": "FAIL" }, "atob(\"ab\\vcd\")": { "status": "FAIL" }, "atob(\"ab cd\")": { "status": "FAIL" }, "atob(\"ab、cd\")": { "status": "FAIL" }, "atob(\"ab\\tcd\")": { "status": "PASS" }, "atob(\"ab\\ncd\")": { "status": "PASS" }, "atob(\"ab\\fcd\")": { "status": "PASS" }, "atob(\"ab\\rcd\")": { "status": "PASS" }, "atob(\"ab cd\")": { "status": "PASS" }, "atob(\"ab cd\")": { "status": "FAIL" }, "atob(\"ab\\t\\n\\f\\r cd\")": { "status": "PASS" }, "atob(\" \\t\\n\\f\\r ab\\t\\n\\f\\r cd\\t\\n\\f\\r \")": { "status": "PASS" }, "atob(\"ab\\t\\n\\f\\r =\\t\\n\\f\\r =\\t\\n\\f\\r \")": { "status": "PASS" }, "atob(\"A\")": { "status": "FAIL" }, "atob(\"/A\")": { "status": "PASS" }, "atob(\"//A\")": { "status": "PASS" }, "atob(\"///A\")": { "status": "PASS" }, "atob(\"////A\")": { "status": "FAIL" }, "atob(\"/\")": { "status": "FAIL" }, "atob(\"A/\")": { "status": "PASS" }, "atob(\"AA/\")": { "status": "PASS" }, "atob(\"AAAA/\")": { "status": "FAIL" }, "atob(\"AAA/\")": { "status": "PASS" }, "atob(\"\\0nonsense\")": { "status": "FAIL" }, "atob(\"abcd\\0nonsense\")": { "status": "FAIL" }, "atob(\"YQ\")": { "status": "PASS" }, "atob(\"YR\")": { "status": "PASS" }, "atob(\"~~\")": { "status": "FAIL" }, "atob(\"..\")": { "status": "FAIL" }, "atob(\"--\")": { "status": "FAIL" }, "atob(\"__\")": { "status": "FAIL" }, "atob(undefined)": { "status": "FAIL" }, "atob(null)": { "status": "PASS" }, "atob(7)": { "status": "FAIL" }, "atob(12)": { "status": "PASS" }, "atob(1.5)": { "status": "FAIL" }, "atob(true)": { "status": "PASS" }, "atob(false)": { "status": "FAIL" }, "atob(NaN)": { "status": "PASS" }, "atob(Infinity)": { "status": "PASS" }, "atob(-Infinity)": { "status": "FAIL" }, "atob(0)": { "status": "FAIL" }, "atob(-0)": { "status": "FAIL" }, "atob(object \"foo\")": { "status": "PASS" }, "atob(object \"abcd\")": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/html/webappapis/structured-clone/structured-clone.any.js.json ================================================ { "primitive undefined": { "status": "PASS" }, "primitive null": { "status": "PASS" }, "primitive true": { "status": "PASS" }, "primitive false": { "status": "PASS" }, "primitive string, empty string": { "status": "PASS" }, "primitive string, lone high surrogate": { "status": "PASS" }, "primitive string, lone low surrogate": { "status": "PASS" }, "primitive string, NUL": { "status": "PASS" }, "primitive string, astral character": { "status": "PASS" }, "primitive number, 0.2": { "status": "PASS" }, "primitive number, 0": { "status": "PASS" }, "primitive number, -0": { "status": "PASS" }, "primitive number, NaN": { "status": "PASS" }, "primitive number, Infinity": { "status": "PASS" }, "primitive number, -Infinity": { "status": "PASS" }, "primitive number, 9007199254740992": { "status": "PASS" }, "primitive number, -9007199254740992": { "status": "PASS" }, "primitive number, 9007199254740994": { "status": "PASS" }, "primitive number, -9007199254740994": { "status": "PASS" }, "primitive BigInt, 0n": { "status": "PASS" }, "primitive BigInt, -0n": { "status": "PASS" }, "primitive BigInt, -9007199254740994000n": { "status": "PASS" }, "primitive BigInt, -9007199254740994000900719925474099400090071992547409940009007199254740994000n": { "status": "PASS" }, "Array primitives": { "status": "PASS" }, "Object primitives": { "status": "PASS" }, "Boolean true": { "status": "PASS" }, "Boolean false": { "status": "PASS" }, "Array Boolean objects": { "status": "PASS" }, "Object Boolean objects": { "status": "PASS" }, "String empty string": { "status": "PASS" }, "String lone high surrogate": { "status": "PASS" }, "String lone low surrogate": { "status": "PASS" }, "String NUL": { "status": "PASS" }, "String astral character": { "status": "PASS" }, "Array String objects": { "status": "PASS" }, "Object String objects": { "status": "PASS" }, "Number 0.2": { "status": "PASS" }, "Number 0": { "status": "PASS" }, "Number -0": { "status": "PASS" }, "Number NaN": { "status": "PASS" }, "Number Infinity": { "status": "PASS" }, "Number -Infinity": { "status": "PASS" }, "Number 9007199254740992": { "status": "PASS" }, "Number -9007199254740992": { "status": "PASS" }, "Number 9007199254740994": { "status": "PASS" }, "Number -9007199254740994": { "status": "PASS" }, "BigInt -9007199254740994n": { "status": "PASS" }, "Array Number objects": { "status": "PASS" }, "Object Number objects": { "status": "PASS" }, "Date 0": { "status": "PASS" }, "Date -0": { "status": "PASS" }, "Date -8.64e15": { "status": "PASS" }, "Date 8.64e15": { "status": "PASS" }, "Array Date objects": { "status": "PASS" }, "Object Date objects": { "status": "PASS" }, "RegExp flags and lastIndex": { "status": "PASS" }, "RegExp sticky flag": { "status": "PASS" }, "RegExp unicode flag": { "status": "PASS" }, "RegExp empty": { "status": "PASS" }, "RegExp slash": { "status": "PASS" }, "RegExp new line": { "status": "PASS" }, "Array RegExp object, RegExp flags and lastIndex": { "status": "PASS" }, "Array RegExp object, RegExp sticky flag": { "status": "PASS" }, "Array RegExp object, RegExp unicode flag": { "status": "PASS" }, "Array RegExp object, RegExp empty": { "status": "PASS" }, "Array RegExp object, RegExp slash": { "status": "PASS" }, "Array RegExp object, RegExp new line": { "status": "PASS" }, "Object RegExp object, RegExp flags and lastIndex": { "status": "PASS" }, "Object RegExp object, RegExp sticky flag": { "status": "PASS" }, "Object RegExp object, RegExp unicode flag": { "status": "PASS" }, "Object RegExp object, RegExp empty": { "status": "PASS" }, "Object RegExp object, RegExp slash": { "status": "PASS" }, "Object RegExp object, RegExp new line": { "status": "PASS" }, "Empty Error object": { "status": "PASS" }, "Error object": { "status": "PASS" }, "EvalError object": { "status": "PASS" }, "RangeError object": { "status": "PASS" }, "ReferenceError object": { "status": "PASS" }, "SyntaxError object": { "status": "PASS" }, "TypeError object": { "status": "PASS" }, "URIError object": { "status": "PASS" }, "Blob basic": { "status": "FAIL" }, "Blob unpaired high surrogate (invalid utf-8)": { "status": "PASS" }, "Blob unpaired low surrogate (invalid utf-8)": { "status": "PASS" }, "Blob paired surrogates (invalid utf-8)": { "status": "PASS" }, "Blob empty": { "status": "PASS" }, "Blob NUL": { "status": "PASS" }, "Array Blob object, Blob basic": { "status": "FAIL" }, "Array Blob object, Blob unpaired high surrogate (invalid utf-8)": { "status": "PASS" }, "Array Blob object, Blob unpaired low surrogate (invalid utf-8)": { "status": "PASS" }, "Array Blob object, Blob paired surrogates (invalid utf-8)": { "status": "PASS" }, "Array Blob object, Blob empty": { "status": "PASS" }, "Array Blob object, Blob NUL": { "status": "PASS" }, "Array Blob object, two Blobs": { "status": "FAIL" }, "Object Blob object, Blob basic": { "status": "FAIL" }, "Object Blob object, Blob unpaired high surrogate (invalid utf-8)": { "status": "PASS" }, "Object Blob object, Blob unpaired low surrogate (invalid utf-8)": { "status": "PASS" }, "Object Blob object, Blob paired surrogates (invalid utf-8)": { "status": "PASS" }, "Object Blob object, Blob empty": { "status": "PASS" }, "Object Blob object, Blob NUL": { "status": "PASS" }, "File basic": { "status": "FAIL" }, "Array sparse": { "status": "PASS" }, "Array with non-index property": { "status": "PASS" }, "Object with index property and length": { "status": "PASS" }, "Array with circular reference": { "status": "PASS" }, "Object with circular reference": { "status": "PASS" }, "Array with identical property values": { "status": "PASS" }, "Object with identical property values": { "status": "PASS" }, "Object with property on prototype": { "status": "PASS" }, "Object with non-enumerable property": { "status": "PASS" }, "Object with non-writable property": { "status": "PASS" }, "Object with non-configurable property": { "status": "PASS" }, "Object with a getter that throws": { "status": "PASS" }, "ObjectPrototype must lose its exotic-ness when cloned": { "status": "PASS" }, "Serializing a non-serializable platform object fails": { "status": "PASS" }, "An object whose interface is deleted from the global must still deserialize": { "status": "PASS" }, "A subclass instance will deserialize as its closest serializable superclass": { "status": "FAIL" }, "Resizable ArrayBuffer": { "status": "PASS" }, "Growable SharedArrayBuffer": { "status": "FAIL" }, "Length-tracking TypedArray": { "status": "PASS" }, "Length-tracking DataView": { "status": "PASS" }, "Serializing OOB TypedArray throws": { "status": "FAIL" }, "Serializing OOB DataView throws": { "status": "FAIL" }, "ArrayBuffer": { "status": "PASS" }, "MessagePort": { "status": "FAIL" }, "A detached ArrayBuffer cannot be transferred": { "status": "FAIL" }, "A detached platform object cannot be transferred": { "status": "FAIL" }, "Transferring a non-transferable platform object fails": { "status": "FAIL" }, "An object whose interface is deleted from the global object must still be received": { "status": "FAIL" }, "A subclass instance will be received as its closest transferable superclass": { "status": "FAIL" }, "Resizable ArrayBuffer is transferable": { "status": "PASS" }, "Length-tracking TypedArray is transferable": { "status": "PASS" }, "Length-tracking DataView is transferable": { "status": "PASS" }, "Transferring OOB TypedArray throws": { "status": "FAIL" }, "Transferring OOB DataView throws": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/html/webappapis/timers/clearinterval-from-callback.any.js.json ================================================ { "Clearing an interval from the callback should still clear it.": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/html/webappapis/timers/cleartimeout-clearinterval.any.js.json ================================================ { "Clear timeout with clearInterval": { "status": "PASS" }, "Clear interval with clearTimeout": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/html/webappapis/timers/missing-timeout-setinterval.any.js.json ================================================ { "Calling setInterval with no interval should be the same as if called with 0 interval": { "status": "PASS" }, "Calling setInterval with undefined interval should be the same as if called with 0 interval": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/html/webappapis/timers/negative-setinterval.any.js.json ================================================ { "negative-setinterval": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/html/webappapis/timers/negative-settimeout.any.js.json ================================================ { "negative-settimeout": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/html/webappapis/timers/type-long-setinterval.any.js.json ================================================ { "type-long-setinterval": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/html/webappapis/timers/type-long-settimeout.any.js.json ================================================ { "type-long-settimeout": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/idlharness.any.js.json ================================================ { "idl_test setup": { "status": "PASS" }, "idl_test validation": { "status": "PASS" }, "ReadableStreamDefaultReader includes ReadableStreamGenericReader: member names are unique": { "status": "PASS" }, "ReadableStreamBYOBReader includes ReadableStreamGenericReader: member names are unique": { "status": "PASS" }, "ReadableStream interface: existence and properties of interface object": { "status": "PASS" }, "ReadableStream interface object length": { "status": "PASS" }, "ReadableStream interface object name": { "status": "PASS" }, "ReadableStream interface: existence and properties of interface prototype object": { "status": "PASS" }, "ReadableStream interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "ReadableStream interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "ReadableStream interface: operation from(any)": { "status": "FAIL" }, "ReadableStream interface: attribute locked": { "status": "PASS" }, "ReadableStream interface: operation cancel(optional any)": { "status": "PASS" }, "ReadableStream interface: operation getReader(optional ReadableStreamGetReaderOptions)": { "status": "PASS" }, "ReadableStream interface: operation pipeThrough(ReadableWritablePair, optional StreamPipeOptions)": { "status": "PASS" }, "ReadableStream interface: operation pipeTo(WritableStream, optional StreamPipeOptions)": { "status": "FAIL" }, "ReadableStream interface: operation tee()": { "status": "PASS" }, "ReadableStream interface: async iterable": { "status": "FAIL" }, "ReadableStream must be primary interface of new ReadableStream()": { "status": "PASS" }, "Stringification of new ReadableStream()": { "status": "PASS" }, "ReadableStream interface: new ReadableStream() must inherit property \"from(any)\" with the proper type": { "status": "PASS" }, "ReadableStream interface: calling from(any) on new ReadableStream() with too few arguments must throw TypeError": { "status": "FAIL" }, "ReadableStream interface: new ReadableStream() must inherit property \"locked\" with the proper type": { "status": "PASS" }, "ReadableStream interface: new ReadableStream() must inherit property \"cancel(optional any)\" with the proper type": { "status": "PASS" }, "ReadableStream interface: calling cancel(optional any) on new ReadableStream() with too few arguments must throw TypeError": { "status": "PASS" }, "ReadableStream interface: new ReadableStream() must inherit property \"getReader(optional ReadableStreamGetReaderOptions)\" with the proper type": { "status": "PASS" }, "ReadableStream interface: calling getReader(optional ReadableStreamGetReaderOptions) on new ReadableStream() with too few arguments must throw TypeError": { "status": "PASS" }, "ReadableStream interface: new ReadableStream() must inherit property \"pipeThrough(ReadableWritablePair, optional StreamPipeOptions)\" with the proper type": { "status": "PASS" }, "ReadableStream interface: calling pipeThrough(ReadableWritablePair, optional StreamPipeOptions) on new ReadableStream() with too few arguments must throw TypeError": { "status": "PASS" }, "ReadableStream interface: new ReadableStream() must inherit property \"pipeTo(WritableStream, optional StreamPipeOptions)\" with the proper type": { "status": "PASS" }, "ReadableStream interface: calling pipeTo(WritableStream, optional StreamPipeOptions) on new ReadableStream() with too few arguments must throw TypeError": { "status": "FAIL" }, "ReadableStream interface: new ReadableStream() must inherit property \"tee()\" with the proper type": { "status": "PASS" }, "ReadableStreamDefaultReader interface: existence and properties of interface object": { "status": "PASS" }, "ReadableStreamDefaultReader interface object length": { "status": "PASS" }, "ReadableStreamDefaultReader interface object name": { "status": "PASS" }, "ReadableStreamDefaultReader interface: existence and properties of interface prototype object": { "status": "PASS" }, "ReadableStreamDefaultReader interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "ReadableStreamDefaultReader interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "ReadableStreamDefaultReader interface: operation read()": { "status": "FAIL" }, "ReadableStreamDefaultReader interface: operation releaseLock()": { "status": "FAIL" }, "ReadableStreamDefaultReader interface: attribute closed": { "status": "FAIL" }, "ReadableStreamDefaultReader interface: operation cancel(optional any)": { "status": "FAIL" }, "ReadableStreamDefaultReader must be primary interface of (new ReadableStream()).getReader()": { "status": "PASS" }, "Stringification of (new ReadableStream()).getReader()": { "status": "FAIL" }, "ReadableStreamDefaultReader interface: (new ReadableStream()).getReader() must inherit property \"read()\" with the proper type": { "status": "PASS" }, "ReadableStreamDefaultReader interface: (new ReadableStream()).getReader() must inherit property \"releaseLock()\" with the proper type": { "status": "PASS" }, "ReadableStreamDefaultReader interface: (new ReadableStream()).getReader() must inherit property \"closed\" with the proper type": { "status": "PASS" }, "ReadableStreamDefaultReader interface: (new ReadableStream()).getReader() must inherit property \"cancel(optional any)\" with the proper type": { "status": "PASS" }, "ReadableStreamDefaultReader interface: calling cancel(optional any) on (new ReadableStream()).getReader() with too few arguments must throw TypeError": { "status": "PASS" }, "ReadableStreamBYOBReader interface: existence and properties of interface object": { "status": "PASS" }, "ReadableStreamBYOBReader interface object length": { "status": "PASS" }, "ReadableStreamBYOBReader interface object name": { "status": "PASS" }, "ReadableStreamBYOBReader interface: existence and properties of interface prototype object": { "status": "PASS" }, "ReadableStreamBYOBReader interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "ReadableStreamBYOBReader interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "ReadableStreamBYOBReader interface: operation read(ArrayBufferView, optional ReadableStreamBYOBReaderReadOptions)": { "status": "FAIL" }, "ReadableStreamBYOBReader interface: operation releaseLock()": { "status": "FAIL" }, "ReadableStreamBYOBReader interface: attribute closed": { "status": "FAIL" }, "ReadableStreamBYOBReader interface: operation cancel(optional any)": { "status": "FAIL" }, "ReadableStreamBYOBReader must be primary interface of (new ReadableStream({ type: 'bytes' })).getReader({ mode: 'byob' })": { "status": "PASS" }, "Stringification of (new ReadableStream({ type: 'bytes' })).getReader({ mode: 'byob' })": { "status": "FAIL" }, "ReadableStreamBYOBReader interface: (new ReadableStream({ type: 'bytes' })).getReader({ mode: 'byob' }) must inherit property \"read(ArrayBufferView, optional ReadableStreamBYOBReaderReadOptions)\" with the proper type": { "status": "PASS" }, "ReadableStreamBYOBReader interface: calling read(ArrayBufferView, optional ReadableStreamBYOBReaderReadOptions) on (new ReadableStream({ type: 'bytes' })).getReader({ mode: 'byob' }) with too few arguments must throw TypeError": { "status": "PASS" }, "ReadableStreamBYOBReader interface: (new ReadableStream({ type: 'bytes' })).getReader({ mode: 'byob' }) must inherit property \"releaseLock()\" with the proper type": { "status": "PASS" }, "ReadableStreamBYOBReader interface: (new ReadableStream({ type: 'bytes' })).getReader({ mode: 'byob' }) must inherit property \"closed\" with the proper type": { "status": "PASS" }, "ReadableStreamBYOBReader interface: (new ReadableStream({ type: 'bytes' })).getReader({ mode: 'byob' }) must inherit property \"cancel(optional any)\" with the proper type": { "status": "PASS" }, "ReadableStreamBYOBReader interface: calling cancel(optional any) on (new ReadableStream({ type: 'bytes' })).getReader({ mode: 'byob' }) with too few arguments must throw TypeError": { "status": "PASS" }, "ReadableStreamDefaultController interface: existence and properties of interface object": { "status": "PASS" }, "ReadableStreamDefaultController interface object length": { "status": "PASS" }, "ReadableStreamDefaultController interface object name": { "status": "PASS" }, "ReadableStreamDefaultController interface: existence and properties of interface prototype object": { "status": "PASS" }, "ReadableStreamDefaultController interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "ReadableStreamDefaultController interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "ReadableStreamDefaultController interface: attribute desiredSize": { "status": "FAIL" }, "ReadableStreamDefaultController interface: operation close()": { "status": "FAIL" }, "ReadableStreamDefaultController interface: operation enqueue(optional any)": { "status": "FAIL" }, "ReadableStreamDefaultController interface: operation error(optional any)": { "status": "FAIL" }, "ReadableStreamDefaultController must be primary interface of self.readableStreamDefaultController": { "status": "PASS" }, "Stringification of self.readableStreamDefaultController": { "status": "FAIL" }, "ReadableStreamDefaultController interface: self.readableStreamDefaultController must inherit property \"desiredSize\" with the proper type": { "status": "PASS" }, "ReadableStreamDefaultController interface: self.readableStreamDefaultController must inherit property \"close()\" with the proper type": { "status": "PASS" }, "ReadableStreamDefaultController interface: self.readableStreamDefaultController must inherit property \"enqueue(optional any)\" with the proper type": { "status": "PASS" }, "ReadableStreamDefaultController interface: calling enqueue(optional any) on self.readableStreamDefaultController with too few arguments must throw TypeError": { "status": "PASS" }, "ReadableStreamDefaultController interface: self.readableStreamDefaultController must inherit property \"error(optional any)\" with the proper type": { "status": "PASS" }, "ReadableStreamDefaultController interface: calling error(optional any) on self.readableStreamDefaultController with too few arguments must throw TypeError": { "status": "PASS" }, "ReadableByteStreamController interface: existence and properties of interface object": { "status": "PASS" }, "ReadableByteStreamController interface object length": { "status": "PASS" }, "ReadableByteStreamController interface object name": { "status": "PASS" }, "ReadableByteStreamController interface: existence and properties of interface prototype object": { "status": "PASS" }, "ReadableByteStreamController interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "ReadableByteStreamController interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "ReadableByteStreamController interface: attribute byobRequest": { "status": "FAIL" }, "ReadableByteStreamController interface: attribute desiredSize": { "status": "FAIL" }, "ReadableByteStreamController interface: operation close()": { "status": "FAIL" }, "ReadableByteStreamController interface: operation enqueue(ArrayBufferView)": { "status": "FAIL" }, "ReadableByteStreamController interface: operation error(optional any)": { "status": "FAIL" }, "ReadableByteStreamController must be primary interface of self.readableByteStreamController": { "status": "PASS" }, "Stringification of self.readableByteStreamController": { "status": "FAIL" }, "ReadableByteStreamController interface: self.readableByteStreamController must inherit property \"byobRequest\" with the proper type": { "status": "PASS" }, "ReadableByteStreamController interface: self.readableByteStreamController must inherit property \"desiredSize\" with the proper type": { "status": "PASS" }, "ReadableByteStreamController interface: self.readableByteStreamController must inherit property \"close()\" with the proper type": { "status": "PASS" }, "ReadableByteStreamController interface: self.readableByteStreamController must inherit property \"enqueue(ArrayBufferView)\" with the proper type": { "status": "PASS" }, "ReadableByteStreamController interface: calling enqueue(ArrayBufferView) on self.readableByteStreamController with too few arguments must throw TypeError": { "status": "PASS" }, "ReadableByteStreamController interface: self.readableByteStreamController must inherit property \"error(optional any)\" with the proper type": { "status": "PASS" }, "ReadableByteStreamController interface: calling error(optional any) on self.readableByteStreamController with too few arguments must throw TypeError": { "status": "PASS" }, "ReadableStreamBYOBRequest interface: existence and properties of interface object": { "status": "PASS" }, "ReadableStreamBYOBRequest interface object length": { "status": "PASS" }, "ReadableStreamBYOBRequest interface object name": { "status": "PASS" }, "ReadableStreamBYOBRequest interface: existence and properties of interface prototype object": { "status": "PASS" }, "ReadableStreamBYOBRequest interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "ReadableStreamBYOBRequest interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "ReadableStreamBYOBRequest interface: attribute view": { "status": "FAIL" }, "ReadableStreamBYOBRequest interface: operation respond(unsigned long long)": { "status": "FAIL" }, "ReadableStreamBYOBRequest interface: operation respondWithNewView(ArrayBufferView)": { "status": "FAIL" }, "ReadableStreamBYOBRequest must be primary interface of self.readableStreamByobRequest": { "status": "PASS" }, "Stringification of self.readableStreamByobRequest": { "status": "FAIL" }, "ReadableStreamBYOBRequest interface: self.readableStreamByobRequest must inherit property \"view\" with the proper type": { "status": "PASS" }, "ReadableStreamBYOBRequest interface: self.readableStreamByobRequest must inherit property \"respond(unsigned long long)\" with the proper type": { "status": "PASS" }, "ReadableStreamBYOBRequest interface: calling respond(unsigned long long) on self.readableStreamByobRequest with too few arguments must throw TypeError": { "status": "FAIL" }, "ReadableStreamBYOBRequest interface: self.readableStreamByobRequest must inherit property \"respondWithNewView(ArrayBufferView)\" with the proper type": { "status": "PASS" }, "ReadableStreamBYOBRequest interface: calling respondWithNewView(ArrayBufferView) on self.readableStreamByobRequest with too few arguments must throw TypeError": { "status": "PASS" }, "WritableStream interface: existence and properties of interface object": { "status": "PASS" }, "WritableStream interface object length": { "status": "PASS" }, "WritableStream interface object name": { "status": "PASS" }, "WritableStream interface: existence and properties of interface prototype object": { "status": "PASS" }, "WritableStream interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "WritableStream interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "WritableStream interface: attribute locked": { "status": "FAIL" }, "WritableStream interface: operation abort(optional any)": { "status": "FAIL" }, "WritableStream interface: operation close()": { "status": "FAIL" }, "WritableStream interface: operation getWriter()": { "status": "FAIL" }, "WritableStream must be primary interface of new WritableStream()": { "status": "PASS" }, "Stringification of new WritableStream()": { "status": "FAIL" }, "WritableStream interface: new WritableStream() must inherit property \"locked\" with the proper type": { "status": "PASS" }, "WritableStream interface: new WritableStream() must inherit property \"abort(optional any)\" with the proper type": { "status": "PASS" }, "WritableStream interface: calling abort(optional any) on new WritableStream() with too few arguments must throw TypeError": { "status": "PASS" }, "WritableStream interface: new WritableStream() must inherit property \"close()\" with the proper type": { "status": "PASS" }, "WritableStream interface: new WritableStream() must inherit property \"getWriter()\" with the proper type": { "status": "PASS" }, "WritableStreamDefaultWriter interface: existence and properties of interface object": { "status": "FAIL" }, "WritableStreamDefaultWriter interface object length": { "status": "FAIL" }, "WritableStreamDefaultWriter interface object name": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: existence and properties of interface prototype object": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: existence and properties of interface prototype object's @@unscopables property": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: attribute closed": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: attribute desiredSize": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: attribute ready": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: operation abort(optional any)": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: operation close()": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: operation releaseLock()": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: operation write(optional any)": { "status": "FAIL" }, "WritableStreamDefaultWriter must be primary interface of (new WritableStream()).getWriter()": { "status": "FAIL" }, "Stringification of (new WritableStream()).getWriter()": { "status": "FAIL" }, "WritableStreamDefaultWriter interface: (new WritableStream()).getWriter() must inherit property \"closed\" with the proper type": { "status": "PASS" }, "WritableStreamDefaultWriter interface: (new WritableStream()).getWriter() must inherit property \"desiredSize\" with the proper type": { "status": "PASS" }, "WritableStreamDefaultWriter interface: (new WritableStream()).getWriter() must inherit property \"ready\" with the proper type": { "status": "PASS" }, "WritableStreamDefaultWriter interface: (new WritableStream()).getWriter() must inherit property \"abort(optional any)\" with the proper type": { "status": "PASS" }, "WritableStreamDefaultWriter interface: calling abort(optional any) on (new WritableStream()).getWriter() with too few arguments must throw TypeError": { "status": "PASS" }, "WritableStreamDefaultWriter interface: (new WritableStream()).getWriter() must inherit property \"close()\" with the proper type": { "status": "PASS" }, "WritableStreamDefaultWriter interface: (new WritableStream()).getWriter() must inherit property \"releaseLock()\" with the proper type": { "status": "PASS" }, "WritableStreamDefaultWriter interface: (new WritableStream()).getWriter() must inherit property \"write(optional any)\" with the proper type": { "status": "PASS" }, "WritableStreamDefaultWriter interface: calling write(optional any) on (new WritableStream()).getWriter() with too few arguments must throw TypeError": { "status": "PASS" }, "WritableStreamDefaultController interface: existence and properties of interface object": { "status": "FAIL" }, "WritableStreamDefaultController interface object length": { "status": "FAIL" }, "WritableStreamDefaultController interface object name": { "status": "FAIL" }, "WritableStreamDefaultController interface: existence and properties of interface prototype object": { "status": "FAIL" }, "WritableStreamDefaultController interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "FAIL" }, "WritableStreamDefaultController interface: existence and properties of interface prototype object's @@unscopables property": { "status": "FAIL" }, "WritableStreamDefaultController interface: attribute signal": { "status": "FAIL" }, "WritableStreamDefaultController interface: operation error(optional any)": { "status": "FAIL" }, "WritableStreamDefaultController must be primary interface of self.writableStreamDefaultController": { "status": "FAIL" }, "Stringification of self.writableStreamDefaultController": { "status": "FAIL" }, "WritableStreamDefaultController interface: self.writableStreamDefaultController must inherit property \"signal\" with the proper type": { "status": "FAIL" }, "WritableStreamDefaultController interface: self.writableStreamDefaultController must inherit property \"error(optional any)\" with the proper type": { "status": "PASS" }, "WritableStreamDefaultController interface: calling error(optional any) on self.writableStreamDefaultController with too few arguments must throw TypeError": { "status": "PASS" }, "TransformStream interface: existence and properties of interface object": { "status": "PASS" }, "TransformStream interface object length": { "status": "PASS" }, "TransformStream interface object name": { "status": "PASS" }, "TransformStream interface: existence and properties of interface prototype object": { "status": "PASS" }, "TransformStream interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "TransformStream interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "TransformStream interface: attribute readable": { "status": "FAIL" }, "TransformStream interface: attribute writable": { "status": "FAIL" }, "TransformStream must be primary interface of new TransformStream()": { "status": "PASS" }, "Stringification of new TransformStream()": { "status": "FAIL" }, "TransformStream interface: new TransformStream() must inherit property \"readable\" with the proper type": { "status": "PASS" }, "TransformStream interface: new TransformStream() must inherit property \"writable\" with the proper type": { "status": "PASS" }, "TransformStreamDefaultController interface: existence and properties of interface object": { "status": "FAIL" }, "TransformStreamDefaultController interface object length": { "status": "FAIL" }, "TransformStreamDefaultController interface object name": { "status": "FAIL" }, "TransformStreamDefaultController interface: existence and properties of interface prototype object": { "status": "FAIL" }, "TransformStreamDefaultController interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "FAIL" }, "TransformStreamDefaultController interface: existence and properties of interface prototype object's @@unscopables property": { "status": "FAIL" }, "TransformStreamDefaultController interface: attribute desiredSize": { "status": "FAIL" }, "TransformStreamDefaultController interface: operation enqueue(optional any)": { "status": "FAIL" }, "TransformStreamDefaultController interface: operation error(optional any)": { "status": "FAIL" }, "TransformStreamDefaultController interface: operation terminate()": { "status": "FAIL" }, "TransformStreamDefaultController must be primary interface of self.transformStreamDefaultController": { "status": "FAIL" }, "Stringification of self.transformStreamDefaultController": { "status": "FAIL" }, "TransformStreamDefaultController interface: self.transformStreamDefaultController must inherit property \"desiredSize\" with the proper type": { "status": "PASS" }, "TransformStreamDefaultController interface: self.transformStreamDefaultController must inherit property \"enqueue(optional any)\" with the proper type": { "status": "PASS" }, "TransformStreamDefaultController interface: calling enqueue(optional any) on self.transformStreamDefaultController with too few arguments must throw TypeError": { "status": "PASS" }, "TransformStreamDefaultController interface: self.transformStreamDefaultController must inherit property \"error(optional any)\" with the proper type": { "status": "PASS" }, "TransformStreamDefaultController interface: calling error(optional any) on self.transformStreamDefaultController with too few arguments must throw TypeError": { "status": "PASS" }, "TransformStreamDefaultController interface: self.transformStreamDefaultController must inherit property \"terminate()\" with the proper type": { "status": "PASS" }, "ByteLengthQueuingStrategy interface: existence and properties of interface object": { "status": "PASS" }, "ByteLengthQueuingStrategy interface object length": { "status": "PASS" }, "ByteLengthQueuingStrategy interface object name": { "status": "PASS" }, "ByteLengthQueuingStrategy interface: existence and properties of interface prototype object": { "status": "PASS" }, "ByteLengthQueuingStrategy interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "ByteLengthQueuingStrategy interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "ByteLengthQueuingStrategy interface: attribute highWaterMark": { "status": "PASS" }, "ByteLengthQueuingStrategy interface: attribute size": { "status": "FAIL" }, "ByteLengthQueuingStrategy must be primary interface of new ByteLengthQueuingStrategy({ highWaterMark: 5 })": { "status": "PASS" }, "Stringification of new ByteLengthQueuingStrategy({ highWaterMark: 5 })": { "status": "PASS" }, "ByteLengthQueuingStrategy interface: new ByteLengthQueuingStrategy({ highWaterMark: 5 }) must inherit property \"highWaterMark\" with the proper type": { "status": "PASS" }, "ByteLengthQueuingStrategy interface: new ByteLengthQueuingStrategy({ highWaterMark: 5 }) must inherit property \"size\" with the proper type": { "status": "PASS" }, "CountQueuingStrategy interface: existence and properties of interface object": { "status": "PASS" }, "CountQueuingStrategy interface object length": { "status": "PASS" }, "CountQueuingStrategy interface object name": { "status": "PASS" }, "CountQueuingStrategy interface: existence and properties of interface prototype object": { "status": "PASS" }, "CountQueuingStrategy interface: existence and properties of interface prototype object's \"constructor\" property": { "status": "PASS" }, "CountQueuingStrategy interface: existence and properties of interface prototype object's @@unscopables property": { "status": "PASS" }, "CountQueuingStrategy interface: attribute highWaterMark": { "status": "PASS" }, "CountQueuingStrategy interface: attribute size": { "status": "FAIL" }, "CountQueuingStrategy must be primary interface of new CountQueuingStrategy({ highWaterMark: 5 })": { "status": "PASS" }, "Stringification of new CountQueuingStrategy({ highWaterMark: 5 })": { "status": "PASS" }, "CountQueuingStrategy interface: new CountQueuingStrategy({ highWaterMark: 5 }) must inherit property \"highWaterMark\" with the proper type": { "status": "PASS" }, "CountQueuingStrategy interface: new CountQueuingStrategy({ highWaterMark: 5 }) must inherit property \"size\" with the proper type": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/close-propagation-backward.any.js.json ================================================ { "Closing must be propagated backward: starts closed; preventCancel omitted; fulfilled cancel promise": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel omitted; rejected cancel promise": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = undefined (falsy); fulfilled cancel promise": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = null (falsy); fulfilled cancel promise": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = false (falsy); fulfilled cancel promise": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = 0 (falsy); fulfilled cancel promise": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = -0 (falsy); fulfilled cancel promise": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = NaN (falsy); fulfilled cancel promise": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = (falsy); fulfilled cancel promise": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = true (truthy)": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = a (truthy)": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = 1 (truthy)": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = Symbol() (truthy)": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = [object Object] (truthy)": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = true, preventAbort = true": { "status": "PASS" }, "Closing must be propagated backward: starts closed; preventCancel = true, preventAbort = true, preventClose = true": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/close-propagation-forward.any.js.json ================================================ { "Closing must be propagated forward: starts closed; preventClose omitted; fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose omitted; rejected close promise": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = undefined (falsy); fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = null (falsy); fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = false (falsy); fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = 0 (falsy); fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = -0 (falsy); fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = NaN (falsy); fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = (falsy); fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = true (truthy)": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = a (truthy)": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = 1 (truthy)": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = Symbol() (truthy)": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = [object Object] (truthy)": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = true, preventAbort = true": { "status": "PASS" }, "Closing must be propagated forward: starts closed; preventClose = true, preventAbort = true, preventCancel = true": { "status": "PASS" }, "Closing must be propagated forward: becomes closed asynchronously; preventClose omitted; fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: becomes closed asynchronously; preventClose omitted; rejected close promise": { "status": "PASS" }, "Closing must be propagated forward: becomes closed asynchronously; preventClose = true": { "status": "PASS" }, "Closing must be propagated forward: becomes closed asynchronously; dest never desires chunks; preventClose omitted; fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: becomes closed asynchronously; dest never desires chunks; preventClose omitted; rejected close promise": { "status": "PASS" }, "Closing must be propagated forward: becomes closed asynchronously; dest never desires chunks; preventClose = true": { "status": "PASS" }, "Closing must be propagated forward: becomes closed after one chunk; preventClose omitted; fulfilled close promise": { "status": "PASS" }, "Closing must be propagated forward: becomes closed after one chunk; preventClose omitted; rejected close promise": { "status": "PASS" }, "Closing must be propagated forward: becomes closed after one chunk; preventClose = true": { "status": "PASS" }, "Closing must be propagated forward: shutdown must not occur until the final write completes": { "status": "PASS" }, "Closing must be propagated forward: shutdown must not occur until the final write completes; preventClose = true": { "status": "PASS" }, "Closing must be propagated forward: shutdown must not occur until the final write completes; becomes closed after first write": { "status": "PASS" }, "Closing must be propagated forward: shutdown must not occur until the final write completes; becomes closed after first write; preventClose = true": { "status": "PASS" }, "Closing must be propagated forward: erroring the writable while flushing pending writes should error pipeTo": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/error-propagation-backward.any.js.json ================================================ { "Errors must be propagated backward: starts errored; preventCancel omitted; fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel omitted; fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel omitted; rejected cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = undefined (falsy); fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = null (falsy); fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = false (falsy); fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = 0 (falsy); fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = -0 (falsy); fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = NaN (falsy); fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = (falsy); fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = true (truthy)": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = a (truthy)": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = 1 (truthy)": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = Symbol() (truthy)": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = [object Object] (truthy)": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write, preventCancel = true; preventAbort = true": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping due to write; preventCancel = true, preventAbort = true, preventClose = true": { "status": "PASS" }, "Errors must be propagated backward: becomes errored during piping due to write; preventCancel omitted; fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored during piping due to write; preventCancel omitted; rejected cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored during piping due to write; preventCancel = true": { "status": "PASS" }, "Errors must be propagated backward: becomes errored during piping due to write, but async; preventCancel = false; fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored during piping due to write, but async; preventCancel = false; rejected cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored during piping due to write, but async; preventCancel = true": { "status": "PASS" }, "Errors must be propagated backward: becomes errored after piping; preventCancel omitted; fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored after piping; preventCancel omitted; rejected cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored after piping; preventCancel = true": { "status": "PASS" }, "Errors must be propagated backward: becomes errored after piping due to last write; source is closed; preventCancel omitted (but cancel is never called)": { "status": "PASS" }, "Errors must be propagated backward: becomes errored after piping due to last write; source is closed; preventCancel = true": { "status": "PASS" }, "Errors must be propagated backward: becomes errored after piping; dest never desires chunks; preventCancel = false; fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored after piping; dest never desires chunks; preventCancel = false; rejected cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored after piping; dest never desires chunks; preventCancel = true": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping via abort; preventCancel omitted; fulfilled cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping via abort; preventCancel omitted; rejected cancel promise": { "status": "PASS" }, "Errors must be propagated backward: becomes errored before piping via abort; preventCancel = true": { "status": "PASS" }, "Errors must be propagated backward: erroring via the controller errors once pending write completes": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/error-propagation-forward.any.js.json ================================================ { "Errors must be propagated forward: starts errored; preventAbort = false; fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = false; rejected abort promise": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = undefined (falsy); fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = null (falsy); fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = false (falsy); fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = 0 (falsy); fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = -0 (falsy); fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = NaN (falsy); fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = (falsy); fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = true (truthy)": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = a (truthy)": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = 1 (truthy)": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = Symbol() (truthy)": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = [object Object] (truthy)": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = true, preventCancel = true": { "status": "PASS" }, "Errors must be propagated forward: starts errored; preventAbort = true, preventCancel = true, preventClose = true": { "status": "PASS" }, "Errors must be propagated forward: becomes errored while empty; preventAbort = false; fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: becomes errored while empty; preventAbort = false; rejected abort promise": { "status": "PASS" }, "Errors must be propagated forward: becomes errored while empty; preventAbort = true": { "status": "PASS" }, "Errors must be propagated forward: becomes errored while empty; dest never desires chunks; preventAbort = false; fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: becomes errored while empty; dest never desires chunks; preventAbort = false; rejected abort promise": { "status": "PASS" }, "Errors must be propagated forward: becomes errored while empty; dest never desires chunks; preventAbort = true": { "status": "PASS" }, "Errors must be propagated forward: becomes errored after one chunk; preventAbort = false; fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: becomes errored after one chunk; preventAbort = false; rejected abort promise": { "status": "PASS" }, "Errors must be propagated forward: becomes errored after one chunk; preventAbort = true": { "status": "PASS" }, "Errors must be propagated forward: becomes errored after one chunk; dest never desires chunks; preventAbort = false; fulfilled abort promise": { "status": "PASS" }, "Errors must be propagated forward: becomes errored after one chunk; dest never desires chunks; preventAbort = false; rejected abort promise": { "status": "PASS" }, "Errors must be propagated forward: becomes errored after one chunk; dest never desires chunks; preventAbort = true": { "status": "PASS" }, "Errors must be propagated forward: shutdown must not occur until the final write completes": { "status": "PASS" }, "Errors must be propagated forward: shutdown must not occur until the final write completes; preventAbort = true": { "status": "PASS" }, "Errors must be propagated forward: shutdown must not occur until the final write completes; becomes errored after first write": { "status": "PASS" }, "Errors must be propagated forward: shutdown must not occur until the final write completes; becomes errored after first write; preventAbort = true": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/flow-control.any.js.json ================================================ { "Piping from a non-empty ReadableStream into a WritableStream that does not desire chunks": { "status": "PASS" }, "Piping from a non-empty ReadableStream into a WritableStream that does not desire chunks, but then does": { "status": "PASS" }, "Piping from an empty ReadableStream into a WritableStream that does not desire chunks, but then the readable stream becomes non-empty and the writable stream starts desiring chunks": { "status": "PASS" }, "Piping from a ReadableStream to a WritableStream that desires more chunks before finishing with previous ones": { "status": "PASS" }, "Piping to a WritableStream that does not consume the writes fast enough exerts backpressure on the ReadableStream": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/general-addition.any.js.json ================================================ { "enqueue() must not synchronously call write algorithm": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/general.any.js.json ================================================ { "Piping must lock both the ReadableStream and WritableStream": { "status": "PASS" }, "Piping finishing must unlock both the ReadableStream and WritableStream": { "status": "PASS" }, "pipeTo must check the brand of its ReadableStream this value": { "status": "FAIL" }, "pipeTo must check the brand of its WritableStream argument": { "status": "PASS" }, "pipeTo must fail if the ReadableStream is locked, and not lock the WritableStream": { "status": "PASS" }, "pipeTo must fail if the WritableStream is locked, and not lock the ReadableStream": { "status": "PASS" }, "Piping from a ReadableStream from which lots of chunks are synchronously readable": { "status": "PASS" }, "Piping from a ReadableStream for which a chunk becomes asynchronously readable after the pipeTo": { "status": "PASS" }, "an undefined rejection from pull should cause pipeTo() to reject when preventAbort is true": { "status": "PASS" }, "an undefined rejection from pull should cause pipeTo() to reject when preventAbort is false": { "status": "PASS" }, "an undefined rejection from write should cause pipeTo() to reject when preventCancel is true": { "status": "PASS" }, "an undefined rejection from write should cause pipeTo() to reject when preventCancel is false": { "status": "PASS" }, "pipeTo() should reject if an option getter grabs a writer": { "status": "PASS" }, "pipeTo() promise should resolve if null is passed": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/multiple-propagation.any.js.json ================================================ { "Piping from an errored readable stream to an erroring writable stream": { "status": "PASS" }, "Piping from an errored readable stream to an errored writable stream": { "status": "PASS" }, "Piping from an errored readable stream to an erroring writable stream; preventAbort = true": { "status": "PASS" }, "Piping from an errored readable stream to an errored writable stream; preventAbort = true": { "status": "PASS" }, "Piping from an errored readable stream to a closing writable stream": { "status": "PASS" }, "Piping from an errored readable stream to a closed writable stream": { "status": "PASS" }, "Piping from a closed readable stream to an erroring writable stream": { "status": "PASS" }, "Piping from a closed readable stream to an errored writable stream": { "status": "PASS" }, "Piping from a closed readable stream to a closed writable stream": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/then-interception.any.js.json ================================================ { "piping should not be observable": { "status": "PASS" }, "tee should not be observable": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/throwing-options.any.js.json ================================================ { "pipeTo should stop after getting preventAbort throws": { "status": "FAIL" }, "pipeThrough should stop after getting preventAbort throws": { "status": "FAIL" }, "pipeTo should stop after getting preventCancel throws": { "status": "FAIL" }, "pipeThrough should stop after getting preventCancel throws": { "status": "FAIL" }, "pipeTo should stop after getting preventClose throws": { "status": "FAIL" }, "pipeThrough should stop after getting preventClose throws": { "status": "FAIL" }, "pipeTo should stop after getting signal throws": { "status": "FAIL" }, "pipeThrough should stop after getting signal throws": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/piping/transform-streams.any.js.json ================================================ { "Piping through an identity transform stream should close the destination when the source closes": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/queuing-strategies.any.js.json ================================================ { "CountQueuingStrategy: Can construct a with a valid high water mark": { "status": "PASS" }, "CountQueuingStrategy: Constructor behaves as expected with strange arguments": { "status": "PASS" }, "CountQueuingStrategy: highWaterMark constructor values are converted per the unrestricted double rules": { "status": "PASS" }, "CountQueuingStrategy: size is the same function across all instances": { "status": "PASS" }, "CountQueuingStrategy: size should have the right name": { "status": "PASS" }, "CountQueuingStrategy: subclassing should work correctly": { "status": "PASS" }, "CountQueuingStrategy: size should not have a prototype property": { "status": "PASS" }, "ByteLengthQueuingStrategy: Can construct a with a valid high water mark": { "status": "PASS" }, "ByteLengthQueuingStrategy: Constructor behaves as expected with strange arguments": { "status": "PASS" }, "ByteLengthQueuingStrategy: highWaterMark constructor values are converted per the unrestricted double rules": { "status": "PASS" }, "ByteLengthQueuingStrategy: size is the same function across all instances": { "status": "PASS" }, "ByteLengthQueuingStrategy: size should have the right name": { "status": "PASS" }, "ByteLengthQueuingStrategy: subclassing should work correctly": { "status": "PASS" }, "ByteLengthQueuingStrategy: size should not have a prototype property": { "status": "PASS" }, "CountQueuingStrategy: size should not be a constructor": { "status": "PASS" }, "ByteLengthQueuingStrategy: size should not be a constructor": { "status": "PASS" }, "CountQueuingStrategy: size should have the right length": { "status": "PASS" }, "ByteLengthQueuingStrategy: size should have the right length": { "status": "PASS" }, "CountQueuingStrategy: size behaves as expected with strange arguments": { "status": "PASS" }, "ByteLengthQueuingStrategy: size behaves as expected with strange arguments": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-byte-streams/bad-buffers-and-views.any.js.json ================================================ { "ReadableStream with byte source: read()ing from a closed stream still transfers the buffer": { "status": "PASS" }, "ReadableStream with byte source: read()ing from a stream with queued chunks still transfers the buffer": { "status": "PASS" }, "ReadableStream with byte source: enqueuing an already-detached buffer throws": { "status": "PASS" }, "ReadableStream with byte source: enqueuing a zero-length buffer throws": { "status": "PASS" }, "ReadableStream with byte source: enqueuing a zero-length view on a non-zero-length buffer throws": { "status": "PASS" }, "ReadableStream with byte source: reading into an already-detached buffer rejects": { "status": "PASS" }, "ReadableStream with byte source: reading into a zero-length buffer rejects": { "status": "PASS" }, "ReadableStream with byte source: reading into a zero-length view on a non-zero-length buffer rejects": { "status": "PASS" }, "ReadableStream with byte source: respond() throws if the BYOB request's buffer has been detached (in the readable state)": { "status": "PASS" }, "ReadableStream with byte source: respond() throws if the BYOB request's buffer has been detached (in the closed state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view's buffer has been detached (in the readable state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view's buffer is zero-length (in the readable state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view is zero-length on a non-zero-length buffer (in the readable state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view has a different offset (in the readable state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view has a different offset (in the closed state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view's buffer has a different length (in the readable state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view's buffer has a different length (autoAllocateChunkSize)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view has a larger length (in the readable state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view's buffer has been detached (in the closed state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view's buffer is zero-length (in the closed state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view is non-zero-length (in the closed state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() throws if the supplied view's buffer has a different length (in the closed state)": { "status": "PASS" }, "ReadableStream with byte source: enqueue() throws if the BYOB request's buffer has been detached (in the readable state)": { "status": "PASS" }, "ReadableStream with byte source: enqueue() throws if the BYOB request's buffer has been detached (in the closed state)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-byte-streams/construct-byob-request.any.js.json ================================================ { "ReadableStreamBYOBRequest constructor should throw when passed a undefined ReadableByteStreamController and a undefined view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a undefined ReadableByteStreamController and a null view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a undefined ReadableByteStreamController and a fake view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a undefined ReadableByteStreamController and a real view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a null ReadableByteStreamController and a undefined view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a null ReadableByteStreamController and a null view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a null ReadableByteStreamController and a fake view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a null ReadableByteStreamController and a real view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a fake ReadableByteStreamController and a undefined view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a fake ReadableByteStreamController and a null view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a fake ReadableByteStreamController and a fake view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a fake ReadableByteStreamController and a real view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a real ReadableByteStreamController and a undefined view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a real ReadableByteStreamController and a null view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a real ReadableByteStreamController and a fake view": { "status": "PASS" }, "ReadableStreamBYOBRequest constructor should throw when passed a real ReadableByteStreamController and a real view": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-byte-streams/enqueue-with-detached-buffer.any.js.json ================================================ { "enqueue after detaching byobRequest.view.buffer should throw": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-byte-streams/general.any.js.json ================================================ { "getReader({mode: \"byob\"}) throws on non-bytes streams": { "status": "PASS" }, "ReadableStream with byte source can be constructed with no errors": { "status": "PASS" }, "getReader({mode}) must perform ToString()": { "status": "PASS" }, "ReadableStream with byte source: Construct and expect start and pull being called": { "status": "PASS" }, "ReadableStream with byte source: No automatic pull call if start doesn't finish": { "status": "PASS" }, "ReadableStream with byte source: start() throws an exception": { "status": "PASS" }, "ReadableStream with byte source: Construct with highWaterMark of 0": { "status": "PASS" }, "ReadableStream with byte source: desiredSize when closed": { "status": "PASS" }, "ReadableStream with byte source: desiredSize when errored": { "status": "PASS" }, "ReadableStream with byte source: getReader(), then releaseLock()": { "status": "PASS" }, "ReadableStream with byte source: getReader() with mode set to byob, then releaseLock()": { "status": "PASS" }, "ReadableStream with byte source: Test that closing a stream does not release a reader automatically": { "status": "PASS" }, "ReadableStream with byte source: Test that closing a stream does not release a BYOB reader automatically": { "status": "PASS" }, "ReadableStream with byte source: Test that erroring a stream does not release a reader automatically": { "status": "PASS" }, "ReadableStream with byte source: Test that erroring a stream does not release a BYOB reader automatically": { "status": "PASS" }, "ReadableStream with byte source: cannot use an already-released BYOB reader to unlock a stream again": { "status": "PASS" }, "ReadableStream with byte source: releaseLock() on ReadableStreamDefaultReader must reject pending read()": { "status": "PASS" }, "ReadableStream with byte source: releaseLock() on ReadableStreamBYOBReader must reject pending read()": { "status": "PASS" }, "ReadableStream with byte source: Automatic pull() after start()": { "status": "PASS" }, "ReadableStream with byte source: Automatic pull() after start() and read()": { "status": "PASS" }, "ReadableStream with byte source: autoAllocateChunkSize": { "status": "PASS" }, "ReadableStream with byte source: Mix of auto allocate and BYOB": { "status": "PASS" }, "ReadableStream with byte source: Automatic pull() after start() and read(view)": { "status": "PASS" }, "ReadableStream with byte source: enqueue(), getReader(), then read()": { "status": "PASS" }, "ReadableStream with byte source: Push source that doesn't understand pull signal": { "status": "PASS" }, "ReadableStream with byte source: pull() function is not callable": { "status": "PASS" }, "ReadableStream with byte source: enqueue() with Uint16Array, getReader(), then read()": { "status": "PASS" }, "ReadableStream with byte source: enqueue(), read(view) partially, then read()": { "status": "PASS" }, "ReadableStream with byte source: getReader(), enqueue(), close(), then read()": { "status": "PASS" }, "ReadableStream with byte source: enqueue(), close(), getReader(), then read()": { "status": "PASS" }, "ReadableStream with byte source: Respond to pull() by enqueue()": { "status": "PASS" }, "ReadableStream with byte source: Respond to pull() by enqueue() asynchronously": { "status": "PASS" }, "ReadableStream with byte source: Respond to multiple pull() by separate enqueue()": { "status": "PASS" }, "ReadableStream with byte source: read(view), then respond()": { "status": "PASS" }, "ReadableStream with byte source: read(view), then respondWithNewView() with a transferred ArrayBuffer": { "status": "PASS" }, "ReadableStream with byte source: read(view), then respond() with too big value": { "status": "PASS" }, "ReadableStream with byte source: respond(3) to read(view) with 2 element Uint16Array enqueues the 1 byte remainder": { "status": "PASS" }, "ReadableStream with byte source: respond(3) to read(view) with 2 element Uint16Array fulfills second read(view) with the 1 byte remainder": { "status": "PASS" }, "ReadableStream with byte source: enqueue(), getReader(), then read(view)": { "status": "PASS" }, "ReadableStream with byte source: enqueue(), getReader(), then cancel() (mode = not BYOB)": { "status": "PASS" }, "ReadableStream with byte source: enqueue(), getReader(), then cancel() (mode = BYOB)": { "status": "PASS" }, "ReadableStream with byte source: getReader(), read(view), then cancel()": { "status": "PASS" }, "ReadableStream with byte source: cancel() with partially filled pending pull() request": { "status": "PASS" }, "ReadableStream with byte source: enqueue(), getReader(), then read(view) where view.buffer is not fully covered by view": { "status": "PASS" }, "ReadableStream with byte source: Multiple enqueue(), getReader(), then read(view)": { "status": "PASS" }, "ReadableStream with byte source: enqueue(), getReader(), then read(view) with a bigger view": { "status": "PASS" }, "ReadableStream with byte source: enqueue(), getReader(), then read(view) with smaller views": { "status": "PASS" }, "ReadableStream with byte source: enqueue() 1 byte, getReader(), then read(view) with Uint16Array": { "status": "PASS" }, "ReadableStream with byte source: enqueue() 3 byte, getReader(), then read(view) with 2-element Uint16Array": { "status": "PASS" }, "ReadableStream with byte source: read(view) with Uint16Array on close()-d stream with 1 byte enqueue()-d must fail": { "status": "PASS" }, "ReadableStream with byte source: A stream must be errored if close()-d before fulfilling read(view) with Uint16Array": { "status": "PASS" }, "ReadableStream with byte source: Throw if close()-ed more than once": { "status": "PASS" }, "ReadableStream with byte source: Throw on enqueue() after close()": { "status": "PASS" }, "ReadableStream with byte source: read(view), then respond() and close() in pull()": { "status": "PASS" }, "ReadableStream with byte source: read(view) with Uint32Array, then fill it by multiple respond() calls": { "status": "PASS" }, "ReadableStream with byte source: read(view) with Uint32Array, then fill it by multiple enqueue() calls": { "status": "PASS" }, "ReadableStream with byte source: read() twice, then enqueue() twice": { "status": "PASS" }, "ReadableStream with byte source: Multiple read(view), close() and respond()": { "status": "PASS" }, "ReadableStream with byte source: Multiple read(view), big enqueue()": { "status": "PASS" }, "ReadableStream with byte source: Multiple read(view) and multiple enqueue()": { "status": "PASS" }, "ReadableStream with byte source: read(view) with passing undefined as view must fail": { "status": "PASS" }, "ReadableStream with byte source: read(view) with passing an empty object as view must fail": { "status": "PASS" }, "ReadableStream with byte source: Even read(view) with passing ArrayBufferView like object as view must fail": { "status": "PASS" }, "ReadableStream with byte source: read() on an errored stream": { "status": "PASS" }, "ReadableStream with byte source: read(), then error()": { "status": "PASS" }, "ReadableStream with byte source: read(view) on an errored stream": { "status": "PASS" }, "ReadableStream with byte source: read(view), then error()": { "status": "PASS" }, "ReadableStream with byte source: Throwing in pull function must error the stream": { "status": "PASS" }, "ReadableStream with byte source: Throwing in pull in response to read() must be ignored if the stream is errored in it": { "status": "PASS" }, "ReadableStream with byte source: Throwing in pull in response to read(view) function must error the stream": { "status": "PASS" }, "ReadableStream with byte source: Throwing in pull in response to read(view) must be ignored if the stream is errored in it": { "status": "PASS" }, "calling respond() twice on the same byobRequest should throw": { "status": "PASS" }, "calling respondWithNewView() twice on the same byobRequest should throw": { "status": "PASS" }, "calling respond(0) twice on the same byobRequest should throw even when closed": { "status": "PASS" }, "calling respond() should throw when canceled": { "status": "PASS" }, "pull() resolving should not resolve read()": { "status": "PASS" }, "ReadableStream with byte source: default reader + autoAllocateChunkSize + byobRequest interaction": { "status": "PASS" }, "ReadableStream with byte source: autoAllocateChunkSize cannot be 0": { "status": "PASS" }, "ReadableStreamBYOBReader can be constructed directly": { "status": "PASS" }, "ReadableStreamBYOBReader constructor requires a ReadableStream argument": { "status": "PASS" }, "ReadableStreamBYOBReader constructor requires an unlocked ReadableStream": { "status": "PASS" }, "ReadableStreamBYOBReader constructor requires a ReadableStream with type \"bytes\"": { "status": "PASS" }, "ReadableStream constructor should not accept a strategy with a size defined if type is \"bytes\"": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() with a smaller view": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() with a zero-length view (in the closed state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() with a transferred non-zero-length view (in the readable state)": { "status": "PASS" }, "ReadableStream with byte source: respondWithNewView() with a transferred zero-length view (in the closed state)": { "status": "PASS" }, "ReadableStream with byte source: enqueue() discards auto-allocated BYOB request": { "status": "PASS" }, "ReadableStream with byte source: releaseLock() with pending read(view), read(view) on second reader, respond()": { "status": "PASS" }, "ReadableStream with byte source: releaseLock() with pending read(view), read(view) on second reader with 1 element Uint16Array, respond(1)": { "status": "PASS" }, "ReadableStream with byte source: releaseLock() with pending read(view), read(view) on second reader with 2 element Uint8Array, respond(3)": { "status": "PASS" }, "ReadableStream with byte source: releaseLock() with pending read(view), read(view) on second reader, respondWithNewView()": { "status": "PASS" }, "ReadableStream with byte source: releaseLock() with pending read(view), read(view) on second reader, enqueue()": { "status": "PASS" }, "ReadableStream with byte source: releaseLock() with pending read(view), read(view) on second reader, close(), respond(0)": { "status": "PASS" }, "ReadableStream with byte source: autoAllocateChunkSize, releaseLock() with pending read(), read() on second reader, respond()": { "status": "PASS" }, "ReadableStream with byte source: autoAllocateChunkSize, releaseLock() with pending read(), read() on second reader, enqueue()": { "status": "PASS" }, "ReadableStream with byte source: autoAllocateChunkSize, releaseLock() with pending read(), read(view) on second reader, respond()": { "status": "PASS" }, "ReadableStream with byte source: autoAllocateChunkSize, releaseLock() with pending read(), read(view) on second reader, enqueue()": { "status": "PASS" }, "ReadableStream with byte source: read(view) with 1 element Uint16Array, respond(1), releaseLock(), read(view) on second reader with 1 element Uint16Array, respond(1)": { "status": "PASS" }, "ReadableStream with byte source: read(view) with 1 element Uint16Array, respond(1), releaseLock(), read() on second reader, enqueue()": { "status": "PASS" }, "ReadableStream with byte source: autoAllocateChunkSize, read(), respondWithNewView()": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-byte-streams/non-transferable-buffers.any.js.json ================================================ { "ReadableStream with byte source: read() with a non-transferable buffer": { "status": "FAIL" }, "ReadableStream with byte source: fill() with a non-transferable buffer": { "status": "FAIL" }, "ReadableStream with byte source: enqueue() with a non-transferable buffer": { "status": "FAIL" }, "ReadableStream with byte source: respondWithNewView() with a non-transferable buffer": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-byte-streams/read-min.any.js.json ================================================ { "ReadableStream with byte source: read({ min }) rejects if min is 0": { "status": "FAIL" }, "ReadableStream with byte source: read({ min }) rejects if min is negative": { "status": "FAIL" }, "ReadableStream with byte source: read({ min }) rejects if min is larger than view's length (Uint8Array)": { "status": "FAIL" }, "ReadableStream with byte source: read({ min }) rejects if min is larger than view's length (Uint16Array)": { "status": "FAIL" }, "ReadableStream with byte source: read({ min }) rejects if min is larger than view's length (DataView)": { "status": "FAIL" }, "ReadableStream with byte source: read({ min }), then read()": { "status": "FAIL" }, "ReadableStream with byte source: read({ min }) with a DataView": { "status": "FAIL" }, "ReadableStream with byte source: enqueue(), then read({ min })": { "status": "FAIL" }, "ReadableStream with byte source: read({ min: 3 }) on a 3-byte Uint8Array, then multiple enqueue() up to 3 bytes": { "status": "FAIL" }, "ReadableStream with byte source: read({ min: 3 }) on a 5-byte Uint8Array, then multiple enqueue() up to 3 bytes": { "status": "FAIL" }, "ReadableStream with byte source: read({ min: 3 }) on a 5-byte Uint8Array, then multiple enqueue() up to 4 bytes": { "status": "FAIL" }, "ReadableStream with byte source: enqueue(), read({ min }) partially, then read()": { "status": "PASS" }, "ReadableStream with byte source: read({ min }), then respondWithNewView() with a transferred ArrayBuffer": { "status": "PASS" }, "ReadableStream with byte source: read({ min }) on a closed stream": { "status": "PASS" }, "ReadableStream with byte source: read({ min }) when closed before view is filled": { "status": "FAIL" }, "ReadableStream with byte source: read({ min }) when closed immediately after view is filled": { "status": "FAIL" }, "ReadableStream with byte source: read({ min }) on an errored stream": { "status": "PASS" }, "ReadableStream with byte source: read({ min }), then error()": { "status": "PASS" }, "ReadableStream with byte source: getReader(), read({ min }), then cancel()": { "status": "PASS" }, "ReadableStream with byte source: cancel() with partially filled pending read({ min }) request": { "status": "FAIL" }, "ReadableStream with byte source: enqueue(), then read({ min }) with smaller views": { "status": "PASS" }, "ReadableStream with byte source: 3 byte enqueue(), then close(), then read({ min }) with 2-element Uint16Array must fail": { "status": "FAIL" }, "ReadableStream with byte source: read({ min }) with 2-element Uint16Array, then 3 byte enqueue(), then close() must fail": { "status": "FAIL" }, "ReadableStream with byte source: tee() with read({ min }) from branch1 and read() from branch2": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-byte-streams/respond-after-enqueue.any.js.json ================================================ { "byobRequest.respond() after enqueue() should not crash": { "status": "PASS" }, "byobRequest.respond() with cached byobRequest after enqueue() should not crash": { "status": "PASS" }, "byobRequest.respond() after enqueue() with double read should not crash": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-byte-streams/tee.any.js.json ================================================ { "ReadableStream teeing with byte source: rs.tee() returns an array of two ReadableStreams": { "status": "FAIL" }, "ReadableStream teeing with byte source: should be able to read one branch to the end without affecting the other": { "status": "FAIL" }, "ReadableStream teeing with byte source: chunks should be cloned for each branch": { "status": "FAIL" }, "ReadableStream teeing with byte source: chunks for BYOB requests from branch 1 should be cloned to branch 2": { "status": "FAIL" }, "ReadableStream teeing with byte source: errors in the source should propagate to both branches": { "status": "FAIL" }, "ReadableStream teeing with byte source: canceling branch1 should not impact branch2": { "status": "FAIL" }, "ReadableStream teeing with byte source: canceling branch2 should not impact branch1": { "status": "FAIL" }, "Running templatedRSTeeCancel with ReadableStream teeing with byte source": { "status": "PASS" }, "ReadableStream teeing with byte source: canceling both branches should aggregate the cancel reasons into an array": { "status": "FAIL" }, "ReadableStream teeing with byte source: canceling both branches in reverse order should aggregate the cancel reasons into an array": { "status": "FAIL" }, "ReadableStream teeing with byte source: failing to cancel the original stream should cause cancel() to reject on branches": { "status": "FAIL" }, "ReadableStream teeing with byte source: erroring a teed stream should properly handle canceled branches": { "status": "FAIL" }, "ReadableStream teeing with byte source: closing the original should close the branches": { "status": "FAIL" }, "ReadableStream teeing with byte source: erroring the original should immediately error the branches": { "status": "FAIL" }, "ReadableStream teeing with byte source: erroring the original should error pending reads from default reader": { "status": "FAIL" }, "ReadableStream teeing with byte source: erroring the original should error pending reads from BYOB reader": { "status": "FAIL" }, "ReadableStream teeing with byte source: canceling branch1 should finish when branch2 reads until end of stream": { "status": "FAIL" }, "ReadableStream teeing with byte source: canceling branch1 should finish when original stream errors": { "status": "FAIL" }, "ReadableStream teeing with byte source: should not pull any chunks if no branches are reading": { "status": "FAIL" }, "ReadableStream teeing with byte source: should only pull enough to fill the emptiest queue": { "status": "FAIL" }, "ReadableStream teeing with byte source: should not pull when original is already errored": { "status": "FAIL" }, "ReadableStream teeing with byte source: stops pulling when original stream errors while branch 1 is reading": { "status": "FAIL" }, "ReadableStream teeing with byte source: stops pulling when original stream errors while branch 2 is reading": { "status": "FAIL" }, "ReadableStream teeing with byte source: stops pulling when original stream errors while both branches are reading": { "status": "FAIL" }, "ReadableStream teeing with byte source: canceling both branches in sequence with delay": { "status": "FAIL" }, "ReadableStream teeing with byte source: failing to cancel when canceling both branches in sequence with delay": { "status": "FAIL" }, "ReadableStream teeing with byte source: read from branch1 and branch2, cancel branch1, cancel branch2": { "status": "FAIL" }, "ReadableStream teeing with byte source: read from branch1 and branch2, cancel branch2, cancel branch1": { "status": "FAIL" }, "ReadableStream teeing with byte source: read from branch1 and branch2, cancel branch2, enqueue to branch1": { "status": "FAIL" }, "ReadableStream teeing with byte source: read from branch1 and branch2, cancel branch1, respond to branch2": { "status": "FAIL" }, "ReadableStream teeing with byte source: pull with BYOB reader, then pull with default reader": { "status": "FAIL" }, "ReadableStream teeing with byte source: pull with default reader, then pull with BYOB reader": { "status": "FAIL" }, "ReadableStream teeing with byte source: read from branch2, then read from branch1": { "status": "FAIL" }, "ReadableStream teeing with byte source: read from branch1 with default reader, then close while branch2 has pending BYOB read": { "status": "FAIL" }, "ReadableStream teeing with byte source: read from branch2 with default reader, then close while branch1 has pending BYOB read": { "status": "FAIL" }, "ReadableStream teeing with byte source: close when both branches have pending BYOB reads": { "status": "FAIL" }, "ReadableStream teeing with byte source: enqueue() and close() while both branches are pulling": { "status": "FAIL" }, "ReadableStream teeing with byte source: respond() and close() while both branches are pulling": { "status": "FAIL" }, "ReadableStream teeing with byte source: reading an array with a byte offset should clone correctly": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/async-iterator.any.js.json ================================================ { "Async iterator instances should have the correct list of properties": { "status": "FAIL" }, "Async-iterating a push source": { "status": "FAIL" }, "Async-iterating a pull source": { "status": "FAIL" }, "Async-iterating a push source with undefined values": { "status": "FAIL" }, "Async-iterating a pull source with undefined values": { "status": "FAIL" }, "Async-iterating a pull source manually": { "status": "FAIL" }, "Async-iterating an errored stream throws": { "status": "FAIL" }, "Async-iterating a closed stream never executes the loop body, but works fine": { "status": "FAIL" }, "Async-iterating an empty but not closed/errored stream never executes the loop body and stalls the async function": { "status": "FAIL" }, "Async-iterating a partially consumed stream": { "status": "FAIL" }, "Cancellation behavior when throwing inside loop body; preventCancel = false": { "status": "FAIL" }, "Cancellation behavior when throwing inside loop body; preventCancel = true": { "status": "FAIL" }, "Cancellation behavior when breaking inside loop body; preventCancel = false": { "status": "FAIL" }, "Cancellation behavior when breaking inside loop body; preventCancel = true": { "status": "FAIL" }, "Cancellation behavior when returning inside loop body; preventCancel = false": { "status": "FAIL" }, "Cancellation behavior when returning inside loop body; preventCancel = true": { "status": "FAIL" }, "Cancellation behavior when manually calling return(); preventCancel = false": { "status": "FAIL" }, "Cancellation behavior when manually calling return(); preventCancel = true": { "status": "FAIL" }, "next() rejects if the stream errors": { "status": "FAIL" }, "return() does not rejects if the stream has not errored yet": { "status": "FAIL" }, "return() rejects if the stream has errored": { "status": "FAIL" }, "next() that succeeds; next() that reports an error; next()": { "status": "FAIL" }, "next() that succeeds; next() that reports an error(); next() [no awaiting]": { "status": "FAIL" }, "next() that succeeds; next() that reports an error(); return()": { "status": "FAIL" }, "next() that succeeds; next() that reports an error(); return() [no awaiting]": { "status": "FAIL" }, "next() that succeeds; return()": { "status": "FAIL" }, "next() that succeeds; return() [no awaiting]": { "status": "FAIL" }, "return(); next()": { "status": "FAIL" }, "return(); next() [no awaiting]": { "status": "FAIL" }, "return(); next() with delayed cancel()": { "status": "FAIL" }, "return(); next() with delayed cancel() [no awaiting]": { "status": "FAIL" }, "return(); return()": { "status": "FAIL" }, "return(); return() [no awaiting]": { "status": "FAIL" }, "values() throws if there's already a lock": { "status": "FAIL" }, "Acquiring a reader after exhaustively async-iterating a stream": { "status": "FAIL" }, "Acquiring a reader after return()ing from a stream that errors": { "status": "FAIL" }, "Acquiring a reader after partially async-iterating a stream": { "status": "FAIL" }, "Acquiring a reader and reading the remaining chunks after partially async-iterating a stream with preventCancel = true": { "status": "FAIL" }, "return() should unlock the stream synchronously when preventCancel = false": { "status": "FAIL" }, "return() should unlock the stream synchronously when preventCancel = true": { "status": "FAIL" }, "close() while next() is pending": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/bad-strategies.any.js.json ================================================ { "Readable stream: throwing strategy.size getter": { "status": "PASS" }, "Readable stream: strategy.size errors the stream and then throws": { "status": "PASS" }, "Readable stream: strategy.size errors the stream and then returns Infinity": { "status": "PASS" }, "Readable stream: throwing strategy.size method": { "status": "PASS" }, "Readable stream: throwing strategy.highWaterMark getter": { "status": "PASS" }, "Readable stream: invalid strategy.highWaterMark": { "status": "PASS" }, "Readable stream: invalid strategy.size return value": { "status": "PASS" }, "Readable stream: invalid strategy.size return value when pulling": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/bad-underlying-sources.any.js.json ================================================ { "Underlying source start: throwing getter": { "status": "PASS" }, "Underlying source start: throwing method": { "status": "PASS" }, "Underlying source: throwing pull getter (initial pull)": { "status": "PASS" }, "Underlying source: throwing pull method (initial pull)": { "status": "PASS" }, "Underlying source pull: throwing getter (second pull does not result in a second get)": { "status": "PASS" }, "Underlying source pull: throwing method (second pull)": { "status": "PASS" }, "Underlying source cancel: throwing getter": { "status": "PASS" }, "Underlying source cancel: throwing method": { "status": "PASS" }, "Underlying source: calling enqueue on an empty canceled stream should throw": { "status": "PASS" }, "Underlying source: calling enqueue on a non-empty canceled stream should throw": { "status": "PASS" }, "Underlying source: calling enqueue on a closed stream should throw": { "status": "PASS" }, "Underlying source: calling enqueue on an errored stream should throw": { "status": "PASS" }, "Underlying source: calling close twice on an empty stream should throw the second time": { "status": "PASS" }, "Underlying source: calling close twice on a non-empty stream should throw the second time": { "status": "PASS" }, "Underlying source: calling close on an empty canceled stream should throw": { "status": "PASS" }, "Underlying source: calling close on a non-empty canceled stream should throw": { "status": "PASS" }, "Underlying source: calling close after error should throw": { "status": "PASS" }, "Underlying source: calling error twice should not throw": { "status": "PASS" }, "Underlying source: calling error after close should not throw": { "status": "PASS" }, "Underlying source: calling error and returning a rejected promise from start should cause the stream to error with the first error": { "status": "PASS" }, "Underlying source: calling error and returning a rejected promise from pull should cause the stream to error with the first error": { "status": "PASS" }, "read should not error if it dequeues and pull() throws": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/cancel.any.js.json ================================================ { "ReadableStream cancellation: integration test on an infinite stream derived from a random push source": { "status": "PASS" }, "ReadableStream cancellation: cancel(reason) should pass through the given reason to the underlying source": { "status": "PASS" }, "ReadableStream cancellation: cancel() on a locked stream should fail and not call the underlying source cancel": { "status": "PASS" }, "ReadableStream cancellation: should fulfill promise when cancel callback went fine": { "status": "PASS" }, "ReadableStream cancellation: returning a value from the underlying source's cancel should not affect the fulfillment value of the promise returned by the stream's cancel": { "status": "PASS" }, "ReadableStream cancellation: should reject promise when cancel callback raises an exception": { "status": "PASS" }, "ReadableStream cancellation: if the underlying source's cancel method returns a promise, the promise returned by the stream's cancel should fulfill when that one does (1)": { "status": "PASS" }, "ReadableStream cancellation: if the underlying source's cancel method returns a promise, the promise returned by the stream's cancel should fulfill when that one does (2)": { "status": "PASS" }, "ReadableStream cancellation: if the underlying source's cancel method returns a promise, the promise returned by the stream's cancel should reject when that one does": { "status": "PASS" }, "ReadableStream cancellation: cancelling before start finishes should prevent pull() from being called": { "status": "PASS" }, "ReadableStream cancellation: underlyingSource.cancel() should called, even with pending pull": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/constructor.any.js.json ================================================ { "underlyingSource argument should be converted after queuingStrategy argument": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/count-queuing-strategy-integration.any.js.json ================================================ { "Can construct a readable stream with a valid CountQueuingStrategy": { "status": "PASS" }, "Correctly governs a ReadableStreamController's desiredSize property (HWM = 0)": { "status": "PASS" }, "Correctly governs a ReadableStreamController's desiredSize property (HWM = 1)": { "status": "PASS" }, "Correctly governs a ReadableStreamController's desiredSize property (HWM = 4)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/default-reader.any.js.json ================================================ { "ReadableStreamDefaultReader constructor should get a ReadableStream object as argument": { "status": "PASS" }, "ReadableStreamDefaultReader closed should always return the same promise object": { "status": "PASS" }, "Constructing a ReadableStreamDefaultReader directly should fail if the stream is already locked (via direct construction)": { "status": "PASS" }, "Getting a ReadableStreamDefaultReader via getReader should fail if the stream is already locked (via direct construction)": { "status": "PASS" }, "Constructing a ReadableStreamDefaultReader directly should fail if the stream is already locked (via getReader)": { "status": "PASS" }, "Getting a ReadableStreamDefaultReader via getReader should fail if the stream is already locked (via getReader)": { "status": "PASS" }, "Constructing a ReadableStreamDefaultReader directly should be OK if the stream is closed": { "status": "PASS" }, "Constructing a ReadableStreamDefaultReader directly should be OK if the stream is errored": { "status": "PASS" }, "Reading from a reader for an empty stream will wait until a chunk is available": { "status": "PASS" }, "cancel() on a reader does not release the reader": { "status": "PASS" }, "closed should be fulfilled after stream is closed (.closed access before acquiring)": { "status": "PASS" }, "closed should be rejected after reader releases its lock (multiple stream locks)": { "status": "PASS" }, "closed is replaced when stream closes and reader releases its lock": { "status": "PASS" }, "closed is replaced when stream errors and reader releases its lock": { "status": "PASS" }, "Multiple readers can access the stream in sequence": { "status": "PASS" }, "Cannot use an already-released reader to unlock a stream again": { "status": "PASS" }, "cancel() on a released reader is a no-op and does not pass through": { "status": "PASS" }, "Getting a second reader after erroring the stream and releasing the reader should succeed": { "status": "PASS" }, "ReadableStreamDefaultReader closed promise should be rejected with undefined if that is the error": { "status": "PASS" }, "ReadableStreamDefaultReader: if start rejects with no parameter, it should error the stream with an undefined error": { "status": "PASS" }, "Erroring a ReadableStream after checking closed should reject ReadableStreamDefaultReader closed promise": { "status": "PASS" }, "Erroring a ReadableStream before checking closed should reject ReadableStreamDefaultReader closed promise": { "status": "PASS" }, "Reading twice on a stream that gets closed": { "status": "PASS" }, "Reading twice on a closed stream": { "status": "PASS" }, "Reading twice on an errored stream": { "status": "PASS" }, "Reading twice on a stream that gets errored": { "status": "PASS" }, "getReader() should call ToString() on mode": { "status": "PASS" }, "controller.close() should clear the list of pending read requests": { "status": "PASS" }, "Second reader can read chunks after first reader was released with pending read requests": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/floating-point-total-queue-size.any.js.json ================================================ { "Floating point arithmetic must manifest near NUMBER.MAX_SAFE_INTEGER (total ends up positive)": { "status": "PASS" }, "Floating point arithmetic must manifest near 0 (total ends up positive, but clamped)": { "status": "PASS" }, "Floating point arithmetic must manifest near 0 (total ends up positive, and not clamped)": { "status": "PASS" }, "Floating point arithmetic must manifest near 0 (total ends up zero)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/from.any.js.json ================================================ { "ReadableStream.from accepts an array of values": { "status": "FAIL" }, "ReadableStream.from accepts an array of promises": { "status": "FAIL" }, "ReadableStream.from accepts an array iterator": { "status": "FAIL" }, "ReadableStream.from accepts a string": { "status": "FAIL" }, "ReadableStream.from accepts a Set": { "status": "FAIL" }, "ReadableStream.from accepts a Set iterator": { "status": "FAIL" }, "ReadableStream.from accepts a sync generator": { "status": "FAIL" }, "ReadableStream.from accepts an async generator": { "status": "FAIL" }, "ReadableStream.from accepts a sync iterable of values": { "status": "FAIL" }, "ReadableStream.from accepts a sync iterable of promises": { "status": "FAIL" }, "ReadableStream.from accepts an async iterable": { "status": "FAIL" }, "ReadableStream.from accepts a ReadableStream": { "status": "FAIL" }, "ReadableStream.from accepts a ReadableStream async iterator": { "status": "FAIL" }, "ReadableStream.from throws on invalid iterables; specifically null": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically undefined": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically 0": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically NaN": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically true": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically {}": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically Object.create(null)": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically a function": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically a symbol": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically an object with a non-callable @@iterator method": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically an object with a non-callable @@asyncIterator method": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically an object with an @@iterator method returning a non-object": { "status": "PASS" }, "ReadableStream.from throws on invalid iterables; specifically an object with an @@asyncIterator method returning a non-object": { "status": "PASS" }, "ReadableStream.from re-throws errors from calling the @@iterator method": { "status": "FAIL" }, "ReadableStream.from re-throws errors from calling the @@asyncIterator method": { "status": "FAIL" }, "ReadableStream.from ignores @@iterator if @@asyncIterator exists": { "status": "FAIL" }, "ReadableStream.from ignores a null @@asyncIterator": { "status": "FAIL" }, "ReadableStream.from accepts an empty iterable": { "status": "FAIL" }, "ReadableStream.from: stream errors when next() rejects": { "status": "FAIL" }, "ReadableStream.from: stream errors when next() throws synchronously": { "status": "FAIL" }, "ReadableStream.from: stream errors when next() returns a non-object": { "status": "FAIL" }, "ReadableStream.from: stream errors when next() fulfills with a non-object": { "status": "FAIL" }, "ReadableStream.from: stream stalls when next() never settles": { "status": "FAIL" }, "ReadableStream.from: calls next() after first read()": { "status": "FAIL" }, "ReadableStream.from: cancelling the returned stream calls and awaits return()": { "status": "FAIL" }, "ReadableStream.from: return() is not called when iterator completes normally": { "status": "FAIL" }, "ReadableStream.from: cancel() resolves when return() method is missing": { "status": "FAIL" }, "ReadableStream.from: cancel() rejects when return() is not a method": { "status": "FAIL" }, "ReadableStream.from: cancel() rejects when return() rejects": { "status": "FAIL" }, "ReadableStream.from: cancel() rejects when return() throws synchronously": { "status": "FAIL" }, "ReadableStream.from: cancel() rejects when return() fulfills with a non-object": { "status": "FAIL" }, "ReadableStream.from: reader.read() inside next()": { "status": "FAIL" }, "ReadableStream.from: reader.cancel() inside next()": { "status": "FAIL" }, "ReadableStream.from: reader.cancel() inside return()": { "status": "FAIL" }, "ReadableStream.from(array), push() to array while reading": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/garbage-collection.any.js.json ================================================ { "ReadableStreamController methods should continue working properly when scripts lose their reference to the readable stream": { "status": "PASS" }, "ReadableStream closed promise should fulfill even if the stream and reader JS references are lost": { "status": "PASS" }, "ReadableStream closed promise should reject even if stream and reader JS references are lost": { "status": "PASS" }, "Garbage-collecting a ReadableStreamDefaultReader should not unlock its stream": { "status": "PASS" }, "A ReadableStream and its reader should not be garbage collected while there is a read promise pending": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/general.any.js.json ================================================ { "ReadableStream can be constructed with no errors": { "status": "PASS" }, "ReadableStream can't be constructed with garbage": { "status": "PASS" }, "ReadableStream can't be constructed with an invalid type": { "status": "FAIL" }, "ReadableStream constructor should throw for non-function start arguments": { "status": "PASS" }, "ReadableStream constructor will not tolerate initial garbage as cancel argument": { "status": "PASS" }, "ReadableStream constructor will not tolerate initial garbage as pull argument": { "status": "PASS" }, "ReadableStream start should be called with the proper thisArg": { "status": "PASS" }, "ReadableStream start controller parameter should be extensible": { "status": "PASS" }, "default ReadableStream getReader() should only accept mode:undefined": { "status": "PASS" }, "ReadableStream should be able to call start method within prototype chain of its source": { "status": "PASS" }, "ReadableStream start should be able to return a promise": { "status": "PASS" }, "ReadableStream start should be able to return a promise and reject it": { "status": "PASS" }, "ReadableStream should be able to enqueue different objects.": { "status": "PASS" }, "ReadableStream: if pull rejects, it should error the stream": { "status": "FAIL" }, "ReadableStream: should only call pull once upon starting the stream": { "status": "PASS" }, "ReadableStream: should call pull when trying to read from a started, empty stream": { "status": "PASS" }, "ReadableStream: should only call pull once on a non-empty stream read from before start fulfills": { "status": "PASS" }, "ReadableStream: should only call pull once on a non-empty stream read from after start fulfills": { "status": "PASS" }, "ReadableStream: should call pull in reaction to read()ing the last chunk, if not draining": { "status": "PASS" }, "ReadableStream: should not call pull() in reaction to read()ing the last chunk, if draining": { "status": "PASS" }, "ReadableStream: should not call pull until the previous pull call's promise fulfills": { "status": "PASS" }, "ReadableStream: should pull after start, and after every read": { "status": "PASS" }, "ReadableStream: should not call pull after start if the stream is now closed": { "status": "PASS" }, "ReadableStream: should call pull after enqueueing from inside pull (with no read requests), if strategy allows": { "status": "PASS" }, "ReadableStream pull should be able to close a stream.": { "status": "PASS" }, "ReadableStream pull should be able to error a stream.": { "status": "PASS" }, "ReadableStream pull should be able to error a stream and throw.": { "status": "PASS" }, "ReadableStream: enqueue should throw when the stream is readable but draining": { "status": "PASS" }, "ReadableStream: enqueue should throw when the stream is closed": { "status": "PASS" }, "ReadableStream: should call underlying source methods as methods": { "status": "PASS" }, "ReadableStream: desiredSize when closed": { "status": "PASS" }, "ReadableStream: desiredSize when errored": { "status": "PASS" }, "Subclassing ReadableStream should work": { "status": "PASS" }, "ReadableStream strategies: the default strategy should give desiredSize of 1 to start, decreasing by 1 per enqueue": { "status": "PASS" }, "ReadableStream strategies: the default strategy should continue giving desiredSize of 1 if the chunks are read immediately": { "status": "PASS" }, "ReadableStream integration test: adapting a random push source": { "status": "PASS" }, "ReadableStream integration test: adapting a sync pull source": { "status": "PASS" }, "ReadableStream integration test: adapting an async pull source": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/owning-type-message-port.any.js.json ================================================ { "Transferred MessageChannel works as expected": { "status": "FAIL" }, "Second branch of owning ReadableStream tee should end up into errors with transfer only values": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/owning-type-video-frame.any.js.json ================================================ { "ReadableStream of type owning should close serialized chunks": { "status": "FAIL" }, "ReadableStream of type owning should transfer JS chunks with transferred values": { "status": "FAIL" }, "ReadableStream of type owning should error when trying to enqueue not serializable values": { "status": "FAIL" }, "ReadableStream of type owning should clone serializable objects when teeing": { "status": "FAIL" }, "ReadableStream of type owning should clone JS Objects with serializables when teeing": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/owning-type.any.js.json ================================================ { "ReadableStream can be constructed with owning type": { "status": "FAIL" }, "ReadableStream of type owning should call start with a ReadableStreamDefaultController": { "status": "FAIL" }, "ReadableStream should be able to call enqueue with an empty transfer list": { "status": "FAIL" }, "ReadableStream should check transfer parameter": { "status": "FAIL" }, "ReadableStream of type owning should transfer enqueued chunks": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/patched-global.any.js.json ================================================ { "ReadableStream tee() should not touch Object.prototype properties": { "status": "PASS" }, "ReadableStream tee() should not call the global ReadableStream": { "status": "PASS" }, "ReadableStream async iterator should use the original values of getReader() and ReadableStreamDefaultReader methods": { "status": "FAIL" }, "tee() should not call Promise.prototype.then()": { "status": "PASS" }, "pipeTo() should not call Promise.prototype.then()": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/reentrant-strategies.any.js.json ================================================ { "enqueue() inside size() should work": { "status": "PASS" }, "close() inside size() should not crash": { "status": "PASS" }, "close request inside size() should work": { "status": "PASS" }, "error() inside size() should work": { "status": "PASS" }, "desiredSize inside size() should work": { "status": "PASS" }, "cancel() inside size() should work": { "status": "PASS" }, "pipeTo() inside size() should behave as expected": { "status": "PASS" }, "read() inside of size() should behave as expected": { "status": "PASS" }, "getReader() inside size() should work": { "status": "PASS" }, "tee() inside size() should work": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/tee.any.js.json ================================================ { "ReadableStream teeing: rs.tee() returns an array of two ReadableStreams": { "status": "PASS" }, "ReadableStream teeing: should be able to read one branch to the end without affecting the other": { "status": "PASS" }, "ReadableStream teeing: values should be equal across each branch": { "status": "PASS" }, "ReadableStream teeing: errors in the source should propagate to both branches": { "status": "PASS" }, "ReadableStream teeing: canceling branch1 should not impact branch2": { "status": "PASS" }, "ReadableStream teeing: canceling branch2 should not impact branch1": { "status": "PASS" }, "Running templatedRSTeeCancel with ReadableStream teeing": { "status": "PASS" }, "ReadableStream teeing: canceling both branches should aggregate the cancel reasons into an array": { "status": "PASS" }, "ReadableStream teeing: canceling both branches in reverse order should aggregate the cancel reasons into an array": { "status": "PASS" }, "ReadableStream teeing: failing to cancel the original stream should cause cancel() to reject on branches": { "status": "PASS" }, "ReadableStream teeing: erroring a teed stream should properly handle canceled branches": { "status": "PASS" }, "ReadableStream teeing: erroring a teed stream should error both branches": { "status": "PASS" }, "ReadableStream teeing: closing the original should immediately close the branches": { "status": "PASS" }, "ReadableStream teeing: erroring the original should immediately error the branches": { "status": "PASS" }, "ReadableStream teeing: canceling branch1 should finish when branch2 reads until end of stream": { "status": "PASS" }, "ReadableStream teeing: canceling branch1 should finish when original stream errors": { "status": "PASS" }, "ReadableStream teeing: canceling both branches in sequence with delay": { "status": "PASS" }, "ReadableStream teeing: failing to cancel when canceling both branches in sequence with delay": { "status": "PASS" }, "ReadableStreamTee should not use a modified ReadableStream constructor from the global object": { "status": "PASS" }, "ReadableStreamTee should not pull more chunks than can fit in the branch queue": { "status": "PASS" }, "ReadableStreamTee should only pull enough to fill the emptiest queue": { "status": "PASS" }, "ReadableStreamTee should not pull when original is already errored": { "status": "PASS" }, "ReadableStreamTee stops pulling when original stream errors while branch 1 is reading": { "status": "PASS" }, "ReadableStreamTee stops pulling when original stream errors while branch 2 is reading": { "status": "PASS" }, "ReadableStreamTee stops pulling when original stream errors while both branches are reading": { "status": "PASS" }, "ReadableStream teeing: enqueue() and close() while both branches are pulling": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/readable-streams/templated.any.js.json ================================================ { "Running templatedRSEmpty with ReadableStream (empty)": { "status": "PASS" }, "ReadableStream (empty): instances have the correct methods and properties": { "status": "PASS" }, "ReadableStream (empty): calling getReader with invalid arguments should throw appropriate errors": { "status": "PASS" }, "Running templatedRSEmptyReader with ReadableStream (empty) reader": { "status": "PASS" }, "ReadableStream (empty) reader: instances have the correct methods and properties": { "status": "PASS" }, "ReadableStream (empty) reader: locked should be true": { "status": "PASS" }, "ReadableStream (empty) reader: read() should never settle": { "status": "PASS" }, "ReadableStream (empty) reader: two read()s should both never settle": { "status": "PASS" }, "ReadableStream (empty) reader: read() should return distinct promises each time": { "status": "PASS" }, "ReadableStream (empty) reader: getReader() again on the stream should fail": { "status": "PASS" }, "ReadableStream (empty) reader: releasing the lock should reject all pending read requests": { "status": "PASS" }, "ReadableStream (empty) reader: releasing the lock should cause further read() calls to reject with a TypeError": { "status": "PASS" }, "ReadableStream (empty) reader: releasing the lock should cause closed calls to reject with a TypeError": { "status": "PASS" }, "ReadableStream (empty) reader: releasing the lock should cause locked to become false": { "status": "PASS" }, "ReadableStream (empty) reader: canceling via the reader should cause the reader to act closed": { "status": "PASS" }, "ReadableStream (empty) reader: canceling via the stream should fail": { "status": "PASS" }, "Running templatedRSClosed with ReadableStream (closed via call in start)": { "status": "PASS" }, "ReadableStream (closed via call in start): cancel() should return a distinct fulfilled promise each time": { "status": "PASS" }, "ReadableStream (closed via call in start): locked should be false": { "status": "PASS" }, "ReadableStream (closed via call in start): getReader() should be OK": { "status": "PASS" }, "ReadableStream (closed via call in start): should be able to acquire multiple readers if they are released in succession": { "status": "PASS" }, "ReadableStream (closed via call in start): should not be able to acquire a second reader if we don't release the first one": { "status": "PASS" }, "Running templatedRSClosedReader with ReadableStream reader (closed before getting reader)": { "status": "PASS" }, "ReadableStream reader (closed before getting reader): read() should fulfill with { value: undefined, done: true }": { "status": "PASS" }, "ReadableStream reader (closed before getting reader): read() multiple times should fulfill with { value: undefined, done: true }": { "status": "PASS" }, "ReadableStream reader (closed before getting reader): read() should work when used within another read() fulfill callback": { "status": "PASS" }, "ReadableStream reader (closed before getting reader): closed should fulfill with undefined": { "status": "PASS" }, "ReadableStream reader (closed before getting reader): releasing the lock should cause closed to reject and change identity": { "status": "PASS" }, "ReadableStream reader (closed before getting reader): cancel() should return a distinct fulfilled promise each time": { "status": "PASS" }, "Running templatedRSClosedReader with ReadableStream reader (closed after getting reader)": { "status": "PASS" }, "ReadableStream reader (closed after getting reader): read() should fulfill with { value: undefined, done: true }": { "status": "PASS" }, "ReadableStream reader (closed after getting reader): read() multiple times should fulfill with { value: undefined, done: true }": { "status": "PASS" }, "ReadableStream reader (closed after getting reader): read() should work when used within another read() fulfill callback": { "status": "PASS" }, "ReadableStream reader (closed after getting reader): closed should fulfill with undefined": { "status": "PASS" }, "ReadableStream reader (closed after getting reader): releasing the lock should cause closed to reject and change identity": { "status": "PASS" }, "ReadableStream reader (closed after getting reader): cancel() should return a distinct fulfilled promise each time": { "status": "PASS" }, "Running templatedRSClosed with ReadableStream (closed via cancel)": { "status": "PASS" }, "ReadableStream (closed via cancel): cancel() should return a distinct fulfilled promise each time": { "status": "PASS" }, "ReadableStream (closed via cancel): locked should be false": { "status": "PASS" }, "ReadableStream (closed via cancel): getReader() should be OK": { "status": "PASS" }, "ReadableStream (closed via cancel): should be able to acquire multiple readers if they are released in succession": { "status": "PASS" }, "ReadableStream (closed via cancel): should not be able to acquire a second reader if we don't release the first one": { "status": "PASS" }, "Running templatedRSClosedReader with ReadableStream reader (closed via cancel after getting reader)": { "status": "PASS" }, "ReadableStream reader (closed via cancel after getting reader): read() should fulfill with { value: undefined, done: true }": { "status": "PASS" }, "ReadableStream reader (closed via cancel after getting reader): read() multiple times should fulfill with { value: undefined, done: true }": { "status": "PASS" }, "ReadableStream reader (closed via cancel after getting reader): read() should work when used within another read() fulfill callback": { "status": "PASS" }, "ReadableStream reader (closed via cancel after getting reader): closed should fulfill with undefined": { "status": "PASS" }, "ReadableStream reader (closed via cancel after getting reader): releasing the lock should cause closed to reject and change identity": { "status": "PASS" }, "ReadableStream reader (closed via cancel after getting reader): cancel() should return a distinct fulfilled promise each time": { "status": "PASS" }, "Running templatedRSErrored with ReadableStream (errored via call in start)": { "status": "PASS" }, "ReadableStream (errored via call in start): getReader() should return a reader that acts errored": { "status": "PASS" }, "ReadableStream (errored via call in start): read() twice should give the error each time": { "status": "PASS" }, "ReadableStream (errored via call in start): locked should be false": { "status": "PASS" }, "Running templatedRSErroredSyncOnly with ReadableStream (errored via call in start)": { "status": "PASS" }, "ReadableStream (errored via call in start): should be able to obtain a second reader, with the correct closed promise": { "status": "PASS" }, "ReadableStream (errored via call in start): should not be able to obtain additional readers if we don't release the first lock": { "status": "PASS" }, "ReadableStream (errored via call in start): cancel() should return a distinct rejected promise each time": { "status": "PASS" }, "ReadableStream (errored via call in start): reader cancel() should return a distinct rejected promise each time": { "status": "PASS" }, "Running templatedRSErrored with ReadableStream (errored via returning a rejected promise in start)": { "status": "PASS" }, "ReadableStream (errored via returning a rejected promise in start): getReader() should return a reader that acts errored": { "status": "PASS" }, "ReadableStream (errored via returning a rejected promise in start): read() twice should give the error each time": { "status": "PASS" }, "ReadableStream (errored via returning a rejected promise in start): locked should be false": { "status": "PASS" }, "Running templatedRSErroredReader with ReadableStream (errored via returning a rejected promise in start) reader": { "status": "PASS" }, "ReadableStream (errored via returning a rejected promise in start) reader: closed should reject with the error": { "status": "PASS" }, "ReadableStream (errored via returning a rejected promise in start) reader: releasing the lock should cause closed to reject and change identity": { "status": "PASS" }, "ReadableStream (errored via returning a rejected promise in start) reader: read() should reject with the error": { "status": "PASS" }, "Running templatedRSErroredReader with ReadableStream reader (errored before getting reader)": { "status": "PASS" }, "ReadableStream reader (errored before getting reader): closed should reject with the error": { "status": "PASS" }, "ReadableStream reader (errored before getting reader): releasing the lock should cause closed to reject and change identity": { "status": "PASS" }, "ReadableStream reader (errored before getting reader): read() should reject with the error": { "status": "PASS" }, "Running templatedRSErroredReader with ReadableStream reader (errored after getting reader)": { "status": "PASS" }, "ReadableStream reader (errored after getting reader): closed should reject with the error": { "status": "PASS" }, "ReadableStream reader (errored after getting reader): releasing the lock should cause closed to reject and change identity": { "status": "PASS" }, "ReadableStream reader (errored after getting reader): read() should reject with the error": { "status": "PASS" }, "Running templatedRSTwoChunksOpenReader with ReadableStream (two chunks enqueued, still open) reader": { "status": "PASS" }, "ReadableStream (two chunks enqueued, still open) reader: calling read() twice without waiting will eventually give both chunks (sequential)": { "status": "PASS" }, "ReadableStream (two chunks enqueued, still open) reader: calling read() twice without waiting will eventually give both chunks (nested)": { "status": "PASS" }, "ReadableStream (two chunks enqueued, still open) reader: read() should return distinct promises each time": { "status": "PASS" }, "ReadableStream (two chunks enqueued, still open) reader: cancel() after a read() should still give that single read result": { "status": "PASS" }, "Running templatedRSTwoChunksClosedReader with ReadableStream (two chunks enqueued, then closed) reader": { "status": "PASS" }, "ReadableStream (two chunks enqueued, then closed) reader: third read(), without waiting, should give { value: undefined, done: true } (sequential)": { "status": "PASS" }, "ReadableStream (two chunks enqueued, then closed) reader: third read(), without waiting, should give { value: undefined, done: true } (nested)": { "status": "PASS" }, "ReadableStream (two chunks enqueued, then closed) reader: draining the stream via read() should cause the reader closed promise to fulfill, but locked stays true": { "status": "PASS" }, "ReadableStream (two chunks enqueued, then closed) reader: releasing the lock after the stream is closed should cause locked to become false": { "status": "PASS" }, "ReadableStream (two chunks enqueued, then closed) reader: releasing the lock should cause further read() calls to reject with a TypeError": { "status": "PASS" }, "ReadableStream (two chunks enqueued, then closed) reader: reader's closed property always returns the same promise": { "status": "PASS" }, "Running templatedRSThrowAfterCloseOrError with ReadableStream": { "status": "PASS" }, "ReadableStream: enqueue() throws after close()": { "status": "PASS" }, "ReadableStream: enqueue() throws after enqueue() and close()": { "status": "PASS" }, "ReadableStream: enqueue() throws after error()": { "status": "PASS" }, "ReadableStream: close() throws after error()": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/backpressure.any.js.json ================================================ { "backpressure allows no transforms with a default identity transform and no reader": { "status": "PASS" }, "backpressure only allows one transform() with a identity transform with a readable HWM of 1 and no reader": { "status": "PASS" }, "transform() should keep being called as long as there is no backpressure": { "status": "PASS" }, "writes should resolve as soon as transform completes": { "status": "PASS" }, "calling pull() before the first write() with backpressure should work": { "status": "PASS" }, "transform() should be able to read the chunk it just enqueued": { "status": "PASS" }, "blocking transform() should cause backpressure": { "status": "PASS" }, "writer.closed should resolve after readable is canceled during start": { "status": "PASS" }, "writer.closed should resolve after readable is canceled with backpressure": { "status": "PASS" }, "writer.closed should resolve after readable is canceled with no backpressure": { "status": "PASS" }, "cancelling the readable should cause a pending write to resolve": { "status": "PASS" }, "cancelling the readable side of a TransformStream should abort an empty pipe": { "status": "PASS" }, "cancelling the readable side of a TransformStream should abort an empty pipe after startup": { "status": "PASS" }, "cancelling the readable side of a TransformStream should abort a full pipe": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/cancel.any.js.json ================================================ { "cancelling the readable side should call transformer.cancel()": { "status": "FAIL" }, "cancelling the readable side should reject if transformer.cancel() throws": { "status": "FAIL" }, "aborting the writable side should call transformer.abort()": { "status": "FAIL" }, "aborting the writable side should reject if transformer.cancel() throws": { "status": "FAIL" }, "closing the writable side should reject if a parallel transformer.cancel() throws": { "status": "FAIL" }, "readable.cancel() and a parallel writable.close() should reject if a transformer.cancel() calls controller.error()": { "status": "FAIL" }, "writable.abort() and readable.cancel() should reject if a transformer.cancel() calls controller.error()": { "status": "FAIL" }, "readable.cancel() should not call cancel() when flush() is already called from writable.close()": { "status": "PASS" }, "readable.cancel() should not call cancel() again when already called from writable.abort()": { "status": "FAIL" }, "writable.close() should not call flush() when cancel() is already called from readable.cancel()": { "status": "FAIL" }, "writable.abort() should not call cancel() again when already called from readable.cancel()": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/errors.any.js.json ================================================ { "TransformStream errors thrown in transform put the writable and readable in an errored state": { "status": "PASS" }, "TransformStream errors thrown in flush put the writable and readable in an errored state": { "status": "PASS" }, "errored TransformStream should not enqueue new chunks": { "status": "PASS" }, "TransformStream transformer.start() rejected promise should error the stream": { "status": "PASS" }, "when controller.error is followed by a rejection, the error reason should come from controller.error": { "status": "PASS" }, "TransformStream constructor should throw when start does": { "status": "PASS" }, "when strategy.size throws inside start(), the constructor should throw the same error": { "status": "PASS" }, "when strategy.size calls controller.error() then throws, the constructor should throw the first error": { "status": "PASS" }, "cancelling the readable side should error the writable": { "status": "PASS" }, "it should be possible to error the readable between close requested and complete": { "status": "PASS" }, "an exception from transform() should error the stream if terminate has been requested but not completed": { "status": "PASS" }, "abort should set the close reason for the writable when it happens before cancel during start, and cancel should reject": { "status": "PASS" }, "abort should set the close reason for the writable when it happens before cancel during underlying sink write, but cancel should still succeed": { "status": "PASS" }, "controller.error() should do nothing the second time it is called": { "status": "PASS" }, "controller.error() should close writable immediately after readable.cancel()": { "status": "FAIL" }, "controller.error() should do nothing after readable.cancel() resolves": { "status": "PASS" }, "controller.error() should do nothing after writable.abort() has completed": { "status": "PASS" }, "controller.error() should do nothing after a transformer method has thrown an exception": { "status": "PASS" }, "erroring during write with backpressure should result in the write failing": { "status": "PASS" }, "a write() that was waiting for backpressure should reject if the writable is aborted": { "status": "PASS" }, "the readable should be errored with the reason passed to the writable abort() method": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/flush.any.js.json ================================================ { "TransformStream flush is called immediately when the writable is closed, if no writes are queued": { "status": "PASS" }, "TransformStream flush is called after all queued writes finish, once the writable is closed": { "status": "PASS" }, "TransformStream flush gets a chance to enqueue more into the readable": { "status": "PASS" }, "TransformStream flush gets a chance to enqueue more into the readable, and can then async close": { "status": "PASS" }, "error() during flush should cause writer.close() to reject": { "status": "PASS" }, "closing the writable side should call transformer.flush() and a parallel readable.cancel() should not reject": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/general.any.js.json ================================================ { "TransformStream can be constructed with a transform function": { "status": "PASS" }, "TransformStream can be constructed with no transform function": { "status": "PASS" }, "TransformStream writable starts in the writable state": { "status": "PASS" }, "Identity TransformStream: can read from readable what is put into writable": { "status": "PASS" }, "Uppercaser sync TransformStream: can read from readable transformed version of what is put into writable": { "status": "PASS" }, "Uppercaser-doubler sync TransformStream: can read both chunks put into the readable": { "status": "PASS" }, "Uppercaser async TransformStream: can read from readable transformed version of what is put into writable": { "status": "PASS" }, "Uppercaser-doubler async TransformStream: can read both chunks put into the readable": { "status": "PASS" }, "TransformStream: by default, closing the writable closes the readable (when there are no queued writes)": { "status": "PASS" }, "TransformStream: by default, closing the writable waits for transforms to finish before closing both": { "status": "PASS" }, "TransformStream: by default, closing the writable closes the readable after sync enqueues and async done": { "status": "PASS" }, "TransformStream: by default, closing the writable closes the readable after async enqueues and async done": { "status": "PASS" }, "Transform stream should call transformer methods as methods": { "status": "PASS" }, "methods should not not have .apply() or .call() called": { "status": "PASS" }, "TransformStream start, transform, and flush should be strictly ordered": { "status": "PASS" }, "it should be possible to call transform() synchronously": { "status": "PASS" }, "closing the writable should close the readable when there are no queued chunks, even with backpressure": { "status": "PASS" }, "enqueue() should throw after controller.terminate()": { "status": "PASS" }, "enqueue() should throw after readable.cancel()": { "status": "PASS" }, "controller.terminate() should do nothing the second time it is called": { "status": "PASS" }, "terminate() should abort writable immediately after readable.cancel()": { "status": "FAIL" }, "terminate() should do nothing after readable.cancel() resolves": { "status": "PASS" }, "start() should not be called twice": { "status": "PASS" }, "specifying a defined readableType should throw": { "status": "FAIL" }, "specifying a defined writableType should throw": { "status": "FAIL" }, "Subclassing TransformStream should work": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/lipfuzz.any.js.json ================================================ { "testing \"\" (length 1)": { "status": "PASS" }, "testing \"\" (length 0)": { "status": "PASS" }, "testing \"{{in1}}\" (length 1)": { "status": "PASS" }, "testing \"z{{in1}}\" (length 1)": { "status": "PASS" }, "testing \"{{in1}}q\" (length 1)": { "status": "PASS" }, "testing \"{{in1}}{{in1}\" (length 1)": { "status": "PASS" }, "testing \"{{in1}}{{in1},}\" (length 2)": { "status": "PASS" }, "testing \"{{in1,}}\" (length 2)": { "status": "PASS" }, "testing \"{{,in1}}\" (length 2)": { "status": "PASS" }, "testing \"{,{in1}}\" (length 2)": { "status": "PASS" }, "testing \"{{,in1}\" (length 2)": { "status": "PASS" }, "testing \"{\" (length 1)": { "status": "PASS" }, "testing \"{,\" (length 2)": { "status": "PASS" }, "testing \"{,{,i,n,1,},}\" (length 7)": { "status": "PASS" }, "testing \"{{in1}}{{in2}}{{in1}}\" (length 1)": { "status": "PASS" }, "testing \"{{wrong}}\" (length 1)": { "status": "PASS" }, "testing \"{{wron,g}}\" (length 2)": { "status": "PASS" }, "testing \"{{quine}}\" (length 1)": { "status": "PASS" }, "testing \"{{bogusPartial}}\" (length 1)": { "status": "PASS" }, "testing \"{{bogusPartial}}}\" (length 1)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/patched-global.any.js.json ================================================ { "TransformStream constructor should not call setters for highWaterMark or size": { "status": "PASS" }, "TransformStream should use the original value of ReadableStream and WritableStream": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/properties.any.js.json ================================================ { "transformer method start should be called with the right number of arguments": { "status": "PASS" }, "transformer method start should be called even when it's located on the prototype chain": { "status": "PASS" }, "transformer method transform should be called with the right number of arguments": { "status": "PASS" }, "transformer method transform should be called even when it's located on the prototype chain": { "status": "PASS" }, "transformer method flush should be called with the right number of arguments": { "status": "PASS" }, "transformer method flush should be called even when it's located on the prototype chain": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/reentrant-strategies.any.js.json ================================================ { "enqueue() inside size() should work": { "status": "PASS" }, "terminate() inside size() should work": { "status": "PASS" }, "error() inside size() should work": { "status": "PASS" }, "desiredSize inside size() should work": { "status": "PASS" }, "readable cancel() inside size() should work": { "status": "PASS" }, "pipeTo() inside size() should work": { "status": "PASS" }, "read() inside of size() should work": { "status": "PASS" }, "writer.write() inside size() should work": { "status": "PASS" }, "synchronous writer.write() inside size() should work": { "status": "PASS" }, "writer.close() inside size() should work": { "status": "PASS" }, "writer.abort() inside size() should work": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/strategies.any.js.json ================================================ { "writableStrategy highWaterMark should work": { "status": "PASS" }, "readableStrategy highWaterMark should work": { "status": "PASS" }, "writable should have the correct size() function": { "status": "PASS" }, "default writable strategy should be equivalent to { highWaterMark: 1 }": { "status": "PASS" }, "default readable strategy should be equivalent to { highWaterMark: 0 }": { "status": "PASS" }, "a RangeError should be thrown for an invalid highWaterMark": { "status": "FAIL" }, "writableStrategy highWaterMark should be converted to a number": { "status": "PASS" }, "readableStrategy highWaterMark should be converted to a number": { "status": "PASS" }, "a bad readableStrategy size function should cause writer.write() to reject on an identity transform": { "status": "PASS" }, "a bad readableStrategy size function should error the stream on enqueue even when transformer.transform() catches the exception": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/transform-streams/terminate.any.js.json ================================================ { "controller.terminate() should error pipeTo()": { "status": "PASS" }, "controller.terminate() should prevent remaining chunks from being processed": { "status": "PASS" }, "controller.enqueue() should throw after controller.terminate()": { "status": "PASS" }, "controller.error() after controller.terminate() with queued chunk should error the readable": { "status": "PASS" }, "controller.error() after controller.terminate() without queued chunk should do nothing": { "status": "PASS" }, "controller.terminate() inside flush() should not prevent writer.close() from succeeding": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/aborting.any.js.json ================================================ { "Aborting a WritableStream before it starts should cause the writer's unsettled ready promise to reject": { "status": "PASS" }, "Aborting a WritableStream should cause the writer's fulfilled ready promise to reset to a rejected one": { "status": "PASS" }, "abort() on a released writer rejects": { "status": "PASS" }, "Aborting a WritableStream immediately prevents future writes": { "status": "PASS" }, "Aborting a WritableStream prevents further writes after any that are in progress": { "status": "PASS" }, "Fulfillment value of writer.abort() call must be undefined even if the underlying sink returns a non-undefined value": { "status": "PASS" }, "WritableStream if sink's abort throws, the promise returned by writer.abort() rejects": { "status": "PASS" }, "WritableStream if sink's abort throws, the promise returned by multiple writer.abort()s is the same and rejects": { "status": "PASS" }, "WritableStream if sink's abort throws, the promise returned by ws.abort() rejects": { "status": "PASS" }, "WritableStream if sink's abort throws, for an abort performed during a write, the promise returned by ws.abort() rejects": { "status": "PASS" }, "Aborting a WritableStream passes through the given reason": { "status": "PASS" }, "Aborting a WritableStream puts it in an errored state with the error passed to abort()": { "status": "PASS" }, "Aborting a WritableStream causes any outstanding write() promises to be rejected with the reason supplied": { "status": "PASS" }, "Closing but then immediately aborting a WritableStream causes the stream to error": { "status": "PASS" }, "Closing a WritableStream and aborting it while it closes causes the stream to ignore the abort attempt": { "status": "PASS" }, "Aborting a WritableStream after it is closed is a no-op": { "status": "PASS" }, "WritableStream should NOT call underlying sink's close if no abort is supplied (historical)": { "status": "PASS" }, "returning a thenable from abort() should work": { "status": "PASS" }, ".closed should not resolve before fulfilled write()": { "status": "PASS" }, ".closed should not resolve before rejected write(); write() error should not overwrite abort() error": { "status": "PASS" }, "writes should be satisfied in order when aborting": { "status": "PASS" }, "writes should be satisfied in order after rejected write when aborting": { "status": "PASS" }, "close() should reject with abort reason why abort() is first error": { "status": "PASS" }, "underlying abort() should not be called until underlying write() completes": { "status": "PASS" }, "underlying abort() should not be called if underlying close() has started": { "status": "PASS" }, "if underlying close() has started and then rejects, the abort() and close() promises should reject with the underlying close rejection reason": { "status": "PASS" }, "an abort() that happens during a write() should trigger the underlying abort() even with a close() queued": { "status": "PASS" }, "if a writer is created for a stream with a pending abort, its ready should be rejected with the abort error": { "status": "PASS" }, "writer close() promise should resolve before abort() promise": { "status": "PASS" }, "writer.ready should reject on controller error without waiting for underlying write": { "status": "PASS" }, "writer.abort() while there is an in-flight write, and then finish the write with rejection": { "status": "PASS" }, "writer.abort(), controller.error() while there is an in-flight write, and then finish the write": { "status": "PASS" }, "writer.abort(), controller.error() while there is an in-flight close, and then finish the close": { "status": "PASS" }, "controller.error(), writer.abort() while there is an in-flight write, and then finish the write": { "status": "PASS" }, "controller.error(), writer.abort() while there is an in-flight close, and then finish the close": { "status": "PASS" }, "releaseLock() while aborting should reject the original closed promise": { "status": "PASS" }, "releaseLock() during delayed async abort() should reject the writer.closed promise": { "status": "PASS" }, "sink abort() should not be called until sink start() is done": { "status": "PASS" }, "if start attempts to error the controller after abort() has been called, then it should lose": { "status": "PASS" }, "stream abort() promise should still resolve if sink start() rejects": { "status": "PASS" }, "writer abort() during sink start() should replace the writer.ready promise synchronously": { "status": "PASS" }, "promises returned from other writer methods should be rejected when writer abort() happens during sink start()": { "status": "PASS" }, "abort() should succeed despite rejection from write": { "status": "PASS" }, "abort() should be rejected with the rejection returned from close()": { "status": "PASS" }, "a rejecting sink.write() should not prevent sink.abort() from being called": { "status": "PASS" }, "when start errors after stream abort(), underlying sink abort() should be called anyway": { "status": "PASS" }, "when calling abort() twice on the same stream, both should give the same promise that fulfills with undefined": { "status": "PASS" }, "when calling abort() twice on the same stream, but sequentially so so there's no pending abort the second time, both should fulfill with undefined": { "status": "PASS" }, "calling abort() on an errored stream should fulfill with undefined": { "status": "PASS" }, "sink abort() should not be called if stream was erroring due to controller.error() before abort() was called": { "status": "PASS" }, "sink abort() should not be called if stream was erroring due to bad strategy before abort() was called": { "status": "PASS" }, "abort with no arguments should set the stored error to undefined": { "status": "PASS" }, "abort with an undefined argument should set the stored error to undefined": { "status": "PASS" }, "abort with a string argument should set the stored error to that argument": { "status": "PASS" }, "abort on a locked stream should reject": { "status": "PASS" }, "WritableStreamDefaultController.signal": { "status": "FAIL" }, "the abort signal is signalled synchronously - write": { "status": "FAIL" }, "the abort signal is signalled synchronously - close": { "status": "FAIL" }, "the abort signal is not signalled on error": { "status": "FAIL" }, "the abort signal is not signalled on write failure": { "status": "FAIL" }, "the abort signal is not signalled on close failure": { "status": "FAIL" }, "recursive abort() call from abort() aborting signal (not started)": { "status": "FAIL" }, "recursive abort() call from abort() aborting signal": { "status": "FAIL" }, "recursive close() call from abort() aborting signal (not started)": { "status": "FAIL" }, "recursive close() call from abort() aborting signal": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/bad-strategies.any.js.json ================================================ { "Writable stream: throwing strategy.size getter": { "status": "PASS" }, "reject any non-function value for strategy.size": { "status": "PASS" }, "Writable stream: throwing strategy.highWaterMark getter": { "status": "PASS" }, "Writable stream: invalid strategy.highWaterMark": { "status": "PASS" }, "Writable stream: throwing strategy.size method": { "status": "PASS" }, "Writable stream: invalid strategy.size return value": { "status": "PASS" }, "Writable stream: invalid size beats invalid highWaterMark": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/bad-underlying-sinks.any.js.json ================================================ { "start: errors in start cause WritableStream constructor to throw": { "status": "PASS" }, "close: throwing method should cause writer close() and ready to reject": { "status": "PASS" }, "close: returning a rejected promise should cause writer close() and ready to reject": { "status": "PASS" }, "close: throwing getter should cause constructor to throw": { "status": "PASS" }, "write: throwing getter should cause write() and closed to reject": { "status": "PASS" }, "write: throwing method should cause write() and closed to reject": { "status": "PASS" }, "write: returning a promise that becomes rejected after the writer write() should cause writer write() and ready to reject": { "status": "PASS" }, "write: returning a rejected promise (second write) should cause writer write() and ready to reject": { "status": "PASS" }, "start: non-function start method": { "status": "PASS" }, "write: non-function write method": { "status": "PASS" }, "close: non-function close method": { "status": "PASS" }, "abort: non-function abort method with .apply": { "status": "PASS" }, "abort: throwing getter should cause abort() and closed to reject": { "status": "PASS" }, "abort: throwing method should cause abort() and closed to reject": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/byte-length-queuing-strategy.any.js.json ================================================ { "Closing a writable stream with in-flight writes below the high water mark delays the close call properly": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/close.any.js.json ================================================ { "fulfillment value of writer.close() call must be undefined even if the underlying sink returns a non-undefined value": { "status": "PASS" }, "when sink calls error asynchronously while sink close is in-flight, the stream should not become errored": { "status": "PASS" }, "when sink calls error synchronously while closing, the stream should not become errored": { "status": "PASS" }, "when the sink throws during close, and the close is requested while a write is still in-flight, the stream should become errored during the close": { "status": "PASS" }, "releaseLock on a stream with a pending write in which the stream has been errored": { "status": "PASS" }, "releaseLock on a stream with a pending close in which controller.error() was called": { "status": "PASS" }, "when close is called on a WritableStream in writable state, ready should return a fulfilled promise": { "status": "PASS" }, "when close is called on a WritableStream in waiting state, ready promise should be fulfilled": { "status": "PASS" }, "when close is called on a WritableStream in waiting state, ready should be fulfilled immediately even if close takes a long time": { "status": "PASS" }, "returning a thenable from close() should work": { "status": "PASS" }, "releaseLock() should not change the result of sync close()": { "status": "PASS" }, "releaseLock() should not change the result of async close()": { "status": "PASS" }, "close() should set state to CLOSED even if writer has detached": { "status": "PASS" }, "the promise returned by async abort during close should resolve": { "status": "PASS" }, "promises must fulfill/reject in the expected order on closure": { "status": "PASS" }, "promises must fulfill/reject in the expected order on aborted closure": { "status": "PASS" }, "promises must fulfill/reject in the expected order on aborted and errored closure": { "status": "PASS" }, "close() should not reject until no sink methods are in flight": { "status": "PASS" }, "ready promise should be initialised as fulfilled for a writer on a closed stream": { "status": "PASS" }, "close() on a writable stream should work": { "status": "PASS" }, "close() on a locked stream should reject": { "status": "PASS" }, "close() on an erroring stream should reject": { "status": "PASS" }, "close() on an errored stream should reject": { "status": "PASS" }, "close() on an closed stream should reject": { "status": "PASS" }, "close() on a stream with a pending close should reject": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/constructor.any.js.json ================================================ { "controller argument should be passed to start method": { "status": "PASS" }, "controller argument should be passed to write method": { "status": "PASS" }, "controller argument should not be passed to close method": { "status": "PASS" }, "highWaterMark should be reflected to desiredSize": { "status": "PASS" }, "WritableStream should be writable and ready should fulfill immediately if the strategy does not apply backpressure": { "status": "PASS" }, "WritableStream should be constructible with no arguments": { "status": "PASS" }, "WritableStream can't be constructed with a defined type": { "status": "PASS" }, "underlyingSink argument should be converted after queuingStrategy argument": { "status": "PASS" }, "WritableStream instances should have standard methods and properties": { "status": "PASS" }, "WritableStreamDefaultController constructor should throw": { "status": "PASS" }, "WritableStreamDefaultController constructor should throw when passed an initialised WritableStream": { "status": "PASS" }, "WritableStreamDefaultWriter should throw unless passed a WritableStream": { "status": "PASS" }, "WritableStreamDefaultWriter constructor should throw when stream argument is locked": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/count-queuing-strategy.any.js.json ================================================ { "Can construct a writable stream with a valid CountQueuingStrategy": { "status": "PASS" }, "Correctly governs the value of a WritableStream's state property (HWM = 0)": { "status": "PASS" }, "Correctly governs the value of a WritableStream's state property (HWM = 4)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/error.any.js.json ================================================ { "controller.error() should error the stream": { "status": "PASS" }, "controller.error() on erroring stream should not throw": { "status": "PASS" }, "surplus calls to controller.error() should be a no-op": { "status": "PASS" }, "controller.error() on errored stream should not throw": { "status": "PASS" }, "controller.error() on closed stream should not throw": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/floating-point-total-queue-size.any.js.json ================================================ { "Floating point arithmetic must manifest near NUMBER.MAX_SAFE_INTEGER (total ends up positive)": { "status": "PASS" }, "Floating point arithmetic must manifest near 0 (total ends up positive, but clamped)": { "status": "PASS" }, "Floating point arithmetic must manifest near 0 (total ends up positive, and not clamped)": { "status": "PASS" }, "Floating point arithmetic must manifest near 0 (total ends up zero)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/general.any.js.json ================================================ { "desiredSize on a released writer": { "status": "PASS" }, "desiredSize initial value": { "status": "PASS" }, "desiredSize on a writer for a closed stream": { "status": "PASS" }, "desiredSize on a writer for an errored stream": { "status": "PASS" }, "ws.getWriter() on a closing WritableStream": { "status": "PASS" }, "ws.getWriter() on a closed WritableStream": { "status": "PASS" }, "ws.getWriter() on an aborted WritableStream": { "status": "PASS" }, "ws.getWriter() on an errored WritableStream": { "status": "PASS" }, "closed and ready on a released writer": { "status": "PASS" }, "WritableStream should call underlying sink methods as methods": { "status": "PASS" }, "methods should not not have .apply() or .call() called": { "status": "PASS" }, "WritableStream's strategy.size should not be called as a method": { "status": "PASS" }, "redundant releaseLock() is no-op": { "status": "PASS" }, "ready promise should fire before closed on releaseLock": { "status": "PASS" }, "Subclassing WritableStream should work": { "status": "PASS" }, "the locked getter should return true if the stream has a writer": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/properties.any.js.json ================================================ { "sink method start should be called with the right number of arguments": { "status": "PASS" }, "sink method start should be called even when it's located on the prototype chain": { "status": "PASS" }, "sink method write should be called with the right number of arguments": { "status": "PASS" }, "sink method write should be called even when it's located on the prototype chain": { "status": "PASS" }, "sink method close should be called with the right number of arguments": { "status": "PASS" }, "sink method close should be called even when it's located on the prototype chain": { "status": "PASS" }, "sink method abort should be called with the right number of arguments": { "status": "PASS" }, "sink method abort should be called even when it's located on the prototype chain": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/reentrant-strategy.any.js.json ================================================ { "writes should be written in the standard order": { "status": "PASS" }, "writer.write() promises should resolve in the standard order": { "status": "PASS" }, "controller.error() should work when called from within strategy.size()": { "status": "PASS" }, "close() should work when called from within strategy.size()": { "status": "PASS" }, "abort() should work when called from within strategy.size()": { "status": "PASS" }, "releaseLock() should abort the write() when called within strategy.size()": { "status": "PASS" }, "original reader should error when new reader is created within strategy.size()": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/start.any.js.json ================================================ { "underlying sink's write should not be called until start finishes": { "status": "PASS" }, "underlying sink's close should not be called until start finishes": { "status": "PASS" }, "underlying sink's write or close should not be called if start throws": { "status": "PASS" }, "underlying sink's write or close should not be invoked if the promise returned by start is rejected": { "status": "PASS" }, "returning a thenable from start() should work": { "status": "PASS" }, "controller.error() during start should cause writes to fail": { "status": "PASS" }, "controller.error() during async start should cause existing writes to fail": { "status": "PASS" }, "when start() rejects, writer promises should reject in standard order": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/streams/writable-streams/write.any.js.json ================================================ { "WritableStream should complete asynchronous writes before close resolves": { "status": "PASS" }, "WritableStream should complete synchronous writes before close resolves": { "status": "PASS" }, "fulfillment value of ws.write() call should be undefined even if the underlying sink returns a non-undefined value": { "status": "PASS" }, "WritableStream should transition to waiting until write is acknowledged": { "status": "PASS" }, "when write returns a rejected promise, queued writes and close should be cleared": { "status": "PASS" }, "when sink's write throws an error, the stream should become errored and the promise should reject": { "status": "PASS" }, "writer.write(), ready and closed reject with the error passed to controller.error() made before sink.write rejection": { "status": "PASS" }, "a large queue of writes should be processed completely": { "status": "PASS" }, "WritableStreamDefaultWriter should work when manually constructed": { "status": "PASS" }, "returning a thenable from write() should work": { "status": "PASS" }, "failing DefaultWriter constructor should not release an existing writer": { "status": "PASS" }, "write() on a stream with HWM 0 should not cause the ready Promise to resolve": { "status": "PASS" }, "writing to a released writer should reject the returned promise": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/historical.any.js.json ================================================ { "searchParams on location object": { "status": "FAIL" }, "Setting URL's href attribute and base URLs": { "status": "FAIL" }, "URL.domainToASCII should be undefined": { "status": "PASS" }, "URL.domainToUnicode should be undefined": { "status": "PASS" }, "URL: no structured serialize/deserialize support": { "status": "PASS" }, "URLSearchParams: no structured serialize/deserialize support": { "status": "FAIL" }, "Constructor only takes strings": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/url/url-constructor.any.js.json ================================================ { "Loading data…": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <\t :foo.com \n> against ": { "status": "PASS" }, "Parsing: < foo.com > against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <> against ": { "status": "PASS" }, "Parsing: < \t> against ": { "status": "PASS" }, "Parsing: <:foo.com/> against ": { "status": "PASS" }, "Parsing: <:foo.com\\> against ": { "status": "PASS" }, "Parsing: <:> against ": { "status": "PASS" }, "Parsing: <:a> against ": { "status": "PASS" }, "Parsing: <:/> against ": { "status": "PASS" }, "Parsing: <:\\> against ": { "status": "PASS" }, "Parsing: <:#> against ": { "status": "PASS" }, "Parsing: <#> against ": { "status": "PASS" }, "Parsing: <#/> against ": { "status": "PASS" }, "Parsing: <#\\> against ": { "status": "PASS" }, "Parsing: <#;?> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <:23> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <\\x> against ": { "status": "PASS" }, "Parsing: <\\\\x\\hello> against ": { "status": "PASS" }, "Parsing: <::> against ": { "status": "PASS" }, "Parsing: <::23> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <[61:24:74]:98> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <#β> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: < File:c|////foo\\bar.html> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <\\\\server\\file> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <.> against ": { "status": "PASS" }, "Parsing: <..> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <./test.txt> against ": { "status": "PASS" }, "Parsing: <../test.txt> against ": { "status": "PASS" }, "Parsing: <../aaa/test.txt> against ": { "status": "PASS" }, "Parsing: <../../test.txt> against ": { "status": "PASS" }, "Parsing: <中/test.txt> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <\u0000\u001b\u0004\u0012 http://example.com/\u001f \r > without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <#> against ": { "status": "PASS" }, "Parsing: <#x> against ": { "status": "PASS" }, "Parsing: <#x> against ": { "status": "PASS" }, "Parsing: <#x> against ": { "status": "PASS" }, "Parsing: <#x:y> against ": { "status": "PASS" }, "Parsing: <#> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <../i> against ": { "status": "PASS" }, "Parsing: <../i> against ": { "status": "PASS" }, "Parsing: <../i> against ": { "status": "PASS" }, "Parsing: <../i> against ": { "status": "PASS" }, "Parsing: <../i> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <#i> against ": { "status": "PASS" }, "Parsing: <#i> against ": { "status": "PASS" }, "Parsing: <#i> against ": { "status": "PASS" }, "Parsing: <#i> against ": { "status": "PASS" }, "Parsing: <#i> against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: b> without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: b> without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: bar> without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <..> against ": { "status": "PASS" }, "Parsing: <..> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <..> against ": { "status": "PASS" }, "Parsing: <..> against ": { "status": "PASS" }, "Parsing: <> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <#x> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: <\\//pig> against ": { "status": "PASS" }, "Parsing: <\\/localhost//pig> against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: <\\\\\\.\\Y:> without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: <\\\\\\.\\y:> without base": { "status": "PASS" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: without base": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: <#x> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <..//path> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <../path> against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: > without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: <10.0.0.7:8080/foo.html> against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: <#link> against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: @[\\]^_`{|}~@host/> without base": { "status": "PASS" }, "Parsing: @[]^_`{|}~@host/> without base": { "status": "PASS" }, "Parsing: @[\\]^_`{|}~@host/> without base": { "status": "PASS" }, "Parsing: @[]^_`{|}~@host/> without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: @[\\]^_`{|}~> without base": { "status": "PASS" }, "Parsing: @[\\]^_`{|}~> without base": { "status": "PASS" }, "Parsing: ?@[\\]^_`{|}~> without base": { "status": "PASS" }, "Parsing: ?@[\\]^_`{|}~> without base": { "status": "PASS" }, "Parsing: ?@[\\]^_`{|}~> without base": { "status": "PASS" }, "Parsing: ?@[\\]^_`{|}~> without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: <#> without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: <> without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "PASS" }, "Parsing: against ": { "status": "FAIL" }, "Parsing: against ": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" }, "Parsing: without base": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/url-origin.any.js.json ================================================ { "Loading data…": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <\t :foo.com \n> against ": { "status": "PASS" }, "Origin parsing: < foo.com > against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <> against ": { "status": "PASS" }, "Origin parsing: < \t> against ": { "status": "PASS" }, "Origin parsing: <:foo.com/> against ": { "status": "PASS" }, "Origin parsing: <:foo.com\\> against ": { "status": "PASS" }, "Origin parsing: <:> against ": { "status": "PASS" }, "Origin parsing: <:a> against ": { "status": "PASS" }, "Origin parsing: <:/> against ": { "status": "PASS" }, "Origin parsing: <:\\> against ": { "status": "PASS" }, "Origin parsing: <:#> against ": { "status": "PASS" }, "Origin parsing: <#> against ": { "status": "PASS" }, "Origin parsing: <#/> against ": { "status": "PASS" }, "Origin parsing: <#\\> against ": { "status": "PASS" }, "Origin parsing: <#;?> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <:23> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <\\x> against ": { "status": "PASS" }, "Origin parsing: <\\\\x\\hello> against ": { "status": "PASS" }, "Origin parsing: <::> against ": { "status": "PASS" }, "Origin parsing: <::23> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <[61:24:74]:98> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <#β> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <.> against ": { "status": "PASS" }, "Origin parsing: <..> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <./test.txt> against ": { "status": "PASS" }, "Origin parsing: <../test.txt> against ": { "status": "PASS" }, "Origin parsing: <../aaa/test.txt> against ": { "status": "PASS" }, "Origin parsing: <../../test.txt> against ": { "status": "PASS" }, "Origin parsing: <中/test.txt> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <\u0000\u001b\u0004\u0012 http://example.com/\u001f \r > without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <#> against ": { "status": "PASS" }, "Origin parsing: <#x> against ": { "status": "PASS" }, "Origin parsing: <#x> against ": { "status": "PASS" }, "Origin parsing: <#x> against ": { "status": "PASS" }, "Origin parsing: <#x:y> against ": { "status": "PASS" }, "Origin parsing: <#> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <../i> against ": { "status": "PASS" }, "Origin parsing: <../i> against ": { "status": "PASS" }, "Origin parsing: <../i> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: <#i> against ": { "status": "PASS" }, "Origin parsing: <#i> against ": { "status": "PASS" }, "Origin parsing: <#i> against ": { "status": "PASS" }, "Origin parsing: <#i> against ": { "status": "PASS" }, "Origin parsing: <#i> against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: bar> without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: <#x> against ": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "FAIL" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "FAIL" }, "Origin parsing: without base": { "status": "FAIL" }, "Origin parsing: without base": { "status": "FAIL" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: against ": { "status": "PASS" }, "Origin parsing: @[\\]^_`{|}~@host/> without base": { "status": "PASS" }, "Origin parsing: @[]^_`{|}~@host/> without base": { "status": "PASS" }, "Origin parsing: @[\\]^_`{|}~@host/> without base": { "status": "PASS" }, "Origin parsing: @[]^_`{|}~@host/> without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: @[\\]^_`{|}~> without base": { "status": "PASS" }, "Origin parsing: @[\\]^_`{|}~> without base": { "status": "PASS" }, "Origin parsing: ?@[\\]^_`{|}~> without base": { "status": "PASS" }, "Origin parsing: ?@[\\]^_`{|}~> without base": { "status": "PASS" }, "Origin parsing: ?@[\\]^_`{|}~> without base": { "status": "PASS" }, "Origin parsing: ?@[\\]^_`{|}~> without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" }, "Origin parsing: without base": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/url-searchparams.any.js.json ================================================ { "URL.searchParams getter": { "status": "PASS" }, "URL.searchParams updating, clearing": { "status": "PASS" }, "URL.searchParams setter, invalid values": { "status": "PASS" }, "URL.searchParams and URL.search setters, update propagation": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/url/url-setters-stripping.any.js.json ================================================ { "Setting protocol with leading U+0000 (https:)": { "status": "PASS" }, "Setting protocol with U+0000 before inserted colon (https:)": { "status": "PASS" }, "Setting username with leading U+0000 (https:)": { "status": "PASS" }, "Setting username with middle U+0000 (https:)": { "status": "PASS" }, "Setting username with trailing U+0000 (https:)": { "status": "PASS" }, "Setting password with leading U+0000 (https:)": { "status": "PASS" }, "Setting password with middle U+0000 (https:)": { "status": "PASS" }, "Setting password with trailing U+0000 (https:)": { "status": "PASS" }, "Setting host with leading U+0000 (https:)": { "status": "PASS" }, "Setting hostname with leading U+0000 (https:)": { "status": "PASS" }, "Setting host with middle U+0000 (https:)": { "status": "PASS" }, "Setting hostname with middle U+0000 (https:)": { "status": "PASS" }, "Setting host with trailing U+0000 (https:)": { "status": "PASS" }, "Setting hostname with trailing U+0000 (https:)": { "status": "PASS" }, "Setting port with leading U+0000 (https:)": { "status": "PASS" }, "Setting port with middle U+0000 (https:)": { "status": "PASS" }, "Setting port with trailing U+0000 (https:)": { "status": "PASS" }, "Setting pathname with leading U+0000 (https:)": { "status": "PASS" }, "Setting pathname with middle U+0000 (https:)": { "status": "PASS" }, "Setting pathname with trailing U+0000 (https:)": { "status": "PASS" }, "Setting search with leading U+0000 (https:)": { "status": "PASS" }, "Setting search with middle U+0000 (https:)": { "status": "PASS" }, "Setting search with trailing U+0000 (https:)": { "status": "PASS" }, "Setting hash with leading U+0000 (https:)": { "status": "PASS" }, "Setting hash with middle U+0000 (https:)": { "status": "PASS" }, "Setting hash with trailing U+0000 (https:)": { "status": "PASS" }, "Setting protocol with leading U+0009 (https:)": { "status": "PASS" }, "Setting protocol with U+0009 before inserted colon (https:)": { "status": "PASS" }, "Setting username with leading U+0009 (https:)": { "status": "PASS" }, "Setting username with middle U+0009 (https:)": { "status": "PASS" }, "Setting username with trailing U+0009 (https:)": { "status": "PASS" }, "Setting password with leading U+0009 (https:)": { "status": "PASS" }, "Setting password with middle U+0009 (https:)": { "status": "PASS" }, "Setting password with trailing U+0009 (https:)": { "status": "PASS" }, "Setting host with leading U+0009 (https:)": { "status": "PASS" }, "Setting hostname with leading U+0009 (https:)": { "status": "PASS" }, "Setting host with middle U+0009 (https:)": { "status": "PASS" }, "Setting hostname with middle U+0009 (https:)": { "status": "PASS" }, "Setting host with trailing U+0009 (https:)": { "status": "PASS" }, "Setting hostname with trailing U+0009 (https:)": { "status": "PASS" }, "Setting port with leading U+0009 (https:)": { "status": "PASS" }, "Setting port with middle U+0009 (https:)": { "status": "PASS" }, "Setting port with trailing U+0009 (https:)": { "status": "PASS" }, "Setting pathname with leading U+0009 (https:)": { "status": "PASS" }, "Setting pathname with middle U+0009 (https:)": { "status": "PASS" }, "Setting pathname with trailing U+0009 (https:)": { "status": "PASS" }, "Setting search with leading U+0009 (https:)": { "status": "PASS" }, "Setting search with middle U+0009 (https:)": { "status": "PASS" }, "Setting search with trailing U+0009 (https:)": { "status": "PASS" }, "Setting hash with leading U+0009 (https:)": { "status": "PASS" }, "Setting hash with middle U+0009 (https:)": { "status": "PASS" }, "Setting hash with trailing U+0009 (https:)": { "status": "PASS" }, "Setting protocol with leading U+000A (https:)": { "status": "PASS" }, "Setting protocol with U+000A before inserted colon (https:)": { "status": "PASS" }, "Setting username with leading U+000A (https:)": { "status": "PASS" }, "Setting username with middle U+000A (https:)": { "status": "PASS" }, "Setting username with trailing U+000A (https:)": { "status": "PASS" }, "Setting password with leading U+000A (https:)": { "status": "PASS" }, "Setting password with middle U+000A (https:)": { "status": "PASS" }, "Setting password with trailing U+000A (https:)": { "status": "PASS" }, "Setting host with leading U+000A (https:)": { "status": "PASS" }, "Setting hostname with leading U+000A (https:)": { "status": "PASS" }, "Setting host with middle U+000A (https:)": { "status": "PASS" }, "Setting hostname with middle U+000A (https:)": { "status": "PASS" }, "Setting host with trailing U+000A (https:)": { "status": "PASS" }, "Setting hostname with trailing U+000A (https:)": { "status": "PASS" }, "Setting port with leading U+000A (https:)": { "status": "PASS" }, "Setting port with middle U+000A (https:)": { "status": "PASS" }, "Setting port with trailing U+000A (https:)": { "status": "PASS" }, "Setting pathname with leading U+000A (https:)": { "status": "PASS" }, "Setting pathname with middle U+000A (https:)": { "status": "PASS" }, "Setting pathname with trailing U+000A (https:)": { "status": "PASS" }, "Setting search with leading U+000A (https:)": { "status": "PASS" }, "Setting search with middle U+000A (https:)": { "status": "PASS" }, "Setting search with trailing U+000A (https:)": { "status": "PASS" }, "Setting hash with leading U+000A (https:)": { "status": "PASS" }, "Setting hash with middle U+000A (https:)": { "status": "PASS" }, "Setting hash with trailing U+000A (https:)": { "status": "PASS" }, "Setting protocol with leading U+000D (https:)": { "status": "PASS" }, "Setting protocol with U+000D before inserted colon (https:)": { "status": "PASS" }, "Setting username with leading U+000D (https:)": { "status": "PASS" }, "Setting username with middle U+000D (https:)": { "status": "PASS" }, "Setting username with trailing U+000D (https:)": { "status": "PASS" }, "Setting password with leading U+000D (https:)": { "status": "PASS" }, "Setting password with middle U+000D (https:)": { "status": "PASS" }, "Setting password with trailing U+000D (https:)": { "status": "PASS" }, "Setting host with leading U+000D (https:)": { "status": "PASS" }, "Setting hostname with leading U+000D (https:)": { "status": "PASS" }, "Setting host with middle U+000D (https:)": { "status": "PASS" }, "Setting hostname with middle U+000D (https:)": { "status": "PASS" }, "Setting host with trailing U+000D (https:)": { "status": "PASS" }, "Setting hostname with trailing U+000D (https:)": { "status": "PASS" }, "Setting port with leading U+000D (https:)": { "status": "PASS" }, "Setting port with middle U+000D (https:)": { "status": "PASS" }, "Setting port with trailing U+000D (https:)": { "status": "PASS" }, "Setting pathname with leading U+000D (https:)": { "status": "PASS" }, "Setting pathname with middle U+000D (https:)": { "status": "PASS" }, "Setting pathname with trailing U+000D (https:)": { "status": "PASS" }, "Setting search with leading U+000D (https:)": { "status": "PASS" }, "Setting search with middle U+000D (https:)": { "status": "PASS" }, "Setting search with trailing U+000D (https:)": { "status": "PASS" }, "Setting hash with leading U+000D (https:)": { "status": "PASS" }, "Setting hash with middle U+000D (https:)": { "status": "PASS" }, "Setting hash with trailing U+000D (https:)": { "status": "PASS" }, "Setting protocol with leading U+001F (https:)": { "status": "PASS" }, "Setting protocol with U+001F before inserted colon (https:)": { "status": "PASS" }, "Setting username with leading U+001F (https:)": { "status": "PASS" }, "Setting username with middle U+001F (https:)": { "status": "PASS" }, "Setting username with trailing U+001F (https:)": { "status": "PASS" }, "Setting password with leading U+001F (https:)": { "status": "PASS" }, "Setting password with middle U+001F (https:)": { "status": "PASS" }, "Setting password with trailing U+001F (https:)": { "status": "PASS" }, "Setting host with leading U+001F (https:)": { "status": "PASS" }, "Setting hostname with leading U+001F (https:)": { "status": "PASS" }, "Setting host with middle U+001F (https:)": { "status": "PASS" }, "Setting hostname with middle U+001F (https:)": { "status": "PASS" }, "Setting host with trailing U+001F (https:)": { "status": "PASS" }, "Setting hostname with trailing U+001F (https:)": { "status": "PASS" }, "Setting port with leading U+001F (https:)": { "status": "PASS" }, "Setting port with middle U+001F (https:)": { "status": "PASS" }, "Setting port with trailing U+001F (https:)": { "status": "PASS" }, "Setting pathname with leading U+001F (https:)": { "status": "PASS" }, "Setting pathname with middle U+001F (https:)": { "status": "PASS" }, "Setting pathname with trailing U+001F (https:)": { "status": "PASS" }, "Setting search with leading U+001F (https:)": { "status": "PASS" }, "Setting search with middle U+001F (https:)": { "status": "PASS" }, "Setting search with trailing U+001F (https:)": { "status": "PASS" }, "Setting hash with leading U+001F (https:)": { "status": "PASS" }, "Setting hash with middle U+001F (https:)": { "status": "PASS" }, "Setting hash with trailing U+001F (https:)": { "status": "PASS" }, "Setting protocol with leading U+0000 (wpt++:)": { "status": "PASS" }, "Setting protocol with U+0000 before inserted colon (wpt++:)": { "status": "PASS" }, "Setting username with leading U+0000 (wpt++:)": { "status": "PASS" }, "Setting username with middle U+0000 (wpt++:)": { "status": "PASS" }, "Setting username with trailing U+0000 (wpt++:)": { "status": "PASS" }, "Setting password with leading U+0000 (wpt++:)": { "status": "PASS" }, "Setting password with middle U+0000 (wpt++:)": { "status": "PASS" }, "Setting password with trailing U+0000 (wpt++:)": { "status": "PASS" }, "Setting host with leading U+0000 (wpt++:)": { "status": "PASS" }, "Setting hostname with leading U+0000 (wpt++:)": { "status": "PASS" }, "Setting host with middle U+0000 (wpt++:)": { "status": "PASS" }, "Setting hostname with middle U+0000 (wpt++:)": { "status": "PASS" }, "Setting host with trailing U+0000 (wpt++:)": { "status": "PASS" }, "Setting hostname with trailing U+0000 (wpt++:)": { "status": "PASS" }, "Setting port with leading U+0000 (wpt++:)": { "status": "PASS" }, "Setting port with middle U+0000 (wpt++:)": { "status": "PASS" }, "Setting port with trailing U+0000 (wpt++:)": { "status": "PASS" }, "Setting pathname with leading U+0000 (wpt++:)": { "status": "PASS" }, "Setting pathname with middle U+0000 (wpt++:)": { "status": "PASS" }, "Setting pathname with trailing U+0000 (wpt++:)": { "status": "PASS" }, "Setting search with leading U+0000 (wpt++:)": { "status": "PASS" }, "Setting search with middle U+0000 (wpt++:)": { "status": "PASS" }, "Setting search with trailing U+0000 (wpt++:)": { "status": "PASS" }, "Setting hash with leading U+0000 (wpt++:)": { "status": "PASS" }, "Setting hash with middle U+0000 (wpt++:)": { "status": "PASS" }, "Setting hash with trailing U+0000 (wpt++:)": { "status": "PASS" }, "Setting protocol with leading U+0009 (wpt++:)": { "status": "PASS" }, "Setting protocol with U+0009 before inserted colon (wpt++:)": { "status": "PASS" }, "Setting username with leading U+0009 (wpt++:)": { "status": "PASS" }, "Setting username with middle U+0009 (wpt++:)": { "status": "PASS" }, "Setting username with trailing U+0009 (wpt++:)": { "status": "PASS" }, "Setting password with leading U+0009 (wpt++:)": { "status": "PASS" }, "Setting password with middle U+0009 (wpt++:)": { "status": "PASS" }, "Setting password with trailing U+0009 (wpt++:)": { "status": "PASS" }, "Setting host with leading U+0009 (wpt++:)": { "status": "PASS" }, "Setting hostname with leading U+0009 (wpt++:)": { "status": "PASS" }, "Setting host with middle U+0009 (wpt++:)": { "status": "PASS" }, "Setting hostname with middle U+0009 (wpt++:)": { "status": "PASS" }, "Setting host with trailing U+0009 (wpt++:)": { "status": "PASS" }, "Setting hostname with trailing U+0009 (wpt++:)": { "status": "PASS" }, "Setting port with leading U+0009 (wpt++:)": { "status": "PASS" }, "Setting port with middle U+0009 (wpt++:)": { "status": "PASS" }, "Setting port with trailing U+0009 (wpt++:)": { "status": "PASS" }, "Setting pathname with leading U+0009 (wpt++:)": { "status": "PASS" }, "Setting pathname with middle U+0009 (wpt++:)": { "status": "PASS" }, "Setting pathname with trailing U+0009 (wpt++:)": { "status": "PASS" }, "Setting search with leading U+0009 (wpt++:)": { "status": "PASS" }, "Setting search with middle U+0009 (wpt++:)": { "status": "PASS" }, "Setting search with trailing U+0009 (wpt++:)": { "status": "PASS" }, "Setting hash with leading U+0009 (wpt++:)": { "status": "PASS" }, "Setting hash with middle U+0009 (wpt++:)": { "status": "PASS" }, "Setting hash with trailing U+0009 (wpt++:)": { "status": "PASS" }, "Setting protocol with leading U+000A (wpt++:)": { "status": "PASS" }, "Setting protocol with U+000A before inserted colon (wpt++:)": { "status": "PASS" }, "Setting username with leading U+000A (wpt++:)": { "status": "PASS" }, "Setting username with middle U+000A (wpt++:)": { "status": "PASS" }, "Setting username with trailing U+000A (wpt++:)": { "status": "PASS" }, "Setting password with leading U+000A (wpt++:)": { "status": "PASS" }, "Setting password with middle U+000A (wpt++:)": { "status": "PASS" }, "Setting password with trailing U+000A (wpt++:)": { "status": "PASS" }, "Setting host with leading U+000A (wpt++:)": { "status": "PASS" }, "Setting hostname with leading U+000A (wpt++:)": { "status": "PASS" }, "Setting host with middle U+000A (wpt++:)": { "status": "PASS" }, "Setting hostname with middle U+000A (wpt++:)": { "status": "PASS" }, "Setting host with trailing U+000A (wpt++:)": { "status": "PASS" }, "Setting hostname with trailing U+000A (wpt++:)": { "status": "PASS" }, "Setting port with leading U+000A (wpt++:)": { "status": "PASS" }, "Setting port with middle U+000A (wpt++:)": { "status": "PASS" }, "Setting port with trailing U+000A (wpt++:)": { "status": "PASS" }, "Setting pathname with leading U+000A (wpt++:)": { "status": "PASS" }, "Setting pathname with middle U+000A (wpt++:)": { "status": "PASS" }, "Setting pathname with trailing U+000A (wpt++:)": { "status": "PASS" }, "Setting search with leading U+000A (wpt++:)": { "status": "PASS" }, "Setting search with middle U+000A (wpt++:)": { "status": "PASS" }, "Setting search with trailing U+000A (wpt++:)": { "status": "PASS" }, "Setting hash with leading U+000A (wpt++:)": { "status": "PASS" }, "Setting hash with middle U+000A (wpt++:)": { "status": "PASS" }, "Setting hash with trailing U+000A (wpt++:)": { "status": "PASS" }, "Setting protocol with leading U+000D (wpt++:)": { "status": "PASS" }, "Setting protocol with U+000D before inserted colon (wpt++:)": { "status": "PASS" }, "Setting username with leading U+000D (wpt++:)": { "status": "PASS" }, "Setting username with middle U+000D (wpt++:)": { "status": "PASS" }, "Setting username with trailing U+000D (wpt++:)": { "status": "PASS" }, "Setting password with leading U+000D (wpt++:)": { "status": "PASS" }, "Setting password with middle U+000D (wpt++:)": { "status": "PASS" }, "Setting password with trailing U+000D (wpt++:)": { "status": "PASS" }, "Setting host with leading U+000D (wpt++:)": { "status": "PASS" }, "Setting hostname with leading U+000D (wpt++:)": { "status": "PASS" }, "Setting host with middle U+000D (wpt++:)": { "status": "PASS" }, "Setting hostname with middle U+000D (wpt++:)": { "status": "PASS" }, "Setting host with trailing U+000D (wpt++:)": { "status": "PASS" }, "Setting hostname with trailing U+000D (wpt++:)": { "status": "PASS" }, "Setting port with leading U+000D (wpt++:)": { "status": "PASS" }, "Setting port with middle U+000D (wpt++:)": { "status": "PASS" }, "Setting port with trailing U+000D (wpt++:)": { "status": "PASS" }, "Setting pathname with leading U+000D (wpt++:)": { "status": "PASS" }, "Setting pathname with middle U+000D (wpt++:)": { "status": "PASS" }, "Setting pathname with trailing U+000D (wpt++:)": { "status": "PASS" }, "Setting search with leading U+000D (wpt++:)": { "status": "PASS" }, "Setting search with middle U+000D (wpt++:)": { "status": "PASS" }, "Setting search with trailing U+000D (wpt++:)": { "status": "PASS" }, "Setting hash with leading U+000D (wpt++:)": { "status": "PASS" }, "Setting hash with middle U+000D (wpt++:)": { "status": "PASS" }, "Setting hash with trailing U+000D (wpt++:)": { "status": "PASS" }, "Setting protocol with leading U+001F (wpt++:)": { "status": "PASS" }, "Setting protocol with U+001F before inserted colon (wpt++:)": { "status": "PASS" }, "Setting username with leading U+001F (wpt++:)": { "status": "PASS" }, "Setting username with middle U+001F (wpt++:)": { "status": "PASS" }, "Setting username with trailing U+001F (wpt++:)": { "status": "PASS" }, "Setting password with leading U+001F (wpt++:)": { "status": "PASS" }, "Setting password with middle U+001F (wpt++:)": { "status": "PASS" }, "Setting password with trailing U+001F (wpt++:)": { "status": "PASS" }, "Setting host with leading U+001F (wpt++:)": { "status": "PASS" }, "Setting hostname with leading U+001F (wpt++:)": { "status": "PASS" }, "Setting host with middle U+001F (wpt++:)": { "status": "PASS" }, "Setting hostname with middle U+001F (wpt++:)": { "status": "PASS" }, "Setting host with trailing U+001F (wpt++:)": { "status": "PASS" }, "Setting hostname with trailing U+001F (wpt++:)": { "status": "PASS" }, "Setting port with leading U+001F (wpt++:)": { "status": "PASS" }, "Setting port with middle U+001F (wpt++:)": { "status": "PASS" }, "Setting port with trailing U+001F (wpt++:)": { "status": "PASS" }, "Setting pathname with leading U+001F (wpt++:)": { "status": "PASS" }, "Setting pathname with middle U+001F (wpt++:)": { "status": "PASS" }, "Setting pathname with trailing U+001F (wpt++:)": { "status": "PASS" }, "Setting search with leading U+001F (wpt++:)": { "status": "PASS" }, "Setting search with middle U+001F (wpt++:)": { "status": "PASS" }, "Setting search with trailing U+001F (wpt++:)": { "status": "PASS" }, "Setting hash with leading U+001F (wpt++:)": { "status": "PASS" }, "Setting hash with middle U+001F (wpt++:)": { "status": "PASS" }, "Setting hash with trailing U+001F (wpt++:)": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/url-setters.any.js.json ================================================ { "Loading data…": { "status": "PASS" }, "URL: Setting .protocol = '' The empty string is not a valid scheme. Setter leaves the URL unchanged.": { "status": "PASS" }, "URL: Setting .protocol = 'b'": { "status": "PASS" }, "URL: Setting .protocol = 'defuse'": { "status": "PASS" }, "URL: Setting .protocol = 'B' Upper-case ASCII is lower-cased": { "status": "PASS" }, "URL: Setting .protocol = 'é' Non-ASCII is rejected": { "status": "PASS" }, "URL: Setting .protocol = '0b' No leading digit": { "status": "PASS" }, "URL: Setting .protocol = '+b' No leading punctuation": { "status": "PASS" }, "URL: Setting .protocol = 'bC0+-.'": { "status": "PASS" }, "URL: Setting .protocol = 'b,c' Only some punctuation is acceptable": { "status": "PASS" }, "URL: Setting .protocol = 'bé' Non-ASCII is rejected": { "status": "PASS" }, "URL: Setting .protocol = 'file' Can’t switch from URL containing username/password/port to file": { "status": "PASS" }, "URL: Setting .protocol = 'file'": { "status": "PASS" }, "URL: Setting .protocol = 'file'": { "status": "PASS" }, "URL: Setting .protocol = 'http' Can’t switch from file URL with no host": { "status": "PASS" }, "URL: Setting .protocol = 'https'": { "status": "PASS" }, "URL: Setting .protocol = 'wss'": { "status": "PASS" }, "URL: Setting .protocol = 'b' Can’t switch from special scheme to non-special": { "status": "PASS" }, "URL: Setting .protocol = 's'": { "status": "PASS" }, "URL: Setting .protocol = 's'": { "status": "PASS" }, "URL: Setting .protocol = 'test'": { "status": "PASS" }, "URL: Setting .protocol = 'http' Cannot-be-a-base URL doesn’t have a host, but URL in a special scheme must.": { "status": "PASS" }, "URL: Setting .protocol = 'http' Can’t switch from non-special scheme to special": { "status": "PASS" }, "URL: Setting .protocol = 'https'": { "status": "PASS" }, "URL: Setting .protocol = 'file'": { "status": "PASS" }, "URL: Setting .protocol = 'file'": { "status": "PASS" }, "URL: Setting .protocol = 'https'": { "status": "PASS" }, "URL: Setting .protocol = 'https:foo : bar' Stuff after the first ':' is ignored": { "status": "PASS" }, "URL: Setting Test>.protocol = 'view-source+data:foo : bar' Stuff after the first ':' is ignored": { "status": "PASS" }, "URL: Setting .protocol = 'https' Port is set to null if it is the default for new scheme.": { "status": "PASS" }, "URL: Setting .protocol = 'h\r\ntt\tps' Tab and newline are stripped": { "status": "PASS" }, "URL: Setting .protocol = 'https\r'": { "status": "PASS" }, "URL: Setting .protocol = 'https\u0000' Non-tab/newline C0 controls result in no-op": { "status": "PASS" }, "URL: Setting .protocol = 'https\f'": { "status": "PASS" }, "URL: Setting .protocol = 'https\u000e'": { "status": "PASS" }, "URL: Setting .protocol = 'https '": { "status": "PASS" }, "URL: Setting .username = 'me' No host means no username": { "status": "PASS" }, "URL: Setting .username = 'me' No host means no username": { "status": "PASS" }, "URL: Setting .username = 'me' Cannot-be-a-base means no username": { "status": "PASS" }, "URL: Setting .username = 'wario'": { "status": "PASS" }, "URL: Setting .username = 'me'": { "status": "PASS" }, "URL: Setting .username = 'me'": { "status": "PASS" }, "URL: Setting .username = ''": { "status": "PASS" }, "URL: Setting .username = ''": { "status": "PASS" }, "URL: Setting .username = '\u0000\u0001\t\n\r\u001f !\"#$%&'()*+,-./09:;<=>?@AZ[\\]^_`az{|}~€Éé' UTF-8 percent encoding with the userinfo encode set.": { "status": "PASS" }, "URL: Setting .username = '%c3%89té' Bytes already percent-encoded are left as-is.": { "status": "PASS" }, "URL: Setting .username = 'x'": { "status": "PASS" }, "URL: Setting .username = 'wario'": { "status": "PASS" }, "URL: Setting .username = 'test'": { "status": "PASS" }, "URL: Setting .password = 'secret' No host means no password": { "status": "PASS" }, "URL: Setting .password = 'secret' No host means no password": { "status": "PASS" }, "URL: Setting .password = 'secret' Cannot-be-a-base means no password": { "status": "PASS" }, "URL: Setting .password = 'secret'": { "status": "PASS" }, "URL: Setting .password = 'secret'": { "status": "PASS" }, "URL: Setting .password = ''": { "status": "PASS" }, "URL: Setting .password = ''": { "status": "PASS" }, "URL: Setting .password = '\u0000\u0001\t\n\r\u001f !\"#$%&'()*+,-./09:;<=>?@AZ[\\]^_`az{|}~€Éé' UTF-8 percent encoding with the userinfo encode set.": { "status": "PASS" }, "URL: Setting .password = '%c3%89té' Bytes already percent-encoded are left as-is.": { "status": "PASS" }, "URL: Setting .password = 'x'": { "status": "PASS" }, "URL: Setting .password = 'bowser'": { "status": "PASS" }, "URL: Setting .password = 'test'": { "status": "PASS" }, "URL: Setting .host = '\u0000' Non-special scheme": { "status": "PASS" }, "URL: Setting .host = '\t'": { "status": "PASS" }, "URL: Setting .host = '\n'": { "status": "PASS" }, "URL: Setting .host = '\r'": { "status": "PASS" }, "URL: Setting .host = ' '": { "status": "PASS" }, "URL: Setting .host = '#'": { "status": "PASS" }, "URL: Setting .host = '/'": { "status": "PASS" }, "URL: Setting .host = '?'": { "status": "PASS" }, "URL: Setting .host = '@'": { "status": "PASS" }, "URL: Setting .host = 'ß'": { "status": "PASS" }, "URL: Setting .host = 'ß' IDNA Nontransitional_Processing": { "status": "PASS" }, "URL: Setting .host = 'example.com' Cannot-be-a-base means no host": { "status": "PASS" }, "URL: Setting .host = 'example.net' Cannot-be-a-base means no host": { "status": "PASS" }, "URL: Setting .host = 'example.com:8080'": { "status": "PASS" }, "URL: Setting .host = 'example.com' Port number is unchanged if not specified in the new value": { "status": "PASS" }, "URL: Setting .host = 'example.com:' Port number is unchanged if not specified": { "status": "PASS" }, "URL: Setting .host = '' The empty host is not valid for special schemes": { "status": "PASS" }, "URL: Setting .host = '' The empty host is OK for non-special schemes": { "status": "PASS" }, "URL: Setting .host = 'example.net' Path-only URLs can gain a host": { "status": "PASS" }, "URL: Setting .host = '0x7F000001:8080' IPv4 address syntax is normalized": { "status": "PASS" }, "URL: Setting .host = '[::0:01]:2' IPv6 address syntax is normalized": { "status": "PASS" }, "URL: Setting .host = '[2001:db8::2]:4002' IPv6 literal address with port, crbug.com/1012416": { "status": "PASS" }, "URL: Setting .host = 'example.com:80' Default port number is removed": { "status": "PASS" }, "URL: Setting .host = 'example.com:443' Default port number is removed": { "status": "PASS" }, "URL: Setting .host = 'example.com:80' Default port number is only removed for the relevant scheme": { "status": "PASS" }, "URL: Setting .host = 'example.com:80' Port number is removed if new port is scheme default and existing URL has a non-default port": { "status": "PASS" }, "URL: Setting .host = 'example.com/stuff' Stuff after a / delimiter is ignored": { "status": "PASS" }, "URL: Setting .host = 'example.com:8080/stuff' Stuff after a / delimiter is ignored": { "status": "PASS" }, "URL: Setting .host = 'example.com?stuff' Stuff after a ? delimiter is ignored": { "status": "PASS" }, "URL: Setting .host = 'example.com?stuff:8080' Stuff after a ? delimiter is ignored, trailing 'port'": { "status": "PASS" }, "URL: Setting .host = 'example.com:8080?stuff' Stuff after a ? delimiter is ignored": { "status": "PASS" }, "URL: Setting .host = 'example.com#stuff' Stuff after a # delimiter is ignored": { "status": "PASS" }, "URL: Setting .host = 'example.com:8080#stuff' Stuff after a # delimiter is ignored": { "status": "PASS" }, "URL: Setting .host = 'example.com\\stuff' Stuff after a \\ delimiter is ignored for special schemes": { "status": "PASS" }, "URL: Setting .host = 'example.com:8080\\stuff' Stuff after a \\ delimiter is ignored for special schemes": { "status": "PASS" }, "URL: Setting .host = 'example.com\\stuff' \\ is not a delimiter for non-special schemes, but still forbidden in hosts": { "status": "PASS" }, "URL: Setting .host = 'example.com:8080stuff2' Anything other than ASCII digit stops the port parser in a setter but is not an error": { "status": "PASS" }, "URL: Setting .host = 'example.com:8080stuff2' Anything other than ASCII digit stops the port parser in a setter but is not an error": { "status": "PASS" }, "URL: Setting .host = 'example.com:8080+2' Anything other than ASCII digit stops the port parser in a setter but is not an error": { "status": "PASS" }, "URL: Setting .host = 'example.com:invalid' Anything other than ASCII digit stops the port parser in a setter but is not an error": { "status": "PASS" }, "URL: Setting .host = '[::1]:invalid' Anything other than ASCII digit stops the port parser in a setter but is not an error": { "status": "PASS" }, "URL: Setting .host = '[::1]' IPv6 without port": { "status": "PASS" }, "URL: Setting .host = 'example.com:65535' Port numbers are 16 bit integers": { "status": "PASS" }, "URL: Setting .host = 'example.com:65536' Port numbers are 16 bit integers, overflowing is an error. Hostname is still set, though.": { "status": "PASS" }, "URL: Setting .host = '[google.com]' Broken IPv6": { "status": "PASS" }, "URL: Setting .host = '[::1.2.3.4x]'": { "status": "PASS" }, "URL: Setting .host = '[::1.2.3.]'": { "status": "PASS" }, "URL: Setting .host = '[::1.2.]'": { "status": "PASS" }, "URL: Setting .host = '[::1.]'": { "status": "PASS" }, "URL: Setting .host = 'x:123'": { "status": "PASS" }, "URL: Setting .host = 'loc%41lhost'": { "status": "PASS" }, "URL: Setting .host = ''": { "status": "PASS" }, "URL: Setting .host = ''": { "status": "PASS" }, "URL: Setting .host = ''": { "status": "PASS" }, "URL: Setting .host = '///bad.com' Leading / is not stripped": { "status": "PASS" }, "URL: Setting .host = '///bad.com' Leading / is not stripped": { "status": "PASS" }, "URL: Setting .host = 'a%C2%ADb'": { "status": "PASS" }, "URL: Setting .host = '­'": { "status": "PASS" }, "URL: Setting .host = '%C2%AD'": { "status": "PASS" }, "URL: Setting .host = 'xn--'": { "status": "PASS" }, "URL: Setting .hostname = '\u0000' Non-special scheme": { "status": "PASS" }, "URL: Setting .hostname = '\t'": { "status": "PASS" }, "URL: Setting .hostname = '\n'": { "status": "PASS" }, "URL: Setting .hostname = '\r'": { "status": "PASS" }, "URL: Setting .hostname = ' '": { "status": "PASS" }, "URL: Setting .hostname = '#'": { "status": "PASS" }, "URL: Setting .hostname = '/'": { "status": "PASS" }, "URL: Setting .hostname = '?'": { "status": "PASS" }, "URL: Setting .hostname = '@'": { "status": "PASS" }, "URL: Setting .hostname = 'example.com' Cannot-be-a-base means no host": { "status": "PASS" }, "URL: Setting .hostname = 'example.net' Cannot-be-a-base means no host": { "status": "PASS" }, "URL: Setting .hostname = 'example.com'": { "status": "PASS" }, "URL: Setting .hostname = '' The empty host is not valid for special schemes": { "status": "PASS" }, "URL: Setting .hostname = '' The empty host is OK for non-special schemes": { "status": "PASS" }, "URL: Setting .hostname = 'example.net' Path-only URLs can gain a host": { "status": "PASS" }, "URL: Setting .hostname = '0x7F000001' IPv4 address syntax is normalized": { "status": "PASS" }, "URL: Setting .hostname = '[::0:01]' IPv6 address syntax is normalized": { "status": "PASS" }, "URL: Setting .hostname = 'example.com:8080' : delimiter invalidates entire value": { "status": "FAIL" }, "URL: Setting .hostname = 'example.com:' : delimiter invalidates entire value": { "status": "FAIL" }, "URL: Setting .hostname = 'example.com/stuff' Stuff after a / delimiter is ignored": { "status": "PASS" }, "URL: Setting .hostname = 'example.com?stuff' Stuff after a ? delimiter is ignored": { "status": "PASS" }, "URL: Setting .hostname = 'example.com#stuff' Stuff after a # delimiter is ignored": { "status": "PASS" }, "URL: Setting .hostname = 'example.com\\stuff' Stuff after a \\ delimiter is ignored for special schemes": { "status": "PASS" }, "URL: Setting .hostname = 'example.com\\stuff' \\ is not a delimiter for non-special schemes, but still forbidden in hosts": { "status": "PASS" }, "URL: Setting .hostname = '[google.com]' Broken IPv6": { "status": "PASS" }, "URL: Setting .hostname = '[::1.2.3.4x]'": { "status": "PASS" }, "URL: Setting .hostname = '[::1.2.3.]'": { "status": "PASS" }, "URL: Setting .hostname = '[::1.2.]'": { "status": "PASS" }, "URL: Setting .hostname = '[::1.]'": { "status": "PASS" }, "URL: Setting .hostname = 'x:123'": { "status": "PASS" }, "URL: Setting .hostname = 'loc%41lhost'": { "status": "PASS" }, "URL: Setting .hostname = ''": { "status": "PASS" }, "URL: Setting .hostname = ''": { "status": "PASS" }, "URL: Setting .hostname = ''": { "status": "PASS" }, "URL: Setting .hostname = 'h' Drop /. from path": { "status": "FAIL" }, "URL: Setting .hostname = ''": { "status": "FAIL" }, "URL: Setting .hostname = '///bad.com' Leading / is not stripped": { "status": "PASS" }, "URL: Setting .hostname = '///bad.com' Leading / is not stripped": { "status": "PASS" }, "URL: Setting .hostname = 'a%C2%ADb'": { "status": "PASS" }, "URL: Setting .hostname = '­'": { "status": "PASS" }, "URL: Setting .hostname = '%C2%AD'": { "status": "PASS" }, "URL: Setting .hostname = 'xn--'": { "status": "PASS" }, "URL: Setting .port = '8080'": { "status": "PASS" }, "URL: Setting .port = '' Port number is removed if empty is the new value": { "status": "PASS" }, "URL: Setting .port = '80' Default port number is removed": { "status": "PASS" }, "URL: Setting .port = '443' Default port number is removed": { "status": "PASS" }, "URL: Setting .port = '80' Default port number is only removed for the relevant scheme": { "status": "PASS" }, "URL: Setting .port = '8080/stuff' Stuff after a / delimiter is ignored": { "status": "PASS" }, "URL: Setting .port = '8080?stuff' Stuff after a ? delimiter is ignored": { "status": "PASS" }, "URL: Setting .port = '8080#stuff' Stuff after a # delimiter is ignored": { "status": "PASS" }, "URL: Setting .port = '8080\\stuff' Stuff after a \\ delimiter is ignored for special schemes": { "status": "PASS" }, "URL: Setting .port = '8080stuff2' Anything other than ASCII digit stops the port parser in a setter but is not an error": { "status": "PASS" }, "URL: Setting .port = '8080stuff2' Anything other than ASCII digit stops the port parser in a setter but is not an error": { "status": "PASS" }, "URL: Setting .port = '8080+2' Anything other than ASCII digit stops the port parser in a setter but is not an error": { "status": "PASS" }, "URL: Setting .port = '65535' Port numbers are 16 bit integers": { "status": "PASS" }, "URL: Setting .port = '65536' Port numbers are 16 bit integers, overflowing is an error": { "status": "PASS" }, "URL: Setting .port = 'randomstring' Setting port to a string that doesn't parse as a number": { "status": "PASS" }, "URL: Setting .port = '65536' Port numbers are 16 bit integers, overflowing is an error": { "status": "PASS" }, "URL: Setting .port = '12'": { "status": "PASS" }, "URL: Setting .port = '12'": { "status": "PASS" }, "URL: Setting .port = '12'": { "status": "PASS" }, "URL: Setting .port = '12'": { "status": "PASS" }, "URL: Setting .port = '12'": { "status": "PASS" }, "URL: Setting .port = '12'": { "status": "PASS" }, "URL: Setting .port = '\t8080' Leading u0009 on special scheme": { "status": "PASS" }, "URL: Setting .port = '\t8080' Leading u0009 on non-special scheme": { "status": "PASS" }, "URL: Setting .port = '4wpt' Should use all ascii prefixed characters as port": { "status": "PASS" }, "URL: Setting .pathname = '/foo' Opaque paths cannot be set": { "status": "PASS" }, "URL: Setting .pathname = 'new value'": { "status": "PASS" }, "URL: Setting .pathname = 'new value'": { "status": "PASS" }, "URL: Setting .pathname = '' Special URLs cannot have their paths erased": { "status": "PASS" }, "URL: Setting .pathname = '' Non-special URLs can have their paths erased": { "status": "PASS" }, "URL: Setting .pathname = '' Non-special URLs with an empty host can have their paths erased": { "status": "FAIL" }, "URL: Setting .pathname = '' Path-only URLs cannot have their paths erased": { "status": "PASS" }, "URL: Setting .pathname = 'test' Path-only URLs always have an initial slash": { "status": "PASS" }, "URL: Setting .pathname = '/var/log/../run/bar.socket'": { "status": "PASS" }, "URL: Setting .pathname = 'home'": { "status": "PASS" }, "URL: Setting .pathname = '../home'": { "status": "PASS" }, "URL: Setting .pathname = '\\a\\%2E\\b\\%2e.\\c' \\ is a segment delimiter for 'special' URLs": { "status": "PASS" }, "URL: Setting .pathname = '\\a\\%2E\\b\\%2e.\\c' \\ is *not* a segment delimiter for non-'special' URLs": { "status": "PASS" }, "URL: Setting .pathname = '\u0000\u0001\t\n\r\u001f !\"#$%&'()*+,-./09:;<=>?@AZ[\\]^_`az{|}~€Éé' UTF-8 percent encoding with the default encode set. Tabs and newlines are removed.": { "status": "PASS" }, "URL: Setting .pathname = '%2e%2E%c3%89té' Bytes already percent-encoded are left as-is, including %2E outside dotted segments.": { "status": "PASS" }, "URL: Setting .pathname = '?' ? needs to be encoded": { "status": "PASS" }, "URL: Setting .pathname = '#' # needs to be encoded": { "status": "PASS" }, "URL: Setting .pathname = '?' ? needs to be encoded, non-special scheme": { "status": "PASS" }, "URL: Setting .pathname = '#' # needs to be encoded, non-special scheme": { "status": "PASS" }, "URL: Setting .pathname = '/?é' ? doesn't mess up encoding": { "status": "PASS" }, "URL: Setting .pathname = '/#é' # doesn't mess up encoding": { "status": "PASS" }, "URL: Setting .pathname = '\\\\' File URLs and (back)slashes": { "status": "FAIL" }, "URL: Setting .pathname = '//\\/' File URLs and (back)slashes": { "status": "FAIL" }, "URL: Setting .pathname = '//monkey/..//' File URLs and (back)slashes": { "status": "FAIL" }, "URL: Setting .pathname = '/.//p' Serialize /. in path": { "status": "FAIL" }, "URL: Setting .pathname = '/..//p'": { "status": "FAIL" }, "URL: Setting .pathname = '//p'": { "status": "FAIL" }, "URL: Setting .pathname = 'p' Drop /. from path": { "status": "FAIL" }, "URL: Setting .pathname = 'space ' Non-special URLs with non-opaque paths percent-encode U+0020": { "status": "PASS" }, "URL: Setting .pathname = 'space '": { "status": "PASS" }, "URL: Setting .pathname = ' ' Trailing space should be encoded": { "status": "PASS" }, "URL: Setting .pathname = '\u0000' Trailing C0 control should be encoded": { "status": "PASS" }, "URL: Setting .search = 'lang=fr'": { "status": "PASS" }, "URL: Setting .search = 'lang=fr'": { "status": "PASS" }, "URL: Setting .search = '?lang=fr'": { "status": "PASS" }, "URL: Setting .search = '??lang=fr'": { "status": "PASS" }, "URL: Setting .search = '?'": { "status": "PASS" }, "URL: Setting .search = ''": { "status": "PASS" }, "URL: Setting .search = ''": { "status": "PASS" }, "URL: Setting .search = ''": { "status": "PASS" }, "URL: Setting .search = '\u0000\u0001\t\n\r\u001f !\"#$%&'()*+,-./09:;<=>?@AZ[\\]^_`az{|}~€Éé' UTF-8 percent encoding with the query encode set. Tabs and newlines are removed.": { "status": "PASS" }, "URL: Setting .search = '%c3%89té' Bytes already percent-encoded are left as-is": { "status": "PASS" }, "URL: Setting .search = '' Drop trailing spaces from trailing opaque paths": { "status": "PASS" }, "URL: Setting .search = ''": { "status": "PASS" }, "URL: Setting .search = '' Do not drop trailing spaces from non-trailing opaque paths": { "status": "PASS" }, "URL: Setting .search = ''": { "status": "PASS" }, "URL: Setting .search = ' ' Trailing space should be encoded": { "status": "PASS" }, "URL: Setting .search = '\u0000' Trailing C0 control should be encoded": { "status": "PASS" }, "URL: Setting .hash = 'main'": { "status": "PASS" }, "URL: Setting .hash = 'main'": { "status": "PASS" }, "URL: Setting .hash = '##nav'": { "status": "PASS" }, "URL: Setting .hash = '#main'": { "status": "PASS" }, "URL: Setting .hash = '#'": { "status": "PASS" }, "URL: Setting .hash = ''": { "status": "PASS" }, "URL: Setting .hash = '#foo bar'": { "status": "PASS" }, "URL: Setting .hash = '#foo\"bar'": { "status": "PASS" }, "URL: Setting .hash = '#foo.hash = '#foo>bar'": { "status": "PASS" }, "URL: Setting .hash = '#foo`bar'": { "status": "PASS" }, "URL: Setting .hash = '\u0000\u0001\t\n\r\u001f !\"#$%&'()*+,-./09:;<=>?@AZ[\\]^_`az{|}~€Éé' Simple percent-encoding; tabs and newlines are removed": { "status": "PASS" }, "URL: Setting .hash = 'a\u0000b' Percent-encode NULLs in fragment": { "status": "PASS" }, "URL: Setting .hash = 'a\u0000b' Percent-encode NULLs in fragment": { "status": "PASS" }, "URL: Setting .hash = '%c3%89té' Bytes already percent-encoded are left as-is": { "status": "PASS" }, "URL: Setting .hash = 'castle'": { "status": "PASS" }, "URL: Setting .hash = '' Drop trailing spaces from trailing opaque paths": { "status": "PASS" }, "URL: Setting .hash = ''": { "status": "PASS" }, "URL: Setting .hash = '' Do not drop trailing spaces from non-trailing opaque paths": { "status": "PASS" }, "URL: Setting .hash = ''": { "status": "PASS" }, "URL: Setting .hash = ' ' Trailing space should be encoded": { "status": "PASS" }, "URL: Setting .hash = '\u0000' Trailing C0 control should be encoded": { "status": "PASS" }, "URL: Setting .href = 'http://0300.168.0xF0'": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/url-statics-canparse.any.js.json ================================================ { "URL.canParse(undefined, undefined)": { "status": "FAIL" }, "URL.canParse(aaa:b, undefined)": { "status": "FAIL" }, "URL.canParse(undefined, aaa:b)": { "status": "FAIL" }, "URL.canParse(aaa:/b, undefined)": { "status": "FAIL" }, "URL.canParse(undefined, aaa:/b)": { "status": "FAIL" }, "URL.canParse(https://test:test, undefined)": { "status": "FAIL" }, "URL.canParse(a, https://b/)": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/url/url-statics-parse.any.js.json ================================================ { "URL.parse(undefined, undefined)": { "status": "FAIL" }, "URL.parse(aaa:b, undefined)": { "status": "FAIL" }, "URL.parse(undefined, aaa:b)": { "status": "FAIL" }, "URL.parse(aaa:/b, undefined)": { "status": "FAIL" }, "URL.parse(undefined, aaa:/b)": { "status": "FAIL" }, "URL.parse(https://test:test, undefined)": { "status": "FAIL" }, "URL.parse(a, https://b/)": { "status": "FAIL" }, "URL.parse() should return a unique object": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/url/url-tojson.any.js.json ================================================ { "url-tojson": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlencoded-parser.any.js.json ================================================ { "URLSearchParams constructed with: test": { "status": "PASS" }, "request.formData() with input: test": { "status": "PASS" }, "response.formData() with input: test": { "status": "PASS" }, "URLSearchParams constructed with: test=": { "status": "PASS" }, "request.formData() with input: test=": { "status": "FAIL" }, "response.formData() with input: test=": { "status": "FAIL" }, "URLSearchParams constructed with: %EF%BB%BFtest=%EF%BB%BF": { "status": "PASS" }, "request.formData() with input: %EF%BB%BFtest=%EF%BB%BF": { "status": "FAIL" }, "response.formData() with input: %EF%BB%BFtest=%EF%BB%BF": { "status": "FAIL" }, "URLSearchParams constructed with: %EF%BF%BF=%EF%BF%BF": { "status": "PASS" }, "request.formData() with input: %EF%BF%BF=%EF%BF%BF": { "status": "FAIL" }, "response.formData() with input: %EF%BF%BF=%EF%BF%BF": { "status": "FAIL" }, "URLSearchParams constructed with: %FE%FF": { "status": "PASS" }, "request.formData() with input: %FE%FF": { "status": "PASS" }, "response.formData() with input: %FE%FF": { "status": "PASS" }, "URLSearchParams constructed with: %FF%FE": { "status": "PASS" }, "request.formData() with input: %FF%FE": { "status": "PASS" }, "response.formData() with input: %FF%FE": { "status": "PASS" }, "URLSearchParams constructed with: †&†=x": { "status": "PASS" }, "request.formData() with input: †&†=x": { "status": "PASS" }, "response.formData() with input: †&†=x": { "status": "PASS" }, "URLSearchParams constructed with: %C2": { "status": "PASS" }, "request.formData() with input: %C2": { "status": "PASS" }, "response.formData() with input: %C2": { "status": "PASS" }, "URLSearchParams constructed with: %C2x": { "status": "PASS" }, "request.formData() with input: %C2x": { "status": "PASS" }, "response.formData() with input: %C2x": { "status": "PASS" }, "URLSearchParams constructed with: _charset_=windows-1252&test=%C2x": { "status": "PASS" }, "request.formData() with input: _charset_=windows-1252&test=%C2x": { "status": "PASS" }, "response.formData() with input: _charset_=windows-1252&test=%C2x": { "status": "PASS" }, "URLSearchParams constructed with: ": { "status": "PASS" }, "request.formData() with input: ": { "status": "PASS" }, "response.formData() with input: ": { "status": "PASS" }, "URLSearchParams constructed with: a": { "status": "PASS" }, "request.formData() with input: a": { "status": "PASS" }, "response.formData() with input: a": { "status": "PASS" }, "URLSearchParams constructed with: a=b": { "status": "PASS" }, "request.formData() with input: a=b": { "status": "PASS" }, "response.formData() with input: a=b": { "status": "PASS" }, "URLSearchParams constructed with: a=": { "status": "PASS" }, "request.formData() with input: a=": { "status": "PASS" }, "response.formData() with input: a=": { "status": "PASS" }, "URLSearchParams constructed with: =b": { "status": "PASS" }, "request.formData() with input: =b": { "status": "PASS" }, "response.formData() with input: =b": { "status": "PASS" }, "URLSearchParams constructed with: &": { "status": "PASS" }, "request.formData() with input: &": { "status": "PASS" }, "response.formData() with input: &": { "status": "PASS" }, "URLSearchParams constructed with: &a": { "status": "PASS" }, "request.formData() with input: &a": { "status": "PASS" }, "response.formData() with input: &a": { "status": "PASS" }, "URLSearchParams constructed with: a&": { "status": "PASS" }, "request.formData() with input: a&": { "status": "PASS" }, "response.formData() with input: a&": { "status": "PASS" }, "URLSearchParams constructed with: a&a": { "status": "PASS" }, "request.formData() with input: a&a": { "status": "PASS" }, "response.formData() with input: a&a": { "status": "PASS" }, "URLSearchParams constructed with: a&b&c": { "status": "PASS" }, "request.formData() with input: a&b&c": { "status": "PASS" }, "response.formData() with input: a&b&c": { "status": "PASS" }, "URLSearchParams constructed with: a=b&c=d": { "status": "PASS" }, "request.formData() with input: a=b&c=d": { "status": "PASS" }, "response.formData() with input: a=b&c=d": { "status": "PASS" }, "URLSearchParams constructed with: a=b&c=d&": { "status": "PASS" }, "request.formData() with input: a=b&c=d&": { "status": "PASS" }, "response.formData() with input: a=b&c=d&": { "status": "PASS" }, "URLSearchParams constructed with: &&&a=b&&&&c=d&": { "status": "PASS" }, "request.formData() with input: &&&a=b&&&&c=d&": { "status": "PASS" }, "response.formData() with input: &&&a=b&&&&c=d&": { "status": "PASS" }, "URLSearchParams constructed with: a=a&a=b&a=c": { "status": "PASS" }, "request.formData() with input: a=a&a=b&a=c": { "status": "PASS" }, "response.formData() with input: a=a&a=b&a=c": { "status": "PASS" }, "URLSearchParams constructed with: a==a": { "status": "PASS" }, "request.formData() with input: a==a": { "status": "PASS" }, "response.formData() with input: a==a": { "status": "PASS" }, "URLSearchParams constructed with: a=a+b+c+d": { "status": "PASS" }, "request.formData() with input: a=a+b+c+d": { "status": "PASS" }, "response.formData() with input: a=a+b+c+d": { "status": "PASS" }, "URLSearchParams constructed with: %=a": { "status": "PASS" }, "request.formData() with input: %=a": { "status": "PASS" }, "response.formData() with input: %=a": { "status": "PASS" }, "URLSearchParams constructed with: %a=a": { "status": "PASS" }, "request.formData() with input: %a=a": { "status": "PASS" }, "response.formData() with input: %a=a": { "status": "PASS" }, "URLSearchParams constructed with: %a_=a": { "status": "PASS" }, "request.formData() with input: %a_=a": { "status": "PASS" }, "response.formData() with input: %a_=a": { "status": "PASS" }, "URLSearchParams constructed with: %61=a": { "status": "PASS" }, "request.formData() with input: %61=a": { "status": "PASS" }, "response.formData() with input: %61=a": { "status": "PASS" }, "URLSearchParams constructed with: %61+%4d%4D=": { "status": "PASS" }, "request.formData() with input: %61+%4d%4D=": { "status": "PASS" }, "response.formData() with input: %61+%4d%4D=": { "status": "PASS" }, "URLSearchParams constructed with: id=0&value=%": { "status": "PASS" }, "request.formData() with input: id=0&value=%": { "status": "PASS" }, "response.formData() with input: id=0&value=%": { "status": "PASS" }, "URLSearchParams constructed with: b=%2sf%2a": { "status": "PASS" }, "request.formData() with input: b=%2sf%2a": { "status": "PASS" }, "response.formData() with input: b=%2sf%2a": { "status": "PASS" }, "URLSearchParams constructed with: b=%2%2af%2a": { "status": "PASS" }, "request.formData() with input: b=%2%2af%2a": { "status": "PASS" }, "response.formData() with input: b=%2%2af%2a": { "status": "PASS" }, "URLSearchParams constructed with: b=%%2a": { "status": "PASS" }, "request.formData() with input: b=%%2a": { "status": "PASS" }, "response.formData() with input: b=%%2a": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-append.any.js.json ================================================ { "Append same name": { "status": "PASS" }, "Append empty strings": { "status": "PASS" }, "Append null": { "status": "PASS" }, "Append multiple": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-constructor.any.js.json ================================================ { "Basic URLSearchParams construction": { "status": "PASS" }, "URLSearchParams constructor, no arguments": { "status": "PASS" }, "URLSearchParams constructor, remove leading \"?\"": { "status": "PASS" }, "URLSearchParams constructor, DOMException as argument": { "status": "PASS" }, "URLSearchParams constructor, empty string as argument": { "status": "PASS" }, "URLSearchParams constructor, {} as argument": { "status": "PASS" }, "URLSearchParams constructor, string.": { "status": "PASS" }, "URLSearchParams constructor, object.": { "status": "PASS" }, "URLSearchParams constructor, FormData.": { "status": "PASS" }, "Parse +": { "status": "PASS" }, "Parse encoded +": { "status": "PASS" }, "Parse space": { "status": "PASS" }, "Parse %20": { "status": "PASS" }, "Parse \\0": { "status": "PASS" }, "Parse %00": { "status": "PASS" }, "Parse ⎄": { "status": "PASS" }, "Parse %e2%8e%84": { "status": "PASS" }, "Parse 💩": { "status": "PASS" }, "Parse %f0%9f%92%a9": { "status": "PASS" }, "Constructor with sequence of sequences of strings": { "status": "PASS" }, "Construct with object with +": { "status": "PASS" }, "Construct with object with two keys": { "status": "PASS" }, "Construct with array with two keys": { "status": "PASS" }, "Construct with 2 unpaired surrogates (no trailing)": { "status": "FAIL" }, "Construct with 3 unpaired surrogates (no leading)": { "status": "FAIL" }, "Construct with object with NULL, non-ASCII, and surrogate keys": { "status": "PASS" }, "Custom [Symbol.iterator]": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-delete.any.js.json ================================================ { "Delete basics": { "status": "PASS" }, "Deleting appended multiple": { "status": "PASS" }, "Deleting all params removes ? from URL": { "status": "PASS" }, "Removing non-existent param removes ? from URL": { "status": "PASS" }, "Changing the query of a URL with an opaque path can impact the path": { "status": "PASS" }, "Changing the query of a URL with an opaque path can impact the path if the URL has no fragment": { "status": "PASS" }, "Two-argument delete()": { "status": "FAIL" }, "Two-argument delete() respects undefined as second arg": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-foreach.any.js.json ================================================ { "ForEach Check": { "status": "PASS" }, "For-of Check": { "status": "PASS" }, "empty": { "status": "PASS" }, "delete next param during iteration": { "status": "PASS" }, "delete current param during iteration": { "status": "PASS" }, "delete every param seen during iteration": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-get.any.js.json ================================================ { "Get basics": { "status": "FAIL" }, "More get() basics": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-getall.any.js.json ================================================ { "getAll() basics": { "status": "PASS" }, "getAll() multiples": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-has.any.js.json ================================================ { "Has basics": { "status": "PASS" }, "has() following delete()": { "status": "PASS" }, "Two-argument has()": { "status": "FAIL" }, "Two-argument has() respects undefined as second arg": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-set.any.js.json ================================================ { "Set basics": { "status": "PASS" }, "URLSearchParams.set": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-size.any.js.json ================================================ { "URLSearchParams's size and deletion": { "status": "FAIL" }, "URLSearchParams's size and addition": { "status": "FAIL" }, "URLSearchParams's size when obtained from a URL": { "status": "FAIL" }, "URLSearchParams's size when obtained from a URL and using .search": { "status": "FAIL" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-sort.any.js.json ================================================ { "Parse and sort: z=b&a=b&z=a&a=a": { "status": "PASS" }, "URL parse and sort: z=b&a=b&z=a&a=a": { "status": "PASS" }, "Parse and sort: �=x&&�=a": { "status": "PASS" }, "URL parse and sort: �=x&&�=a": { "status": "PASS" }, "Parse and sort: ffi&🌈": { "status": "PASS" }, "URL parse and sort: ffi&🌈": { "status": "PASS" }, "Parse and sort: é&e�&é": { "status": "PASS" }, "URL parse and sort: é&e�&é": { "status": "PASS" }, "Parse and sort: z=z&a=a&z=y&a=b&z=x&a=c&z=w&a=d&z=v&a=e&z=u&a=f&z=t&a=g": { "status": "PASS" }, "URL parse and sort: z=z&a=a&z=y&a=b&z=x&a=c&z=w&a=d&z=v&a=e&z=u&a=f&z=t&a=g": { "status": "PASS" }, "Parse and sort: bbb&bb&aaa&aa=x&aa=y": { "status": "PASS" }, "URL parse and sort: bbb&bb&aaa&aa=x&aa=y": { "status": "PASS" }, "Parse and sort: z=z&=f&=t&=x": { "status": "PASS" }, "URL parse and sort: z=z&=f&=t&=x": { "status": "PASS" }, "Parse and sort: a🌈&a💩": { "status": "PASS" }, "URL parse and sort: a🌈&a💩": { "status": "PASS" }, "Sorting non-existent params removes ? from URL": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/url/urlsearchparams-stringifier.any.js.json ================================================ { "Serialize space": { "status": "PASS" }, "Serialize empty value": { "status": "PASS" }, "Serialize empty name": { "status": "PASS" }, "Serialize empty name and value": { "status": "PASS" }, "Serialize +": { "status": "PASS" }, "Serialize =": { "status": "PASS" }, "Serialize &": { "status": "PASS" }, "Serialize *-._": { "status": "PASS" }, "Serialize %": { "status": "PASS" }, "Serialize \\0": { "status": "PASS" }, "Serialize 💩": { "status": "PASS" }, "URLSearchParams.toString": { "status": "PASS" }, "URLSearchParams connected to URL": { "status": "FAIL" }, "URLSearchParams must not do newline normalization": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/webidl/ecmascript-binding/es-exceptions/DOMException-constants.any.js.json ================================================ { "DOMException-constants": { "status": "PASS" }, "Constant INDEX_SIZE_ERR on DOMException constructor object": { "status": "PASS" }, "Constant INDEX_SIZE_ERR on DOMException prototype object": { "status": "PASS" }, "Constant DOMSTRING_SIZE_ERR on DOMException constructor object": { "status": "PASS" }, "Constant DOMSTRING_SIZE_ERR on DOMException prototype object": { "status": "PASS" }, "Constant HIERARCHY_REQUEST_ERR on DOMException constructor object": { "status": "PASS" }, "Constant HIERARCHY_REQUEST_ERR on DOMException prototype object": { "status": "PASS" }, "Constant WRONG_DOCUMENT_ERR on DOMException constructor object": { "status": "PASS" }, "Constant WRONG_DOCUMENT_ERR on DOMException prototype object": { "status": "PASS" }, "Constant INVALID_CHARACTER_ERR on DOMException constructor object": { "status": "PASS" }, "Constant INVALID_CHARACTER_ERR on DOMException prototype object": { "status": "PASS" }, "Constant NO_DATA_ALLOWED_ERR on DOMException constructor object": { "status": "PASS" }, "Constant NO_DATA_ALLOWED_ERR on DOMException prototype object": { "status": "PASS" }, "Constant NO_MODIFICATION_ALLOWED_ERR on DOMException constructor object": { "status": "PASS" }, "Constant NO_MODIFICATION_ALLOWED_ERR on DOMException prototype object": { "status": "PASS" }, "Constant NOT_FOUND_ERR on DOMException constructor object": { "status": "PASS" }, "Constant NOT_FOUND_ERR on DOMException prototype object": { "status": "PASS" }, "Constant NOT_SUPPORTED_ERR on DOMException constructor object": { "status": "PASS" }, "Constant NOT_SUPPORTED_ERR on DOMException prototype object": { "status": "PASS" }, "Constant INUSE_ATTRIBUTE_ERR on DOMException constructor object": { "status": "PASS" }, "Constant INUSE_ATTRIBUTE_ERR on DOMException prototype object": { "status": "PASS" }, "Constant INVALID_STATE_ERR on DOMException constructor object": { "status": "PASS" }, "Constant INVALID_STATE_ERR on DOMException prototype object": { "status": "PASS" }, "Constant SYNTAX_ERR on DOMException constructor object": { "status": "PASS" }, "Constant SYNTAX_ERR on DOMException prototype object": { "status": "PASS" }, "Constant INVALID_MODIFICATION_ERR on DOMException constructor object": { "status": "PASS" }, "Constant INVALID_MODIFICATION_ERR on DOMException prototype object": { "status": "PASS" }, "Constant NAMESPACE_ERR on DOMException constructor object": { "status": "PASS" }, "Constant NAMESPACE_ERR on DOMException prototype object": { "status": "PASS" }, "Constant INVALID_ACCESS_ERR on DOMException constructor object": { "status": "PASS" }, "Constant INVALID_ACCESS_ERR on DOMException prototype object": { "status": "PASS" }, "Constant VALIDATION_ERR on DOMException constructor object": { "status": "PASS" }, "Constant VALIDATION_ERR on DOMException prototype object": { "status": "PASS" }, "Constant TYPE_MISMATCH_ERR on DOMException constructor object": { "status": "PASS" }, "Constant TYPE_MISMATCH_ERR on DOMException prototype object": { "status": "PASS" }, "Constant SECURITY_ERR on DOMException constructor object": { "status": "PASS" }, "Constant SECURITY_ERR on DOMException prototype object": { "status": "PASS" }, "Constant NETWORK_ERR on DOMException constructor object": { "status": "PASS" }, "Constant NETWORK_ERR on DOMException prototype object": { "status": "PASS" }, "Constant ABORT_ERR on DOMException constructor object": { "status": "PASS" }, "Constant ABORT_ERR on DOMException prototype object": { "status": "PASS" }, "Constant URL_MISMATCH_ERR on DOMException constructor object": { "status": "PASS" }, "Constant URL_MISMATCH_ERR on DOMException prototype object": { "status": "PASS" }, "Constant QUOTA_EXCEEDED_ERR on DOMException constructor object": { "status": "PASS" }, "Constant QUOTA_EXCEEDED_ERR on DOMException prototype object": { "status": "PASS" }, "Constant TIMEOUT_ERR on DOMException constructor object": { "status": "PASS" }, "Constant TIMEOUT_ERR on DOMException prototype object": { "status": "PASS" }, "Constant INVALID_NODE_TYPE_ERR on DOMException constructor object": { "status": "PASS" }, "Constant INVALID_NODE_TYPE_ERR on DOMException prototype object": { "status": "PASS" }, "Constant DATA_CLONE_ERR on DOMException constructor object": { "status": "PASS" }, "Constant DATA_CLONE_ERR on DOMException prototype object": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/webidl/ecmascript-binding/es-exceptions/DOMException-constructor-and-prototype.any.js.json ================================================ { "existence and property descriptor of DOMException": { "status": "PASS" }, "existence and property descriptor of DOMException.prototype": { "status": "PASS" }, "existence and property descriptor of DOMException.prototype.constructor": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/webidl/ecmascript-binding/es-exceptions/DOMException-constructor-behavior.any.js.json ================================================ { "new DOMException()": { "status": "PASS" }, "new DOMException(): inherited-ness": { "status": "PASS" }, "new DOMException(null)": { "status": "PASS" }, "new DOMException(undefined)": { "status": "PASS" }, "new DOMException(undefined): inherited-ness": { "status": "PASS" }, "new DOMException(\"foo\")": { "status": "PASS" }, "new DOMException(\"foo\"): inherited-ness": { "status": "PASS" }, "new DOMException(\"bar\", undefined)": { "status": "PASS" }, "new DOMException(\"bar\", \"NotSupportedError\")": { "status": "PASS" }, "new DOMException(\"bar\", \"NotSupportedError\"): inherited-ness": { "status": "PASS" }, "new DOMException(\"bar\", \"foo\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"IndexSizeError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"HierarchyRequestError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"WrongDocumentError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"InvalidCharacterError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"NoModificationAllowedError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"NotFoundError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"NotSupportedError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"InUseAttributeError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"InvalidStateError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"SyntaxError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"InvalidModificationError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"NamespaceError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"InvalidAccessError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"TypeMismatchError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"SecurityError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"NetworkError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"AbortError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"URLMismatchError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"QuotaExceededError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"TimeoutError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"InvalidNodeTypeError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"DataCloneError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"DOMStringSizeError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"NoDataAllowedError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"ValidationError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"EncodingError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"NotReadableError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"UnknownError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"ConstraintError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"DataError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"TransactionInactiveError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"ReadOnlyError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"VersionError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"OperationError\")": { "status": "PASS" }, "new DOMexception(\"msg\", \"NotAllowedError\")": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/webidl/ecmascript-binding/es-exceptions/DOMException-custom-bindings.any.js.json ================================================ { "Cannot construct without new": { "status": "PASS" }, "inherits from Error: prototype-side": { "status": "PASS" }, "does not inherit from Error: class-side": { "status": "PASS" }, "message property descriptor": { "status": "PASS" }, "message getter performs brand checks (i.e. is not [LegacyLenientThis])": { "status": "PASS" }, "name property descriptor": { "status": "PASS" }, "name getter performs brand checks (i.e. is not [LegacyLenientThis])": { "status": "PASS" }, "code property descriptor": { "status": "PASS" }, "code getter performs brand checks (i.e. is not [LegacyLenientThis])": { "status": "PASS" }, "code property is not affected by shadowing the name property": { "status": "PASS" }, "Object.prototype.toString behavior is like other interfaces": { "status": "PASS" }, "Inherits its toString() from Error.prototype": { "status": "PASS" }, "toString() behavior from Error.prototype applies as expected": { "status": "PASS" }, "DOMException.prototype.toString() applied to DOMException.prototype throws because of name/message brand checks": { "status": "PASS" }, "If the implementation has a stack property on normal errors, it also does on DOMExceptions": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/xhr/formdata/append.any.js.json ================================================ { "testFormDataAppend1": { "status": "PASS" }, "testFormDataAppend2": { "status": "PASS" }, "testFormDataAppendUndefined1": { "status": "PASS" }, "testFormDataAppendUndefined2": { "status": "PASS" }, "testFormDataAppendNull1": { "status": "PASS" }, "testFormDataAppendNull2": { "status": "PASS" }, "testFormDataAppendEmptyBlob": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/xhr/formdata/constructor.any.js.json ================================================ { "Constructors should throw a type error": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/xhr/formdata/delete.any.js.json ================================================ { "testFormDataDelete": { "status": "PASS" }, "testFormDataDeleteNonExistentKey": { "status": "PASS" }, "testFormDataDeleteOtherKey": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/xhr/formdata/foreach.any.js.json ================================================ { "Iterator should return duplicate keys and non-deleted values": { "status": "PASS" }, "Entries iterator should return duplicate keys and non-deleted values": { "status": "PASS" }, "Keys iterator should return duplicates": { "status": "PASS" }, "Values iterator should return non-deleted values": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/xhr/formdata/get.any.js.json ================================================ { "testFormDataGet": { "status": "PASS" }, "testFormDataGetNull1": { "status": "PASS" }, "testFormDataGetNull2": { "status": "PASS" }, "testFormDataGetAll": { "status": "PASS" }, "testFormDataGetAllEmpty1": { "status": "PASS" }, "testFormDataGetAllEmpty2": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/xhr/formdata/has.any.js.json ================================================ { "testFormDataHas": { "status": "PASS" }, "testFormDataHasEmpty1": { "status": "PASS" }, "testFormDataHasEmpty2": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/xhr/formdata/iteration.any.js.json ================================================ { "Iteration skips elements removed while iterating": { "status": "PASS" }, "Removing elements already iterated over causes an element to be skipped during iteration": { "status": "PASS" }, "Appending a value pair during iteration causes it to be reached during iteration": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/xhr/formdata/set-blob.any.js.json ================================================ { "blob without type": { "status": "PASS" }, "blob with type": { "status": "PASS" }, "blob with custom name": { "status": "PASS" }, "file without lastModified or custom name": { "status": "PASS" }, "file with lastModified and custom name": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/expectations/xhr/formdata/set.any.js.json ================================================ { "testFormDataSet1": { "status": "PASS" }, "testFormDataSet2": { "status": "PASS" }, "testFormDataSetUndefined1": { "status": "PASS" }, "testFormDataSetUndefined2": { "status": "PASS" }, "testFormDataSetNull1": { "status": "PASS" }, "testFormDataSetNull2": { "status": "PASS" }, "testFormDataSetEmptyBlob": { "status": "PASS" } } ================================================ FILE: tests/wpt-harness/post-harness.js ================================================ /* eslint-env serviceworker */ /* global add_completion_callback setup done */ let completionPromise = new Promise((resolve) => { add_completion_callback(function(tests, harness_status, asserts) { resolve({tests, harness_status, asserts}); }); }); setup({ explicit_done: true }); async function handleRequest(event) { let url = new URL(event.request.url); let input = `http://web-platform.test:8000${url.pathname}${url.search}`; let baseURL = new URL(input); setBaseURL(baseURL); globalThis.location = baseURL; try { let response = await fetch(input); let testSource = await response.text(); testSource += "\n//# sourceURL=" + url.pathname; let scripts = []; // eslint-disable-next-line no-unused-vars for (let [_, path] of testSource.matchAll(/META: *script=(.+)/g)) { let metaSource = await loadMetaScript(path, input); scripts.push(metaSource); } scripts.push(testSource); evalAllScripts(scripts); done(); let {tests} = await completionPromise; return new Response(JSON.stringify(tests, null, 2), { headers: { "content-encoding" : "application/json" } }); } catch (e) { console.log(`error: ${e}, stack:\n${e.stack}`); return new Response(`{ "error": { "message": ${JSON.stringify(e.message)}, "stack": ${JSON.stringify(e.stack)} } }`, { status: 500 }); } } function evalAllScripts(wpt_test_scripts) { for (let wpt_test_script of wpt_test_scripts) { (0, eval)(wpt_test_script); } } async function loadMetaScript(path) { let response = await fetch(path); let metaSource = await response.text(); // Somewhat annoyingly, the WPT harness includes META scripts as {results}
Test Result Message
================================================ FILE: tests/wpt-harness/results-section-error.template.html ================================================ ${prefix}${title}
Details

Message:

${message}

Stack:

${stack}

================================================ FILE: tests/wpt-harness/results-section.template.html ================================================ ${prefix}${title} ${pass} / ${total}duration: ${duration}ms ${info} ${rows} ================================================ FILE: tests/wpt-harness/run-wpt.mjs ================================================ import { argv } from 'process'; import { execFile } from "child_process"; import { on, once } from "events"; import { existsSync, mkdirSync, rmSync, readFileSync, writeFileSync } from "fs"; import http from "http"; import path from "path"; let LogLevel = { Quiet: 0, Verbose: 1, VeryVerbose: 2, }; function relativePath(path) { return new URL(path, import.meta.url).pathname; } const SLOW_PREFIX = "SLOW "; const config = { viceroy: { external: false, configFile: relativePath("./viceroy.toml"), host: "http://127.0.0.1:7676", runtime: "wpt-runtime.wasm", }, wptServer: { external: false, path: relativePath("./wpt/wpt"), }, server: { port: 7879, }, tests: { list: relativePath("tests.json"), expectations: relativePath("expectations"), updateExpectations: false, pattern: "", }, results: { pageTemplate: relativePath("results-page.template.html"), sectionTemplate: relativePath("results-section.template.html"), sectionErrorTemplate: relativePath("results-section-error.template.html"), }, interactive: false, skipSlowTests: false, logLevel: LogLevel.Quiet, }; const ArgParsers = { "--runtime": { help: `Path to .wasm file containing the WPT tests runtime to use (default: ${config.viceroy.runtime})`, cmd: val => { config.viceroy.runtime = val } }, "--port": { help: `Port to run the server on in interactive mode (default: ${config.server.port})`, cmd: val => { config.server.port = parseInt(val, 10); if (isNaN(config.server.port)) { return `Invalid value for --port: ${val}`; } } }, "--external-viceroy": { help: "Don't start a Viceroy instance internally (default: false)", cmd: () => { config.viceroy.external = true; } }, "--external-wpt-server": { help: "Don't start an instance of the WPT server internally (default: false)", cmd: () => { config.wptServer.external = true; } }, "--expectations": { help: `Path to the directory containing test expectations files (default: ${config.tests.expectations}}`, cmd: val => { config.tests.expectations = val; } }, "--update-expectations": { help: "Update test expectations file with results from the current run (default: false)", cmd: () => { config.tests.updateExpectations = true; } }, "--interactive": { help: "Start a server instead of directly running tests", cmd: () => { config.interactive = true; } }, "--skip-slow-tests": { help: "Skip tests that take a long time, in particular in debug builds of the runtime", cmd: () => { config.skipSlowTests = true; } }, "-v": { help: "Verbose output", cmd: () => { config.logLevel = LogLevel.Verbose; } }, "-vv": { help: "Very verbose output", cmd: () => { config.logLevel = LogLevel.VeryVerbose; } }, "--help": { help: "Print this help message", cmd: () => { console.log(`Usage: node run-wpt.mjs [...options] [pattern] If a pattern is provided, only tests whose path contains the pattern will be run Options:`); for (let [name, parser] of Object.entries(ArgParsers)) { console.log(` ${(name + (parser.cmd.length > 0 ? "=value" : "")).padEnd(25)}${parser.help}`); } process.exit(0); } }, } function applyConfig(argv) { for (let entry of argv.slice(2)) { if (entry[0] != "-") { config.tests.pattern = entry; continue; } let [arg, val] = entry.split("="); let result = undefined; let parser = ArgParsers[arg]; if (parser) { result = parser.cmd(val); } else { result = `Unknown argument: ${arg}`; } if (result) { console.error(result); process.exit(1); } } if (!existsSync(config.viceroy.runtime)) { console.error(`Runtime not found: ${config.viceroy.runtime}`); return false; } if (config.interactive) { if (config.tests.updateExpectations) { console.error("Can't update test expectations in interactive mode"); return false; } } return true; } async function run() { if (!applyConfig(argv)) { return process.exit(1); } let [wptServer, viceroy] = await Promise.all([ensureWptServer(config.wptServer, config.logLevel), ensureViceroy(config.viceroy, config.logLevel)]); if (config.interactive) { const server = http.createServer((req, res) => handleRequest(req, res, viceroy)); server.listen(config.server.port); console.log(`Listening on http://localhost:${config.server.port}`); } else { let {testPaths, totalCount } = getTests(config.tests.pattern); let pathLength = testPaths.reduce((length, path) => Math.max(path.length, length), 0); console.log(`Running ${testPaths.length} of ${totalCount} tests ...\n`); let expectationsUpdated = 0; let unexpectedFailure = false; let stats = await runTests(testPaths, viceroy, (testPath, results, stats) => { console.log(`${testPath.padEnd(pathLength)} ${formatStats(stats)}`); if (config.tests.updateExpectations && stats.unexpectedFail + stats.unexpectedPass + stats.missing > 0) { let expectPath = path.join(config.tests.expectations, testPath + ".json"); console.log(`writing changed expectations to ${expectPath}`); let expectations = {}; for (let result of results) { expectations[result.name] = { status: result.status === 0 ? 'PASS' : 'FAIL', }; } mkdirSync(path.dirname(expectPath), { recursive: true }); writeFileSync(expectPath, JSON.stringify(expectations, null, 2)); expectationsUpdated++; } }, (testPath, error, stats) => { let expectPath = path.join(config.tests.expectations, testPath + ".json"); let exists = existsSync(expectPath); if (exists) { console.log(`UNEXPECTED ERROR: ${testPath} (${stats.duration}ms) MESSAGE: ${error.message} STACK: ${error.stack.split('\n').join('\n ')}`); if (config.tests.updateExpectations) { console.log(`Removing expectations file ${expectPath}`); rmSync(expectPath); expectationsUpdated++; } else { unexpectedFailure = true; } } else { console.log(`EXPECTED ERROR: ${testPath} (${stats.duration}ms)`); } } ); console.log(`\n${"Done. Stats:".padEnd(pathLength)} ${formatStats(stats)}`); wptServer.process && wptServer.process.kill("SIGINT"); viceroy.process && viceroy.process.kill("SIGINT"); if (config.tests.updateExpectations) { console.log(`Expectations updated: ${expectationsUpdated}`); } else if (stats.unexpectedFail + stats.unexpectedPass + stats.missing != 0 || unexpectedFailure) { process.exitCode = 1; } } } function formatStats(stats) { return `${padStart(stats.pass, 4)} / ${padStart(stats.count, 4)} (${padStart("+" + stats.unexpectedPass, 5)}, ${padStart("-" + (stats.unexpectedFail), 5)}, ${padStart("?" + (stats.missing), 5)}) passing in ${padStart(stats.duration, 4)}ms`; } function padStart(value, length) { return (value + "").padStart(length); } async function ensureWptServer(config, logLevel) { if (config.external) { let wptServer = { ...config }; if (logLevel > LogLevel.Quiet) { console.info(`Using external WPT server`); } return wptServer; } else { return await startWptServer(config.path, logLevel); } } async function startWptServer(path, logLevel) { if (logLevel > LogLevel.Quiet) { console.info(`Starting WPT server ...`); } let server = execFile(path, ["--no-h2", "serve"]); server.on("error", event => { console.error(`error starting WPT server: ${event}`); process.exit(1); }); if (logLevel >= LogLevel.VeryVerbose) { server.stderr.on("data", data => { console.log(`WPT server stderr: ${stripTrailingNewline(data)}`); }); server.stdout.on("data", data => { console.log(`WPT server stdout: ${stripTrailingNewline(data)}`); }); } // Wait until the server has fully initialized. // `wpt.py serve` doesn't explicitly signal when it's done initializing, so we have to // read the tea leaves a bit, by waiting for a message that is among the very last to be // printed during initialization, well after the main http server has started. for await(let [chunk] of on(server.stdout, "data")) { if (/wss on port \d+\] INFO - Listen on/.test(chunk)) { if (logLevel > LogLevel.Quiet) { console.info(`Started internal WPT server`); } return { process: server, ...config }; } } } async function ensureViceroy(config, logLevel) { if (config.external) { let viceroy = { ...config }; if (logLevel > LogLevel.Quiet) { console.info(`Using external Viceroy host ${config.host}`); } return viceroy; } else { let viceroy = await startViceroy(config.runtime, config.configFile, logLevel); if (logLevel > LogLevel.Quiet) { console.info(`Started internal Viceroy host ${viceroy.host}`); } return viceroy; } } async function timeout(millis, message) { if (message === undefined) { message = `timeout reached after ${millis} milliseconds`; } return new Promise((_resolve, reject) => setTimeout(() => reject(message), millis)); } async function viceroyReady(viceroy, config) { // Wait until Viceroy has fully initialized and extract host from output. for await(const [chunk] of on(viceroy.stdout, "data")) { let result = chunk.match(/INFO Listening on (.+)/); if (result) { return { process: viceroy, host: result[1], ...config }; } } } async function startViceroy(runtime, config, logLevel) { if (logLevel > LogLevel.Quiet) { console.info(`Starting Viceroy server ...`); } let viceroy = execFile("viceroy", [runtime, "-C", config, "-v"]); viceroy.on("error", event => { console.error(`error starting Viceroy: ${event}`); process.exit(1); }); if (logLevel >= LogLevel.VeryVerbose) { viceroy.stderr.on("data", data => { console.log(`viceroy stderr: ${stripTrailingNewline(data)}`); }); viceroy.stdout.on("data", data => { console.log(`viceroy stdout: ${stripTrailingNewline(data)}`); }); } // give viceroy 20 seconds to become available const VICEROY_READY_TIMEOUT = 20000; return await Promise.race([ viceroyReady(viceroy, config), timeout(VICEROY_READY_TIMEOUT, "Viceroy failed to start"), ]); } function stripTrailingNewline(str) { if (str[str.length - 1] == '\n') { return str.substr(0, str.length - 1); } return str; } function getExpectedResults(testPath) { testPath = path.join(config.tests.expectations, testPath + ".json"); try { return JSON.parse(readFileSync(testPath)); } catch (e) { if (config.tests.updateExpectations) { if (config.logLevel >= LogLevel.Verbose) { console.log(`Expectations file ${testPath} will be created with results from current run`); } } return {}; } } function getTests(pattern) { config.logLevel >= LogLevel.Verbose && console.log(`Loading tests list from ${config.tests.list}`); let testPaths = JSON.parse(readFileSync(config.tests.list, { encoding: "utf-8" })); let totalCount = testPaths.length; if (config.skipSlowTests) { testPaths = testPaths.filter(path => !path.startsWith(SLOW_PREFIX)); } testPaths = testPaths.map(path => path.startsWith(SLOW_PREFIX) ? path.substr(SLOW_PREFIX.length) : path) .filter(path => path.indexOf(pattern) != -1); config.logLevel >= LogLevel.Verbose && console.log(`Loaded ${totalCount} tests, of which ${testPaths.length} match pattern ${pattern}${config.skipSlowTests ? " and aren't skipped for being slow" : ""}`); return { testPaths, totalCount }; } async function runTests(testPaths, viceroy, resultCallback, errorCallback) { let totalStats = { duration: 0, count: 0, pass: 0, missing: 0, unexpectedPass: 0, unexpectedFail: 0, }; for (let path of testPaths) { if (config.logLevel >= LogLevel.Verbose) { console.log(`Running test ${path}`); } let expectations = getExpectedResults(path); let t1 = Date.now(); let {response, body} = await request(`${viceroy.host}/${path}`); let stats = { count: 0, pass: 0, missing: 0, unexpectedPass: 0, unexpectedFail: 0, duration: Date.now() - t1, }; totalStats.duration += stats.duration; let results; try { results = JSON.parse(body); if (response.statusCode == 500) { throw {message: results.error.message, stack: results.error.stack}; } for (let result of results) { stats.count++; let expectation = expectations[result.name]; if (expectation) { expectation.did_run = true; result.expected = true; } if (result.status !== 0 && config.logLevel >= LogLevel.VeryVerbose) { console.error(result.message); } if (result.status == 0) { stats.pass++; if (!expectation || expectation.status === 'FAIL') { result.expected = false; console.log(`${expectation ? "UNEXPECTED" : "NEW"} PASS NAME: ${result.name}`); stats.unexpectedPass++; } } else if (!expectation || expectation.status === 'PASS') { result.expected = false; console.log(`${expectation ? "UNEXPECTED" : "NEW"} FAIL NAME: ${result.name} MESSAGE: ${result.message}`); stats.unexpectedFail++; } } for (let [name, expectation] of Object.entries(expectations)) { if (!expectation.did_run) { stats.missing++; console.log(`MISSING TEST NAME: ${name} EXPECTED RESULT: ${expectation.status}`); } } totalStats.count += stats.count; totalStats.pass += stats.pass; totalStats.missing += stats.missing; totalStats.unexpectedPass += stats.unexpectedPass; totalStats.unexpectedFail += stats.unexpectedFail; await resultCallback(path, results, stats); } catch (e) { if (!results) { e = new Error(`\nMISSING TEST RESULTS: ${path}\nParsing test results as JSON failed. Output was:\n ${body}`); totalStats.missing += Math.max(Object.keys(expectations).length, 1); } if (config.logLevel >= LogLevel.Verbose) { console.log(`Error running file ${path}: ${e.message}, stack:\n${e.stack}`); } await errorCallback(path, e, stats); } } return totalStats; } async function handleRequest(req, res, viceroy) { let pattern = req.url.substr(1); if (pattern == "favicon.ico") { return; } let {testPaths, totalCount } = getTests(pattern); res.writeHead(200, { 'Content-Type': 'text/html' }); let page = readFileSync(config.results.pageTemplate, { encoding: "utf-8" }); let [pageStart, pageEnd] = page.split("{results}"); pageStart = pageStart.split("{pattern}").join(`${pattern}`); pageStart = pageStart.split("{count}").join(`${testPaths.length} of ${totalCount}`); res.write(pageStart); let section = readFileSync(config.results.sectionTemplate, { encoding: "utf-8" }); let template = new Function("prefix", "title", "info", "pass", "total", "duration", "rows", `return \`${section}\``); let section_error = readFileSync(config.results.sectionErrorTemplate, { encoding: "utf-8" }); let error_template = new Function("prefix", "title", "message", "stack", `return \`${section_error}\``); let { duration, pass, count } = await runTests(testPaths, viceroy, (testPath, results, stats) => { let table = renderResultsTable(testPath, results, stats, template); res.write(table); }, (testPath, error, stats) => { let expectPath = path.join(config.tests.expectations, testPath + ".json"); let exists = existsSync(expectPath); let table = error_template(`${exists ? "UN" : ""}EXPECTED ERROR: `, testPath, error.message, renderStack(error.stack)); res.write(table); } ); res.end(pageEnd.split("{pass}").join(pass).split("{total}").join(count).split("{duration}").join(duration)); } async function request(url) { return new Promise(async (resolve, reject) => { let request = http.get(url); let [response] = await once(request, "response"); response.setEncoding('utf8'); let body = ""; response.on("data", chunk => { body += chunk; }); await once(response, "end"); resolve({ response, body }); }); } function renderResultsTable(title, results, stats, template) { let rows = results.map(test => { let name = test.name.split("<").join("<").split(">").join(">"); return ` ${name} ${test.status == 0 ? "PASS" : "FAIL"} ${ test.status ? `

${test.message}

Stack ${renderStack(test.stack)}
` : "" } ` } ).join("\n"); return template("", title, "", stats.pass, stats.count, stats.duration, rows); } function renderStack(stack) { stack = stack.split("<").join("<"); stack = stack.split(">").join(">"); // Strip the parts of the stack that's just about handling asserts. let lines = stack.split("\n"); for (let i = 0; i < lines.length; i++) { if (lines[i].indexOf("assert_wrapper") > -1) { lines = lines.slice(i + 1); break; } } stack = lines.join("
"); return stack; } await run(); ================================================ FILE: tests/wpt-harness/run-wpt.sh ================================================ #!/usr/bin/env bash # Use this script to run the wpt test harness locally. You'll need to have the # following executables in your path: # # * wizer # * npm # * node # # From any directory, run this script and it will do the following: # # 1. build js-compute-runtime.wasm and move it into the current directory # 2. build the wpt runner # 3. run the test suite and forward any arguments to it # # If you'd like to run a debug build, set the `DEBUG` environment variable when # running this script: # # > mkdir my_test # > cd my_test # > DEBUG=true ../tests/wpt-harness/run-wpt.sh # # For this to work, you'll need to have run the following command in advance: # # > cd runtime/spidermonkey # > ./build-engine.sh debug # # If you get an error about missing "jsapi.h" while building the runtime, # something's gone wrong with the engine download. set -euo pipefail working_dir="$(pwd)" root="$(dirname "${BASH_SOURCE[0]}")/../.." output="$(mktemp)" trap 'rm $output' EXIT echo "Building the runtime..." cd "$root" if ! npm run build:release > "$output" 2>&1; then cat "$output" exit 1 fi cp js-compute-runtime.wasm "$working_dir" cd "$working_dir" echo "Building the wpt runtime..." bash "$root/tests/wpt-harness/build-wpt-runtime.sh" echo "Running the wpt tests..." node "$root/tests/wpt-harness/run-wpt.mjs" "$@" ================================================ FILE: tests/wpt-harness/tests.json ================================================ [ "compression/compression-bad-chunks.tentative.any.js", "compression/compression-constructor-error.tentative.any.js", "compression/compression-including-empty-chunk.tentative.any.js", "compression/compression-large-flush-output.any.js", "compression/compression-multiple-chunks.tentative.any.js", "compression/compression-output-length.tentative.any.js", "SLOW compression/compression-stream.tentative.any.js", "compression/compression-with-detach.tentative.window.js", "compression/decompression-bad-chunks.tentative.any.js", "compression/decompression-buffersource.tentative.any.js", "compression/decompression-constructor-error.tentative.any.js", "compression/decompression-correct-input.tentative.any.js", "compression/decompression-corrupt-input.tentative.any.js", "compression/decompression-empty-input.tentative.any.js", "compression/decompression-split-chunk.tentative.any.js", "compression/decompression-uint8array-output.tentative.any.js", "compression/decompression-with-detach.tentative.window.js", "compression/idlharness.https.any.js", "console/console-is-a-namespace.any.js", "console/console-label-conversion.any.js", "SKIP console/console-log-large-array.any.js", "console/console-log-symbol.any.js", "console/console-namespace-object-class-string.any.js", "console/console-tests-historical.any.js", "console/idlharness.any.js", "dom/events/AddEventListenerOptions-once.any.js", "dom/events/AddEventListenerOptions-passive.any.js", "dom/events/Event-constructors.any.js", "dom/events/EventTarget-add-remove-listener.any.js", "dom/events/EventTarget-addEventListener.any.js", "dom/events/EventTarget-constructible.any.js", "dom/events/EventTarget-removeEventListener.any.js", "encoding/api-basics.any.js", "encoding/api-basics.any.js", "encoding/api-invalid-label.any.js", "encoding/api-replacement-encodings.any.js", "encoding/api-surrogates-utf8.any.js", "encoding/api-surrogates-utf8.any.js", "encoding/encodeInto.any.js", "SLOW encoding/idlharness.any.js", "encoding/iso-2022-jp-decoder.any.js", "encoding/replacement-encodings.any.js", "encoding/textdecoder-arguments.any.js", "encoding/textdecoder-byte-order-marks.any.js", "encoding/textdecoder-copy.any.js", "encoding/textdecoder-eof.any.js", "encoding/textdecoder-fatal-single-byte.any.js", "encoding/textdecoder-fatal-streaming.any.js", "encoding/textdecoder-fatal.any.js", "encoding/textdecoder-ignorebom.any.js", "encoding/textdecoder-labels.any.js", "encoding/textdecoder-streaming.any.js", "encoding/textdecoder-utf16-surrogates.any.js", "encoding/textencoder-constructor-non-utf.any.js", "encoding/textencoder-utf16-surrogates.any.js", "encoding/unsupported-encodings.any.js", "SKIP fetch/api/abort/cache.https.any.js", "fetch/api/abort/general.any.js", "fetch/api/abort/request.any.js", "fetch/api/basic/accept-header.any.js", "fetch/api/basic/conditional-get.any.js", "SKIP fetch/api/basic/error-after-response.any.js", "fetch/api/basic/header-value-combining.any.js", "fetch/api/basic/header-value-null-byte.any.js", "fetch/api/basic/historical.any.js", "fetch/api/basic/http-response-code.any.js", "fetch/api/basic/integrity.sub.any.js", "fetch/api/basic/keepalive.any.js", "SKIP fetch/api/basic/mode-no-cors.sub.any.js", "fetch/api/basic/mode-same-origin.any.js", "fetch/api/basic/referrer.any.js", "fetch/api/basic/referrer.any.js", "fetch/api/basic/request-head.any.js", "fetch/api/basic/request-headers-case.any.js", "fetch/api/basic/request-headers-nonascii.any.js", "fetch/api/basic/request-headers.any.js", "SKIP fetch/api/basic/request-private-network-headers.tentative.any.js", "fetch/api/basic/request-referrer.any.js", "fetch/api/basic/request-upload.any.js", "SKIP fetch/api/basic/request-upload.h2.any.js", "fetch/api/basic/response-null-body.any.js", "fetch/api/basic/response-url.sub.any.js", "fetch/api/basic/scheme-about.any.js", "fetch/api/basic/scheme-blob.sub.any.js", "fetch/api/basic/scheme-data.any.js", "fetch/api/basic/scheme-others.sub.any.js", "fetch/api/basic/status.h2.any.js", "fetch/api/basic/stream-response.any.js", "fetch/api/basic/stream-safe-creation.any.js", "fetch/api/basic/text-utf8.any.js", "fetch/api/body/cloned-any.js", "fetch/api/body/formdata.any.js", "fetch/api/body/mime-type.any.js", "fetch/api/headers/header-setcookie.any.js", "fetch/api/headers/header-values-normalize.any.js", "fetch/api/headers/header-values.any.js", "fetch/api/headers/headers-basic.any.js", "fetch/api/headers/headers-casing.any.js", "fetch/api/headers/headers-combine.any.js", "fetch/api/headers/headers-errors.any.js", "fetch/api/headers/headers-no-cors.any.js", "fetch/api/headers/headers-normalize.any.js", "fetch/api/headers/headers-record.any.js", "fetch/api/headers/headers-structure.any.js", "SKIP fetch/api/idlharness.any.js", "fetch/api/redirect/redirect-back-to-original-origin.any.js", "fetch/api/redirect/redirect-count.any.js", "fetch/api/redirect/redirect-empty-location.any.js", "fetch/api/redirect/redirect-keepalive.any.js", "fetch/api/redirect/redirect-keepalive.https.any.js", "fetch/api/redirect/redirect-location-escape.tentative.any.js", "fetch/api/redirect/redirect-location.any.js", "fetch/api/redirect/redirect-method.any.js", "fetch/api/redirect/redirect-mode.any.js", "fetch/api/redirect/redirect-origin.any.js", "fetch/api/redirect/redirect-referrer-override.any.js", "fetch/api/redirect/redirect-referrer.any.js", "fetch/api/basic/request-forbidden-headers.any.js", "fetch/api/redirect/redirect-schemes.any.js", "fetch/api/redirect/redirect-to-dataurl.any.js", "fetch/api/redirect/redirect-upload.h2.any.js", "fetch/api/request/forbidden-method.any.js", "SKIP [tests restrictions we're not imposing] fetch/api/request/request-bad-port.any.js", "fetch/api/request/request-cache-default-conditional.any.js", "fetch/api/request/request-cache-default.any.js", "fetch/api/request/request-cache-force-cache.any.js", "fetch/api/request/request-cache-no-cache.any.js", "fetch/api/request/request-cache-no-store.any.js", "fetch/api/request/request-cache-only-if-cached.any.js", "fetch/api/request/request-cache-reload.any.js", "fetch/api/request/request-cache.js", "fetch/api/request/request-constructor-init-body-override.any.js", "fetch/api/request/request-consume-empty.any.js", "fetch/api/request/request-consume.any.js", "fetch/api/request/request-disturbed.any.js", "fetch/api/request/request-error.any.js", "fetch/api/request/request-headers.any.js", "fetch/api/request/request-init-002.any.js", "fetch/api/request/request-init-contenttype.any.js", "fetch/api/request/request-init-priority.any.js", "fetch/api/request/request-init-stream.any.js", "fetch/api/request/request-keepalive.any.js", "fetch/api/request/request-structure.any.js", "fetch/api/response/json.any.js", "fetch/api/response/response-blob-realm.any.js", "fetch/api/response/response-cancel-stream.any.js", "fetch/api/response/response-clone.any.js", "fetch/api/response/response-consume-empty.any.js", "fetch/api/response/response-consume-stream.any.js", "fetch/api/response/response-error-from-stream.any.js", "fetch/api/response/response-error.any.js", "fetch/api/response/response-from-stream.any.js", "fetch/api/response/response-headers-guard.any.js", "fetch/api/response/response-init-001.any.js", "fetch/api/response/response-init-002.any.js", "fetch/api/response/response-init-contenttype.any.js", "fetch/api/response/response-static-error.any.js", "fetch/api/response/response-static-json.any.js", "fetch/api/response/response-static-redirect.any.js", "fetch/api/response/response-stream-bad-chunk.any.js", "fetch/api/response/response-stream-disturbed-1.any.js", "fetch/api/response/response-stream-disturbed-2.any.js", "fetch/api/response/response-stream-disturbed-3.any.js", "fetch/api/response/response-stream-disturbed-4.any.js", "fetch/api/response/response-stream-disturbed-5.any.js", "fetch/api/response/response-stream-disturbed-6.any.js", "fetch/api/response/response-stream-disturbed-by-pipe.any.js", "fetch/api/response/response-stream-with-broken-then.any.js", "fetch/data-urls/base64.any.js", "fetch/data-urls/processing.any.js", "fetch/content-type/multipart.window.js", "fetch/content-type/multipart-malformed.any.js", "FileAPI/blob/Blob-array-buffer.any.js", "FileAPI/blob/Blob-bytes.any.js", "FileAPI/blob/Blob-constructor.any.js", "FileAPI/blob/Blob-constructor-dom.window.js", "FileAPI/blob/Blob-in-worker.worker.js", "FileAPI/blob/Blob-slice.any.js", "FileAPI/blob/Blob-slice-overflow.any.js", "FileAPI/blob/Blob-stream.any.js", "FileAPI/blob/Blob-text.any.js", "FileAPI/file/File-constructor.any.js", "FileAPI/file/send-file-formdata.any.js", "FileAPI/file/send-file-formdata-controls.any.js", "FileAPI/file/send-file-formdata-punctuation.any.js", "FileAPI/file/send-file-formdata-utf-8.any.js", "hr-time/basic.any.js", "hr-time/idlharness.any.js", "hr-time/monotonic-clock.any.js", "html/webappapis/atob/base64.any.js", "streams/idlharness.any.js", "streams/piping/abort.any.js", "streams/piping/close-propagation-backward.any.js", "streams/piping/close-propagation-forward.any.js", "streams/piping/error-propagation-backward.any.js", "streams/piping/error-propagation-forward.any.js", "streams/piping/flow-control.any.js", "streams/piping/general-addition.any.js", "streams/piping/general.any.js", "streams/piping/multiple-propagation.any.js", "streams/piping/pipe-through.any.js", "streams/piping/then-interception.any.js", "streams/piping/throwing-options.any.js", "streams/piping/transform-streams.any.js", "streams/queuing-strategies-size-function-per-global.window.js", "streams/queuing-strategies.any.js", "streams/readable-byte-streams/bad-buffers-and-views.any.js", "streams/readable-byte-streams/construct-byob-request.any.js", "streams/readable-byte-streams/enqueue-with-detached-buffer.any.js", "streams/readable-byte-streams/general.any.js", "streams/readable-byte-streams/non-transferable-buffers.any.js", "streams/readable-byte-streams/read-min.any.js", "streams/readable-byte-streams/respond-after-enqueue.any.js", "streams/readable-byte-streams/tee.any.js", "streams/readable-streams/async-iterator.any.js", "streams/readable-streams/bad-strategies.any.js", "streams/readable-streams/bad-underlying-sources.any.js", "streams/readable-streams/cancel.any.js", "streams/readable-streams/constructor.any.js", "streams/readable-streams/count-queuing-strategy-integration.any.js", "streams/readable-streams/default-reader.any.js", "streams/readable-streams/floating-point-total-queue-size.any.js", "streams/readable-streams/from.any.js", "streams/readable-streams/garbage-collection.any.js", "streams/readable-streams/general.any.js", "streams/readable-streams/owning-type-message-port.any.js", "streams/readable-streams/owning-type-video-frame.any.js", "streams/readable-streams/owning-type.any.js", "streams/readable-streams/patched-global.any.js", "streams/readable-streams/reentrant-strategies.any.js", "streams/readable-streams/tee.any.js", "streams/readable-streams/templated.any.js", "streams/transform-streams/backpressure.any.js", "streams/transform-streams/cancel.any.js", "streams/transform-streams/errors.any.js", "streams/transform-streams/flush.any.js", "streams/transform-streams/general.any.js", "streams/transform-streams/lipfuzz.any.js", "streams/transform-streams/patched-global.any.js", "streams/transform-streams/properties.any.js", "streams/transform-streams/reentrant-strategies.any.js", "streams/transform-streams/strategies.any.js", "streams/transform-streams/terminate.any.js", "streams/writable-streams/aborting.any.js", "streams/writable-streams/bad-strategies.any.js", "streams/writable-streams/bad-underlying-sinks.any.js", "streams/writable-streams/byte-length-queuing-strategy.any.js", "streams/writable-streams/close.any.js", "streams/writable-streams/constructor.any.js", "streams/writable-streams/count-queuing-strategy.any.js", "streams/writable-streams/error.any.js", "streams/writable-streams/floating-point-total-queue-size.any.js", "streams/writable-streams/general.any.js", "streams/writable-streams/properties.any.js", "streams/writable-streams/reentrant-strategy.any.js", "streams/writable-streams/start.any.js", "streams/writable-streams/write.any.js", "url/historical.any.js", "SKIP url/idlharness.any.js", "SLOW url/url-constructor.any.js", "url/url-origin.any.js", "url/url-searchparams.any.js", "url/url-setters-stripping.any.js", "url/url-setters.any.js", "url/url-statics-canparse.any.js", "url/url-statics-parse.any.js", "url/url-tojson.any.js", "url/urlencoded-parser.any.js", "url/urlsearchparams-append.any.js", "url/urlsearchparams-constructor.any.js", "url/urlsearchparams-delete.any.js", "url/urlsearchparams-foreach.any.js", "url/urlsearchparams-get.any.js", "url/urlsearchparams-getall.any.js", "url/urlsearchparams-has.any.js", "url/urlsearchparams-set.any.js", "url/urlsearchparams-size.any.js", "url/urlsearchparams-sort.any.js", "url/urlsearchparams-stringifier.any.js", "WebCryptoAPI/digest/digest.https.any.js", "WebCryptoAPI/getRandomValues.any.js", "WebCryptoAPI/idlharness.https.any.js", "WebCryptoAPI/import_export/ec_importKey.https.any.js", "WebCryptoAPI/randomUUID.https.any.js", "WebCryptoAPI/sign_verify/ecdsa.https.any.js", "WebCryptoAPI/sign_verify/hmac.https.any.js", "html/webappapis/structured-clone/structured-clone.any.js", "html/webappapis/timers/clearinterval-from-callback.any.js", "html/webappapis/timers/cleartimeout-clearinterval.any.js", "html/webappapis/timers/evil-spec-example.any.js", "html/webappapis/timers/missing-timeout-setinterval.any.js", "html/webappapis/timers/negative-setinterval.any.js", "html/webappapis/timers/negative-settimeout.any.js", "html/webappapis/timers/type-long-setinterval.any.js", "html/webappapis/timers/type-long-settimeout.any.js", "webidl/ecmascript-binding/es-exceptions/DOMException-constants.any.js", "webidl/ecmascript-binding/es-exceptions/DOMException-constructor-and-prototype.any.js", "webidl/ecmascript-binding/es-exceptions/DOMException-constructor-behavior.any.js", "webidl/ecmascript-binding/es-exceptions/DOMException-custom-bindings.any.js", "xhr/formdata/constructor.any.js", "xhr/formdata/append.any.js", "xhr/formdata/constructor.any.js", "xhr/formdata/delete.any.js", "xhr/formdata/foreach.any.js", "xhr/formdata/get.any.js", "xhr/formdata/has.any.js", "xhr/formdata/iteration.any.js", "xhr/formdata/set.any.js", "xhr/formdata/set-blob.any.js" ] ================================================ FILE: tests/wpt-harness/viceroy.toml ================================================ [local_server] [local_server.backends] [local_server.backends.wpt] url = "http://web-platform.test:8000" ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "target": "es2022", "module": "nodenext", "lib": ["es2022"], "outDir": "./dist", "rootDir": "./src", "strict": true, "moduleResolution": "nodenext", "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "allowJs": true, "declaration": true }, "include": [ "src/**/*.ts", ], "exclude": [ "node_modules" ] } ================================================ FILE: typedoc.json ================================================ { "$schema": "https://typedoc.org/schema.json", "plugin": ["typedoc-plugin-versions", "typedoc-plugin-mdn-links"], "theme": "default", "tsconfig": "tsconfig.json", "exclude": ["types/index.d.ts"], "entryPointStrategy": "expand", "entryPoints": [ "types" ], "excludeExternals":true, "excludeInternal": true, "excludePrivate": true, "categorizeByGroup": false, "includeVersion": true, "githubPages": false, "cleanOutputDir": false, "out": "reference-docs" } ================================================ FILE: types/acl.d.ts ================================================ /// declare module 'fastly:acl' { /** * @version 3.32.0 */ class Acl { /** * Opens the given ACL store by name */ static open(aclName: string): Acl; /** * Lookup a given IP address in the ACL list. * * @example * import { Acl } from 'fastly:acl'; * addEventListener('fetch', async (evt) => { * const myAcl = Acl.open('myacl'); * const result = await myAcl.lookup(evt.client.address); * evt.respondWith(new Response(result?.action === 'BLOCK' ? 'blocked' : 'allowed')); * }); * * @param ipAddress Ipv6 or IPv4 IP address string * @returns An object containing the ACL action and IP prefix if the given IP address matches an ACL entry, or null if there is no match. */ lookup(ipAddress: string): Promise<{ action: 'ALLOW' | 'BLOCK'; prefix: string; } | null>; } } ================================================ FILE: types/backend.d.ts ================================================ /// /// declare module 'fastly:backend' { /** * Set the default backend configuration options for dynamic backends. * * Applies to backends created via {@link Backend | new Backend(...)} as well as for dynamic backends * implicitly created when using {@link fetch | fetch()}. * * @param defaultDynamicBackendConfiguration default backend configuration options * * @example * Setting default timeouts and TLS options for all newly created dynamic backends: * ```js * import { Backend, setDefaultDynamicBackendConfig } from "fastly:backend"; * setDefaultDynamicBackendConfig({ * connectTimeout: 1000, // milliseconds * firstByteTimeout: 15_000, // milliseconds * betweenBytesTimeout: 10_000, // milliseconds * useSSL: true, * tlsMinVersion: 1.3, * tlsMaxVersion: 1.3, * }); * // Timeouts and TLS configuration are inherited from the defaults above. * const backend = new Backend({ * target: 'my-site.com', * hostOverride: "www.my-site.com", * }); * ``` * @fiddle meta * { * "title": "setDefaultDynamicBackendConfig Example", * "request": "/status=200" * } * @version 3.24.0 */ export function setDefaultDynamicBackendConfig( defaultDynamicBackendConfiguration: DefaultBackendConfiguration, ): void; /** * Call this function to enforce the security property of explicitly-defined backends, even * when dynamic backends are enabled at the Fastly service level. * * By default, if dynamic backends are supported for the Fastly service, they will be automatically * used when creating a new `fetch()` request. This default behaviour for dynamic backends can be a * potential security concern since third-party JavaScript code may send arbitrary requests, * including sensitive/secret data, off to destinations that the JavaScript project was not * intending. * * When calling this function, an optional default backend name can be provided. * * @note * This is a separate option to the service-level dynamic backend support for Fastly services. * By default, dynamic backends are disabled for Fastly Services, so that even if not using this * function, the service-level security configuration will apply. * * @param defaultBackend the name of the default backend to use, when using {@link fetch | fetch()}. * * @version 3.24.0 * @experimental */ export function enforceExplicitBackends(defaultBackend?: string): void; /** * @version 3.24.0 */ interface DefaultBackendConfiguration { /** * Maximum duration in milliseconds to wait for a connection to this backend to be established. * If exceeded, the connection is aborted and a 503 response will be presented instead. * @defaultValue 1_000 * @throws {RangeError} Throws a RangeError if the value is negative or greater than or equal to 2^32 */ connectTimeout?: number; /** * Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. * If exceeded, the connection is aborted and a 503 response will be presented instead. * @defaultValue 15_000 * @throws {RangeError} Throws a RangeError if the value is negative or greater than or equal to 2^32 */ firstByteTimeout?: number; /** * Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. * If exceeded, the response received so far will be considered complete and the fetch will end. * @defaultValue 10_000 * @throws {RangeError} Throws a RangeError if the value is negative or greater than or equal to 2^32 */ betweenBytesTimeout?: number; /** * Whether or not to require TLS for connections to this backend. * * When using TLS, Fastly checks the validity of the backend's certificate, and fails the connection if the certificate is invalid. * This check is not optional: an invalid certificate will cause the backend connection to fail (but read on). * * By default, the validity check does not require that the certificate hostname matches the hostname of your request. * You can use {@link BackendConfiguration.certificateHostname} to request a check of the certificate hostname. * * By default, certificate validity uses a set of public certificate authorities. * You can specify an alternative CA using {@link caCertificate}. */ useSSL?: boolean; /** * Determine whether or not connections to the same backend should be pooled across different sessions. * Fastly considers two backends “the same” if they’re registered with the same name and the exact same settings. * In those cases, when pooling is enabled, if Session 1 opens a connection to this backend it will be left open, and can be re-used by Session 2. * This can help improve backend latency, by removing the need for the initial network / TLS handshake(s). * By default, pooling is enabled for dynamic backends. * @version 3.1.0 */ dontPool?: boolean; /** * Minimum allowed TLS version on SSL connections to this backend. * If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. * * @throws {RangeError} Throws a RangeError if the value is not 1, 1.1, 1.2, or 1.3 */ tlsMinVersion?: 1 | 1.1 | 1.2 | 1.3; /** * Maximum allowed TLS version on SSL connections to this backend. * If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. * * @throws {RangeError} Throws a RangeError if the value is not 1, 1.1, 1.2, or 1.3 */ tlsMaxVersion?: 1 | 1.1 | 1.2 | 1.3; /** * Define the hostname that the server certificate should declare. * * If not set (default), the server certificate may present any hostname. * * @throws {TypeError} Throws a TypeError if the value is an empty string. */ certificateHostname?: string; /** * The CA certificate to use when checking the validity of the backend. * * If not provided (default), the backend's certificate is validated using a set of public root CAs. * * @throws {TypeError} Throws a TypeError if the value is an empty string. */ caCertificate?: string; /** * List of OpenSSL ciphers to support for connections to this origin. * If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. * * [List of ciphers supported by Fastly](https://developer.fastly.com/learning/concepts/routing-traffic-to-fastly/#use-a-tls-configuration). * * @throws {TypeError} Throws a TypeError if the value is an empty string. */ ciphers?: string; /** * Set the client certificate to be provided to the server during the initial TLS handshake. * * @throws {TypeError} Throws a TypeError if the value is not an object of the correct type. * * @version 3.15.0 */ clientCertificate?: { /** The PEM certificate string. */ certificate: string; /** * The {@link import('fastly:secret-store').SecretStoreEntry} to use for the key, * created via `SecretStore.prototype.get` or via `SecretStore.fromBytes`. */ key: import('fastly:secret-store').SecretStoreEntry; }; /** * Enables and sets the HTTP keepalive time in milliseconds for the backend. * * @version 3.24.0 */ httpKeepalive?: number; /** * Enables and sets the TCP keep alive options for the backend. * Setting to boolean true enables keepalive with the default options. * * @version 3.24.0 */ tcpKeepalive?: | boolean | { /** * Configure how long to wait after the last sent data over the TCP connection before * starting to send TCP keepalive probes. */ timeSecs?: number; /** * Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. */ intervalSecs?: number; /** * Number of probes to send to the backend before it is considered dead. */ probes?: number; }; } interface BackendConfiguration extends DefaultBackendConfiguration { /** * The name of the backend. * The name has to be between 1 and 254 characters inclusive. * The name can be whatever you would like, as long as it does not match the name of any of the static service backends nor match any other dynamic backends built during a single execution of the application. * * If no name is provided, an autogenerated internal name will be used. * * @throws {TypeError} Throws a TypeError if the backend already exists or the name value is not valid, e.g., an empty string or a string with more than 254 characters. * * @deprecated to avoid name collisions it is recommended to use auto-generated names by omitting this property. */ name?: string; /** * A hostname, IPv4, or IPv6 address for the backend as well as an optional port. * If set, the target has to be at least 1 character. * * @example hostname * "example.com" * @example hostname and port * "example.com:443" * @example ip address * "1.2.3.4" * @example ip address and port * "1.2.3.4:8080" * * @throws {TypeError} Throws a TypeError if the value is not valid, i.e. is null, undefined, an empty string, not a valid IP address or host, or is the string `::` */ target: string; /** * If set, will force the HTTP Host header on connections to this backend to be the supplied value. * * @example * "example.com:443" * * @throws {TypeError} Throws a TypeError if the value is an empty string. */ hostOverride?: string; /** * The SNI hostname to use on connections to this backend. * * @throws {TypeError} Throws a TypeError if the value is an empty string. */ sniHostname?: string; /** * @experimental * * When enabled, sets that this backend is to be used for gRPC traffic. * * Warning: When using this experimental feature, no guarantees are provided for behaviours for * backends that do not provide gRPC traffic. * @version 3.23.0 */ grpc?: boolean; } /** * Class for dynamically creating new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/). * * **Note**: Dynamic backends are by default disabled at the Fastly service level. * Contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) * to request dynamic backends on Fastly Services. * * To disable the usage of dynamic backends, see {@link enforceExplicitBackends}. * * @example * In this example an explicit Dynamic Backend is created and supplied to the fetch request, the response is then returned to the client. * ```js * /// * import { Backend } from "fastly:backend"; * async function app() { * // For any request, return the fastly homepage -- without defining a backend! * const backend = new Backend({ * name: 'fastly', * target: 'fastly.com', * hostOverride: "www.fastly.com", * connectTimeout: 1000, * firstByteTimeout: 15000, * betweenBytesTimeout: 10000, * useSSL: true, * tlsMinVersion: 1.3, * tlsMaxVersion: 1.3, * }); * return fetch('https://www.fastly.com/', { * backend // Here we are configuring this request to use the backend from above. * }); * } * addEventListener("fetch", event => event.respondWith(app(event))); * ``` * @fiddle meta * { * "title": "Explicit Dynamic Backend Example", * "request": "/status=200" * } */ class Backend { /** * Creates a new Backend instance. * * **Note:** `Backend()` can only be constructed with `new`. Attempting to call it * without `new` throws a TypeError. * * All optional generic options can have their defaults set via * {@link setDefaultDynamicBackendConfig}. This includes all configuration * options except for `name`, `target`, `hostOverride`, `sniHostname` and `grpc`. * * @example * Construct a new backend with all properties set to their default values: * ```js * const myBackend = new Backend({ name: 'fastly', target: 'www.fastly.com'}); * ``` */ constructor(configuration: BackendConfiguration); /** * The name of the backend. * * @example * ```js * import { Backend } from "fastly:backend"; * const backend = new Backend({ * name: "my-backend", * target: "my-site.com", * }); * console.log(backend.name); // "my-backend" * ``` * @fiddle meta * { * "title": "Backend.prototype.name Example", * "request": "/status=200" * } * @version 3.24.0 */ readonly name: string; /** * Whether this backend was dynamically created by the running service. * @version 3.24.0 */ readonly isDynamic: boolean; /** * The host target for the backend * @version 3.24.0 */ readonly target: string; /** * The host header override defined for the backend. * * See https://docs.fastly.com/en/guides/specifying-an-override-host for more information. * @version 3.24.0 */ readonly hostOverride: string; /** * The backend port * @version 3.24.0 */ readonly port: number; /** * The connect timeout for the backend in milliseconds, if available. * When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. * @version 3.24.0 */ readonly connectTimeout: number | null; /** * The first byte timeout for the backend in milliseconds, if available. * When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. * @version 3.24.0 */ readonly firstByteTimeout: number | null; /** * The between bytes timeout for the backend in milliseconds, if available. * When not set or in environments that do not support this property (such as Viceroy), `null` may be returned. * @version 3.24.0 */ readonly betweenBytesTimeout: number | null; /** * The HTTP keepalive time for the backend in milliseconds, or 0 if no keepalive is set. * @version 3.24.0 */ readonly httpKeepaliveTime: number; /** * The TCP keepalive configuration, if TCP keepalive is enabled. * @version 3.24.0 */ readonly tcpKeepalive: null | { /** * The keepalive time in seconds. */ timeSecs: number | null; /** * The interval in seconds between probes. */ intervalSecs: number | null; /** * The number of probes to send before terminating the keepalive. */ probes: number | null; }; /** * Whether the backend is configured to use SSL. * @version 3.24.0 */ readonly isSSL: boolean; /** * The minimum TLS version number this backend will use. * When not used, or for environments that do not support this feature (such as Viceroy), `null` may be returned. * @version 3.24.0 */ readonly tlsMinVersion: 1 | 1.1 | 1.2 | 1.3 | null; /** * The maximum TLS version number this backend will use. * When not used, or for environments that do not support this feature (such as Viceroy), `null` may be returned. * @version 3.24.0 */ readonly tlsMaxversion: 1 | 1.1 | 1.2 | 1.3 | null; /** * Returns a string representing the health of this backend. * Possible values are: * * - "healthy" - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. * - "unhealthy" - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. * - "unknown" - The backend does not have a health check configured. * * @version 3.24.0 */ health(): 'healthy' | 'unhealthy' | 'unknown'; /** * Returns the name associated with the Backend instance. * @deprecated Use `backend.name` instead. * @version 3.7.0 */ toName(): string; /** * Returns the name associated with the Backend instance. * * The Backend object overrides the `toString()` method of Object; it does not inherit * `Object.prototype.toString()`. For Backend values, the `toString` method returns the * name given to the Backend object during construction. * * @example * ```js * import { Backend } from "fastly:backend"; * const backend = new Backend({ * name: "my-backend", * target: "my-site.com", * }); * console.log(backend.toString()); // "my-backend" * ``` * @fiddle meta * { * "title": "Backend.prototype.toString Example", * "request": "/status=200" * } * @deprecated Use `backend.name` instead. */ toString(): string; /** * Returns a boolean indicating if a Backend with the given name exists or not. * @version 3.7.0 */ static exists(name: string): boolean; /** * Returns the Backend instance with the given name, if one exists. If one does not exist, an error is thrown. * @version 3.7.0 */ static fromName(name: string): Backend; /** * Returns a string representing the health of the given Backend instance. * Possible values are: * * "healthy" - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. * "unhealthy" - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. * "unknown" - The backend does not have a health check configured. * * @deprecated Use `backend.health()` ({@link Backend.prototype.health}) instead. * @version 3.7.0 */ static health(backend: Backend): 'healthy' | 'unhealthy' | 'unknown'; } } ================================================ FILE: types/body.d.ts ================================================ /// declare module 'fastly:body' { /** * A low-level API for constructing and manipulating HTTP message bodies outside of the standard Fetch API. * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @example * ```js * import { FastlyBody } from 'fastly:body'; * * addEventListener('fetch', (event) => { * const body = new FastlyBody(); * body.append('Hello, '); * body.append('world!'); * const chunk = body.read(1024); * event.respondWith(new Response(chunk, { status: 200 })); * }); * ``` * * @version 3.9.0 */ export class FastlyBody { /** * Creates a new, empty `FastlyBody` instance. */ constructor(); /** * Appends the contents of another `FastlyBody` to this body. * The `dest` body is consumed by this operation and should not be reused. * * @param dest The `FastlyBody` to append to this body. * @throws `Error` if `dest` is not a `FastlyBody` instance. */ concat(dest: FastlyBody): void; /** * Reads up to `chunkSize` bytes from the body, advancing the read position. * Returns an empty `ArrayBuffer` when no more data is available. * * @param chunkSize The maximum number of bytes to read. Must be a positive number. * @throws `Error` if `chunkSize` is not a positive number, is `NaN`, or is `Infinity`. */ read(chunkSize: number): ArrayBuffer; /** * Appends data to the end of this body. * * @param data The data to append. * @throws `TypeError` if `data` is a guest-backed `ReadableStream` (not yet supported), * or if the `ReadableStream` is unusable (locked or already read from). */ append(data: BodyInit): void; /** * Prepends data to the beginning of this body. * * @param data The data to prepend. * @throws `TypeError` if `data` is a guest-backed `ReadableStream` (not yet supported), * or if the `ReadableStream` is unusable (locked or already read from). */ prepend(data: BodyInit): void; /** * Closes the body, signaling that no more data will be written. */ close(): void; /** * Abandons the body, discarding its contents without finalizing. * Unlike {@link close}, this signals that the body is being discarded rather than completed. * * @version 3.30.0 */ abandon(): void; } } ================================================ FILE: types/cache-override.d.ts ================================================ declare module 'fastly:cache-override' { /** * Cache customization options for responses, provided through the afterSend hook. * * For customizing the response status, headers, and other cache options, these * can be modified directly on the response. * * @version 3.30.0 */ interface CacheOptions { /** * Whether to cache this response. * * By default, leaving this field empty, responses will be cached based on their cache header * information. * * Setting this to true or false will override this default cache behaviour, setting in the cache * or not setting in the cache, even if the default behaviour would have been otherwise. * * Setting to 'uncacheable' the response will not only not be cached, but the cache will * record that the originating request led to an uncacheable response, so that future cache lookups * will result in immediately going to the backend, rather than attempting to coordinate concurrent * requests to reduce backend traffic. * * See the [Fastly request collapsing guide](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/request-collapsing/) * for more details on the mechanism that `uncacheable` disables. */ cache?: boolean | 'uncacheable'; /** * Provide a function to be used for transforming the response body prior to caching. * * Body transformations are performed by specifying a transform, rather than by directly working with the body * during the onAfterSend callback function, because not every response contains a fresh body: * 304 Not Modified responses, which are used to revalidate a stale cached response, are valuable precisely because * they do not retransmit the body. * * For any other response status, the backend response will contain a relevant body, and the `bodyTransformFn` will * be applied to it. The original backend body is passed in to the transform function, and the function is expected * to return the new body. */ bodyTransformFn?: ( body: Uint8Array, ) => Uint8Array | PromiseLike>; } /** * The cache override mode for a request * * If set to: * - "none": Do not override the behavior specified in the origin response’s cache control headers. * - "pass": Do not cache the response to this request, regardless of the origin response’s headers. * - "override": Override particular cache control settings using a {@linkcode CacheOverride} object. */ type CacheOverrideMode = 'none' | 'pass' | 'override'; interface ICacheOverride { /** * Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. */ ttl?: number; /** * Override the caching behavior of this request to use the given `stale-while-revalidate` time, * in seconds. */ swr?: number; /** * Override the caching behavior of this request to include the given surrogate key, provided as * a header value. * * See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) * for details. */ surrogateKey?: string; /** * Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant * non-volatile caching. * * By default, this is false, which means the request may not be PCI/HIPAA-compliant. Set it to * true to enable compliant caching. * * See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) * for details. */ pci?: boolean; /** * Set a [callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function) to be invoked if a * request is going all the way to a backend, allowing the request to be modified beforehand. * * See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) * in the Fastly cache interfaces documentation for details. * * @param request * @returns {void | PromiseLike} * * @version 3.30.0 */ beforeSend?: (request: Request) => void | PromiseLike; /** * Set a [callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function) to be invoked after * a response has been sent, but before it is stored into the cache. * * See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) * in the Fastly cache interfaces documentation for details. * * @param response * @returns {void | CacheOptions | PromiseLike} * * @version 3.30.0 */ afterSend?: ( response: Response, ) => void | CacheOptions | PromiseLike; } /** * Configures the caching behavior of a {@linkcode "globals".Response | Response}. * * Normally, the HTTP Headers on a {@linkcode "globals".Response | Response} would control how the {@linkcode "globals".Response | Response} is cached, * but `CacheOverride` can be set on a {@linkcode "globals".Request | Request}, to define custom caching behavior. * * @example * In this example we override the cache for all the requests prefixed /static/ to have a long TTL (Time To Live), * and the home page to have a short TTL and a long SWR (Stale While Revalidate). * * ```js * import { CacheOverride } from "fastly:cache-override"; * * async function app(event) { * const path = (new URL(event.request.url)).pathname; * let cacheOverride; * if (path == '/') { * cacheOverride = new CacheOverride('override', {ttl: 10, swr: 86_400}); * } else if (path.startsWith('/static/')) { * cacheOverride = new CacheOverride('override', {ttl: 86_400}); * } else { * cacheOverride = new CacheOverride('none') * } * return fetch(event.request.url, { * cacheOverride, * backend: 'my-backend' * }); * } * addEventListener("fetch", event => event.respondWith(app(event))); * ``` * @fiddle meta * { * "title": "CacheOverride Example", * "request": "/status=200" * } */ class CacheOverride { /** * @param mode Sets the cache override mode for a request * * If set to: * - "none": Do not override the behavior specified in the origin response’s cache control headers. * - "pass": Do not cache the response to this request, regardless of the origin response’s headers. * - "override": Override particular cache control settings using a {@linkcode CacheOverride} object. * * @param init Sets the cache override init options */ constructor(mode: CacheOverrideMode, init?: ICacheOverride); /** * When an init object is provided as the first argument, the mode defaults to `"override"`. * * @param overrideInit Sets the cache override init options * @version 3.30.0 */ constructor(overrideInit?: ICacheOverride); /** * Sets the cache override mode for a request * * If set to: * - "none": Do not override the behavior specified in the origin response’s cache control headers. * - "pass": Do not cache the response to this request, regardless of the origin response’s headers. * - "override": Override particular cache control settings using a {@linkcode CacheOverride} object. */ public mode: CacheOverrideMode; /** * Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. */ public ttl?: number; /** * Override the caching behavior of this request to use the given `stale-while-revalidate` time, * in seconds */ public swr?: number; /** * Override the caching behavior of this request to include the given surrogate key, provided as * a header value. * * See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) * for details. */ public surrogateKey?: string; /** * Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant * non-volatile caching. * * By default, this is false, which means the request may not be PCI/HIPAA-compliant. Set it to * true to enable compliant caching. * * See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) * for details. */ public pci?: boolean; /** * Callback to be invoked if a request is going all the way to a backend, allowing the request to be modified beforehand. * * See [Modifying a request as it is forwarded to a backend](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#modifying-a-request-as-it-is-forwarded-to-a-backend) * in the Fastly cache interfaces documentation for details. * * @version 3.30.0 */ public beforeSend?: (request: Request) => void | PromiseLike; /** * Callback to be invoked after a response has been sent, but before it is stored into the cache. * * See [Controlling cache behavior based on backend response](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#controlling-cache-behavior-based-on-backend-response) * in the Fastly cache interfaces documentation for details. * * @version 3.30.0 */ public afterSend?: ( response: Response, ) => void | CacheOptions | PromiseLike; } } ================================================ FILE: types/cache.d.ts ================================================ declare module 'fastly:cache' { interface PurgeOptions { /** * Where to purge the content from. * * "pop" - This will remove the content from the POP that contains the currently executing instance. * "global" - This will remove the content from all of Fastly. */ scope: 'pop' | 'global'; } /** * The `SimpleCache` class provides a simplified interface to inserting and retrieving entries * from Fastly's Cache. All methods on the class are static methods. * * For more advanced use cases requiring transactional lookups, request collapsing, or * revalidation, use {@link CoreCache} instead. * * @example * ```js * import { SimpleCache } from 'fastly:cache'; * * addEventListener('fetch', event => event.respondWith(app(event))); * * async function app(event) { * const path = new URL(event.request.url).pathname; * let page = await SimpleCache.getOrSet(path, async () => { * return { * value: await render(path), * // Store the page in the cache for 1 minute * ttl: 60 // seconds * } * }); * return new Response(await page.text(), { * headers: { 'content-type': 'text/plain;charset=UTF-8' } * }); * } * * async function render(path) { * // expensive/slow function which constructs and returns the contents for a given path * await new Promise(resolve => setTimeout(resolve, 10_000)); * return path; * } * ``` */ export class SimpleCache { /** * Gets the entry associated with the key `key` from the cache. * * @param key The key to retrieve from within the cache (up to 8,135 characters). * @returns The cached entry, or `null` if the key does not exist in the cache. * @throws `TypeError` if the provided `key` is an empty string, cannot be coerced to a string, or is longer than 8,135 characters. */ static get(key: string): SimpleCacheEntry | null; /** * Inserts a new entry or overwrites an existing entry in the cache. * * @deprecated Use {@link SimpleCache.getOrSet} instead. * @param key The key to store the entry under (up to 8,135 characters). * @param value The value to store in the cache. * @param ttl The time-to-live for this entry, in seconds. * @throws `TypeError` if the provided `key` is an empty string, cannot be coerced to a string, or is longer than 8,135 characters. */ static set(key: string, value: BodyInit, ttl: number): undefined; /** * Inserts a new entry or overwrites an existing entry in the cache using a `ReadableStream`. * * @deprecated Use {@link SimpleCache.getOrSet} instead. * @param key The key to store the entry under (up to 8,135 characters). * @param value A `ReadableStream` to store in the cache. * @param ttl The time-to-live for this entry, in seconds. * @param length The length of the `ReadableStream` value, in bytes. * @throws `TypeError` if the provided `key` is an empty string, cannot be coerced to a string, or is longer than 8,135 characters. */ static set( key: string, value: ReadableStream, ttl: number, length: number, ): undefined; /** * Attempts to get an entry from the cache for the supplied `key`. If no entry is found * (or has expired), the supplied `set` function is executed and its result is inserted * into the cache under the supplied `key`. * * @param key The key to lookup and/or store the entry under (up to 8,135 characters). * @param set A function to execute if the cache does not have a usable entry. Should return a Promise resolving with `value` and `ttl` (in seconds). * @throws `TypeError` if the provided `key` is an empty string, cannot be coerced to a string, or is longer than 8,135 characters. * @throws `TypeError` if the provided `ttl` cannot be coerced to a number, is negative, `NaN`, or `Infinity`. */ static getOrSet( key: string, set: () => Promise<{ value: BodyInit; ttl: number }>, ): Promise; /** * Attempts to get an entry from the cache for the supplied `key`. If no entry is found * (or has expired), the supplied `set` function is executed and its result is inserted * into the cache under the supplied `key`. * * When the value is a `ReadableStream`, the `length` property must be provided. * * @param key The key to lookup and/or store the entry under (up to 8,135 characters). * @param set A function to execute if the cache does not have a usable entry. Should return a Promise resolving with `value`, `ttl` (in seconds), and `length` (in bytes). * @throws `TypeError` if the provided `key` is an empty string, cannot be coerced to a string, or is longer than 8,135 characters. * @throws `TypeError` if the provided `ttl` cannot be coerced to a number, is negative, `NaN`, or `Infinity`. */ static getOrSet( key: string, set: () => Promise<{ value: ReadableStream; ttl: number; length: number; }>, ): Promise; /** * Purges the entry associated with the key `key` from the cache. * * @param key The key to purge from within the cache (up to 8,135 characters). * @param options Options controlling the scope of the purge. * @throws `TypeError` if the provided `key` is an empty string, cannot be coerced to a string, or is longer than 8,135 characters. */ static purge(key: string, options: PurgeOptions): undefined; } /** * Represents an entry retrieved from the {@link SimpleCache}. */ export interface SimpleCacheEntry { /** Provides access to the entry's contents as a `ReadableStream`. */ get body(): ReadableStream; /** Indicates whether the body has been read yet. */ get bodyUsed(): boolean; /** Reads the entry's stream to completion and returns the result as a string, decoded using UTF-8. */ text(): Promise; /** Reads the entry's stream to completion and parses the result as JSON. */ json(): Promise; /** Reads the entry's stream to completion and returns the result as an `ArrayBuffer`. */ arrayBuffer(): Promise; } /** * Options for cache lookups. * * @version 3.9.0 */ export interface LookupOptions { /** * Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. * The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. * A lookup will succeed when there is at least one cached item that matches lookup's `key`, and all of the lookup's headers included in the cache items' `vary` list match the corresponding headers in that cached item. * A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin's response. */ headers?: HeadersInit; } /** * Options for non-transactional cache insertions via {@link CoreCache.insert}. * * @version 3.9.0 */ export interface InsertOptions extends TransactionInsertOptions { /** * Note: These headers are narrowly useful for implementing cache lookups incorporating the semantics of the HTTP Vary header. * The headers act as additional factors in object selection, and the choice of which headers to factor in is determined during insertion, via the `vary` property within `TransactionInsertOptions`. * A lookup will succeed when there is at least one cached item that matches lookup's `key`, and all of the lookup's headers included in the cache items' `vary` list match the corresponding headers in that cached item. * A typical example is a cached HTTP response, where the request had an "Accept-Encoding" header. In that case, the origin server may or may not decide on a given encoding, and whether that same response is suitable for a request with a different (or missing) Accept-Encoding header is determined by whether Accept-Encoding is listed in Vary header in the origin's response. */ headers?: HeadersInit; } /** * Options for transactional cache insertions. * * @version 3.9.0 */ export interface TransactionInsertOptions { /** * Sets the "time to live" for the cache item in milliseconds: The time for which the item will be considered fresh. */ maxAge: number; /** * Sets the list of headers that must match when looking up this cached item. */ vary?: Array; /** * Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. * * The initial age is 0 by default. */ initialAge?: number; /** * Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. * Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. * The methods `CacheState.prototype.usable` and `CacheState.prototype.stale` can be used to determine the current state of an item. * * The stale-while-revalidate period is 0 by default. */ staleWhileRevalidate?: number; /** * Sets the surrogate keys that can be used for purging this cached item. * Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item's TTL to elapse, or overwriting the item with insert(). * Surrogate keys must contain only printable ASCII characters (those between 0x21 and 0x7E, inclusive). Any invalid keys will be ignored. * * See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/working-with-surrogate-keys) for details. */ surrogateKeys?: Array; /** * Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. * It is preferable to provide a length, if possible. * Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. */ length?: number; /** * Sets the user-defined metadata to associate with the cached item. */ userMetadata?: ArrayBufferView | ArrayBuffer | URLSearchParams | string; /** * Enable or disable PCI/HIPAA-compliant non-volatile caching. * By default, this is false. * * See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for details. */ sensitive?: boolean; } /** * The CoreCache class exposes the Compute Core Cache API, the same set of primitive operations used to build Fastly services. * The Core Cache API puts the highest level of power in the hands of the user, but requires manual serialization of cache contents and explicit handling of request collapsing and revalidation control flow. * * @version 3.9.0 */ export class CoreCache { /** * Perform a non-transactional lookup into the cache, returning a CacheEntry if a usable cached item was found. * A cached item is usable if its age is less than the sum of its TTL and its stale-while-revalidate period. Items beyond that age are unusably stale. * * Note: A non-transactional lookup will not attempt to coordinate with any concurrent cache lookups. * If two instances of the service perform a lookup at the same time for the same cache key, and the item is not yet cached, they will both return `null`. * Without further coordination, they may both end up performing the work needed to insert() the item (which usually involves origin requests and/or computation) and racing with each other to insert. * To resolve such races between concurrent lookups, use `CoreCache.transactionLookup()` instead. * * @param key A cache key which is a string with a length of up to 8,135 that identify a cached item. The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. * @param options A set of options to used whilst performing this lookup into the cache. * @throws `TypeError` if the provided `key` is an empty string, cannot be coerced to a string, or is longer than 8,135 characters. */ static lookup(key: string, options?: LookupOptions): CacheEntry | null; /** * Perform a non-transactional insertion into the cache, returning a `FastlyBody` instance for providing the cached object itself. * For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.prototype.close` must be called. * If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. * * Note: Like `CoreCache.lookup()`, `CoreCache.insert()` may race with concurrent lookups or insertions, and will unconditionally overwrite existing cached items rather than allowing for revalidation of an existing object. * The transactional equivalent of this function is `TransactionCacheEntry.insert()`, which may only be called following a `CoreCache.transactionLookup()` call and the returned `CacheEntry` when has a state where `CacheState.mustInsertOrUpdate()` returns true. * * @param key A cache key which is a string with a length of up to 8,135 that identify a cached item. The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. * @param options A set of options to used whilst performing this insertion into the cache. * @throws `TypeError` if the provided `key` is an empty string, cannot be coerced to a string, or is longer than 8,135 characters. */ static insert( key: string, options: InsertOptions, ): import('fastly:body').FastlyBody; /** * Perform a transactional lookup into the cache, returning a `TransactionCacheEntry` instance. * * Transactions coordinate between concurrent actions on the same cache key, incorporating concepts of [request collapsing](https://developer.fastly.com/learning/concepts/request-collapsing/) and [revalidation](https://developer.fastly.com/learning/concepts/stale/), though at a lower level that does not automatically interpret HTTP semantics. * * Request Collapsing: * If there are multiple concurrent calls to `CoreCache.transactionLookup()` for the same item and that item is not present, * just one of the callers will be instructed to insert the item into the cache as part of the transaction. * The other callers will block until the metadata for the item has been inserted, and can then begin streaming its contents out of the cache at the same time that the inserting caller streams them into the cache. * * Revalidation: * Similarly, if an item is usable but stale, and multiple callers attempt a `CoreCache.transactionLookup()` concurrently, they will all be given access to the stale item, but only one will be designated to perform an asynchronous update (or insertion) to freshen the item in the cache. * * @param key A cache key which is a string with a length of up to 8,135 that identify a cached item. The cache key may not uniquely identify an item; headers can be used to augment the key when multiple items are associated with the same key. * @param options A set of options to used whilst performing this lookup into the cache. * @throws `TypeError` if the provided `key` is an empty string, cannot be coerced to a string, or is longer than 8,135 characters. */ static transactionLookup( key: string, options?: LookupOptions, ): TransactionCacheEntry; } /** * The status of this lookup (and potential transaction). * * @version 3.9.0 */ export class CacheState { /** * Returns `true` if a cached item was located. * * Even if a cached item is found, the cached item might be stale and require updating. Use `mustInsertOrUpdate()` to determine whether this transaction client is expected to update the cached item. */ found(): boolean; /** * Returns `true` if the cached item is usable. * * A cached item is usable if its age is less than the sum of the `maxAge` and `staleWhileRevalidate` periods. */ usable(): boolean; /** * Returns `true` if the cached item is stale. * * A cached item is stale if its age is greater than its `maxAge` period. */ stale(): boolean; /** * Returns `true` if a fresh cache item was not found, and this transaction client is expected to insert a new item or update a stale item. */ mustInsertOrUpdate(): boolean; } /** * Options for requesting a byte range within a cached item. * * @version 3.9.0 */ export interface CacheBodyOptions { /** * The offset from which to start the range. */ start: number; /** * How long the range should be. */ end: number; } /** * Represents a cached item retrieved via {@link CoreCache.lookup} or as part of a * {@link TransactionCacheEntry.insertAndStreamBack} operation. * * @version 3.9.0 */ export class CacheEntry { /** * Closes the connection to the cache for this `CacheEntry`. */ close(): void; /** * Returns a `CacheState` instance which reflects the current state of this `CacheEntry` instance. */ state(): CacheState; /** * The user-controlled metadata associated with the cached item. */ userMetadata(): ArrayBuffer; /** * Retrieves the cached item as a `ReadableStream`. * * Only one stream can be active at a time for a given `CacheEntry`. An error will be thrown if a stream is already active for this CacheEntry. * * @param options Optional property used to request a range of bytes within the cached item. */ body(options?: CacheBodyOptions): ReadableStream; /** * The size in bytes of the cached item, if known. * * @returns The length in bytes, or `null` if the length is currently unknown. The length may be unknown if the item is currently being streamed into the cache without a fixed length. */ length(): number | null; /** * The time in milliseconds for which the cached item is considered fresh. */ maxAge(): number; /** * The time in milliseconds for which a cached item can safely be used despite being considered stale. */ staleWhileRevalidate(): number; /** * The current age in milliseconds of the cached item. */ age(): number; /** * Determines the number of cache hits to this cached item. * * Note: this hit count only reflects the view of the server that supplied the cached item. Due to clustering, this count may vary between potentially many servers within the data center where the item is cached. See the [clustering documentation](https://developer.fastly.com/learning/vcl/clustering/) for details, though note that the exact caching architecture of Compute is different from VCL services. */ hits(): number; } /** * Options for updating a cached item's metadata via {@link TransactionCacheEntry.update}. * * @version 3.9.0 */ export interface TransactionUpdateOptions { /** * Sets the "time to live" for the cache item in milliseconds: The time for which the item will be considered fresh. */ maxAge: number; /** * Sets the list of headers that must match when looking up this cached item. */ vary?: Array; /** * Sets the initial age of the cached item, in milliseconds, to be used in freshness calculations. * * The initial age is 0 by default. */ initialAge?: number; /** * Sets the stale-while-revalidate period, in milliseconds for the cached item, which is the time for which the item can be safely used despite being considered stale. * Having a stale-while-revalidate period provides a signal that the cache should be updated (or its contents otherwise revalidated for freshness) asynchronously, while the stale cached item continues to be used, rather than blocking on updating the cached item. * The methods `CacheState.prototype.usable` and `CacheState.prototype.stale` can be used to determine the current state of an item. * * The stale-while-revalidate period is 0 by default. */ staleWhileRevalidate?: number; /** * Sets the surrogate keys that can be used for purging this cached item. * Surrogate key purges are the only means to purge specific items from the cache. At least one surrogate key must be set in order to remove an item without performing a purge-all, waiting for the item's TTL to elapse, or overwriting the item with insert(). * Surrogate keys must contain only printable ASCII characters (those between `0x21` and `0x7E`, inclusive). Any invalid keys will be ignored. * * See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/working-with-surrogate-keys) for details. */ surrogateKeys?: Array; /** * Sets the size of the cached item, in bytes, when known prior to actually providing the bytes. * It is preferable to provide a length, if possible. * Clients that begin streaming the item's contents before it is completely provided will see the promised length which allows them to, for example, use content-length instead of transfer-encoding: chunked if the item is used as the body of a Request or Response. */ length?: number; /** * Sets the user-defined metadata to associate with the cached item. */ userMetadata?: ArrayBufferView | ArrayBuffer | URLSearchParams | string; } /** * Represents a cached item retrieved via a transactional lookup ({@link CoreCache.transactionLookup}). * Extends {@link CacheEntry} with methods for inserting, updating, and cancelling cache transactions. * * @version 3.9.0 */ export class TransactionCacheEntry extends CacheEntry { /** * Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself. * * This method should only be called when `TransactionCacheEntry.state().mustInsertOrUpdate()` is true; otherwise, an error will be thrown when attempting to perform the insertion. */ insert(options: TransactionInsertOptions): import('fastly:body').FastlyBody; /** * Perform a transactional cache insertion, returning a `FastlyBody` instance for providing the cached object itself, and a `CacheEntry` instance which can be used to stream out the newly-inserted cache item. * * For the insertion to complete successfully, the object must be written into the returned `FastlyBody` instance, and then `FastlyBody.prototype.close` must be called. * If `FastlyBody.prototype.close` does not get called, the insertion is considered incomplete, and any concurrent lookups that may be reading from the object as it is streamed into the cache may encounter a streaming error. */ insertAndStreamBack( options: TransactionInsertOptions, ): [import('fastly:body').FastlyBody, CacheEntry]; /** * Perform an update of the cache item's metadata. */ update(options: TransactionUpdateOptions): void; /** * Cancel an obligation to provide an object to the cache. */ cancel(): void; } } ================================================ FILE: types/compute.d.ts ================================================ declare module 'fastly:compute' { /** * Get the current elapsed vCPU time in milliseconds for the current request handler. * * @version 3.22.0 */ export function vCpuTime(): number; /** * Purge the given surrogate key from Fastly's HTTP and Core caches. * * There are two purge modes: hard purge (the default) clears all matching items from * the cache immediately, while soft purge retains stale entries in the cache, reducing * origin load while enabling stale revalidations. * * See the [Fastly Purge documentation](https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#surrogate-key-purge) * for more information on caching and purge operations. * * @param surrogateKey The surrogate key string to purge. * @param soft Enable to perform a soft purge, retaining stale cache entries to * reduce load on the origin server. Defaults to a hard purge. * @version 3.22.0 */ export function purgeSurrogateKey( surrogateKey: string, soft?: boolean, ): void; } ================================================ FILE: types/config-store.d.ts ================================================ declare module 'fastly:config-store' { /** * Class for accessing a [Fastly Config Store](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @example * ```js * import { ConfigStore } from "fastly:config-store"; * * async function app(event) { * const config = new ConfigStore("animals"); * return new Response(config.get("cat")); * } * addEventListener("fetch", (event) => event.respondWith(app(event))); * ``` */ class ConfigStore { /** * Creates a new ConfigStore object, providing access to the named * [Config Store resource](https://www.fastly.com/documentation/reference/api/services/resources/config-store/). * * @param name The resource link name for the Config Store. * @throws `TypeError` if no Config Store exists with the provided name. * @throws `TypeError` if the provided name is empty, longer than 255 characters, * does not start with an ASCII alphabetical character, or contains characters * other than ASCII alphanumerics, underscores, and spaces. */ constructor(name: string); /** * Get a value for a key in the Config Store. If the provided key does not * exist in the Config Store then this returns `null`. * * @param key The key to retrieve. * @throws `TypeError` if the provided key is empty or longer than 255 characters. */ get(key: string): string | null; } } ================================================ FILE: types/device.d.ts ================================================ declare module 'fastly:device' { /** * Provides device detection based on User-Agent strings. * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @version 3.10.0 */ class Device { /** * Look up the data associated with a particular User-Agent string. * If there is data associated with the User-Agent, a `Device` instance is returned. * Otherwise, `null` is returned. * * @param useragent The User-Agent string to look up. * @throws `TypeError` if the provided User-Agent string is empty. */ static lookup(useragent: string): Device | null; /** * The name of the device, or `null` if no name is known. */ get name(): string | null; /** * The brand of the device, which may be different from the manufacturer. * `null` if no brand is known. */ get brand(): string | null; /** * The model of the device, or `null` if no model is known. */ get model(): string | null; /** * A string representation of the device's primary platform hardware, * or `null` if not known. * * The most commonly used device types are also identified via boolean * properties. Because a device may have multiple device types and this * property only has the primary type, we recommend using the boolean * properties for logic and this string representation for logging. */ get hardwareType(): string | null; /** * Whether the device is a desktop web browser, or `null` if not known. */ get isDesktop(): boolean | null; /** * Whether the device is a video game console, or `null` if not known. */ get isGameConsole(): boolean | null; /** * Whether the device is a media player (like Blu-ray players, iPod * devices, and smart speakers such as Amazon Echo), or `null` if not known. */ get isMediaPlayer(): boolean | null; /** * Whether the device is a mobile phone, or `null` if not known. */ get isMobile(): boolean | null; /** * Whether the device is a smart TV, or `null` if not known. */ get isSmartTV(): boolean | null; /** * Whether the device is a tablet (like an iPad), or `null` if not known. */ get isTablet(): boolean | null; /** * Whether the device's screen is touch sensitive, or `null` if not known. */ get isTouchscreen(): boolean | null; /** * Whether the device is a bot, or `null` if not known. * * @version 3.39.0 */ get isBot(): boolean | null; /** * Returns a JSON representation of the Device object. * * To get a JSON string, you can use `JSON.stringify(device)` directly; * it will call `toJSON()` automatically. */ toJSON(): Object; } } ================================================ FILE: types/dictionary.d.ts ================================================ declare module 'fastly:dictionary' { /** * Class for accessing [Fastly Edge Dictionaries](https://docs.fastly.com/en/guides/about-edge-dictionaries). * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @deprecated Use {@link config-store!ConfigStore | ConfigStore} from `'fastly:config-store'` instead. */ class Dictionary { /** * Creates a new Dictionary object, providing access to the named * [Edge Dictionary](https://docs.fastly.com/en/guides/about-edge-dictionaries). * * @param name The name of the Edge Dictionary. * @throws `TypeError` if no Dictionary exists with the provided name. * @throws `TypeError` if the provided name is empty, longer than 255 characters, * does not start with an ASCII alphabetical character, or contains characters * other than ASCII alphanumerics, underscores, and spaces. * @deprecated Use {@link config-store!ConfigStore | ConfigStore} from `'fastly:config-store'` instead. */ constructor(name: string); /** * Get a value for a key in the Dictionary. If the provided key does not * exist in the Dictionary then this returns `null`. * * @param key The key to retrieve. * @throws `TypeError` if the provided key is empty or longer than 255 characters. * @deprecated Use {@link config-store!ConfigStore | ConfigStore} from `'fastly:config-store'` instead. */ get(key: string): string | null; } } ================================================ FILE: types/edge-rate-limiter.d.ts ================================================ declare module 'fastly:edge-rate-limiter' { /** * Provides [Edge Rate Limiting](https://docs.fastly.com/products/edge-rate-limiting) by * combining a {@link RateCounter} and a {@link PenaltyBox}. * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @version 3.9.0 */ export class EdgeRateLimiter { /** * Open an EdgeRateLimiter with the given rate counter and penalty box. * * @param rateCounter The RateCounter instance to associate with this EdgeRateLimiter. * @param penaltyBox The PenaltyBox instance to associate with this EdgeRateLimiter. * @throws `TypeError` If `rateCounter` is not an instance of RateCounter. * or if `penaltyBox` is not an instance of PenaltyBox. */ constructor(rateCounter: RateCounter, penaltyBox: PenaltyBox); /** * Increment an entry in the rate counter and check if the entry has exceeded * some average number of requests per second (RPS) over the given window. * If the entry is over the RPS limit for the window, add it to the penalty * box for the given `timeToLive`. * * @param entry The name of the entry to increment and check. * @param delta The amount to increment the entry by. * @param window The time period in seconds to check across. * @param limit The requests-per-second limit. * @param timeToLive How long in minutes (1–60) the entry should be added * into the penalty box. Value is truncated to the nearest minute. * @returns `true` if the entry has exceeded the average RPS for the window, * otherwise `false`. * @throws `TypeError` If `delta` is not a non-negative finite number, * if `window` is not 1, 10, or 60, if `limit` is not a non-negative finite number, * or if `timeToLive` is not a number between 1 and 60. */ checkRate( entry: string, delta: number, window: 1 | 10 | 60, limit: number, timeToLive: number, ): boolean; } /** * A penalty box that can be used with {@link EdgeRateLimiter} or standalone * for adding and checking if an entry is in the dataset. * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @version 3.9.0 */ export class PenaltyBox { /** * Open a penalty box identified by the given name. * * @param name The name of the penalty box to open. */ constructor(name: string); /** * Add an entry to the penalty box for the duration of the given `timeToLive`. * * @param entry The entry to add. * @param timeToLive How long in minutes (1–60) the entry should be added * into the penalty box. Value is truncated to the nearest minute. * @throws `TypeError` if `timeToLive` is not a number between 1 and 60. */ add(entry: string, timeToLive: number): void; /** * Check if an entry is in the penalty box. * * @param entry The entry to look up. * @returns `true` if the entry is in the penalty box, otherwise `false`. */ has(entry: string): boolean; } /** * A rate counter that can be used with {@link EdgeRateLimiter} or standalone * for counting and rate calculations. * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @version 3.9.0 */ export class RateCounter { /** * Open a RateCounter instance with the given name. * * @param name The name of the rate counter. */ constructor(name: string); /** * Increment the given entry by `delta`. * * @param entry The entry to increment. * @param delta The amount to increment the entry by. * @throws `TypeError` if `delta` is not a non-negative finite number. */ increment(entry: string, delta: number): void; /** * Look up the current rate for an entry over a given window. * * @param entry The entry to look up. * @param window The time window in seconds to look up alongside the entry. * @returns The rate for the given entry and window. * @throws `TypeError` if `window` is not 1, 10, or 60. */ lookupRate(entry: string, window: 1 | 10 | 60): number; /** * Look up the current count for an entry over a given duration. * * @param entry The entry to look up. * @param duration The duration in seconds to look up alongside the entry. * @returns The count for the given entry and duration. * @throws `TypeError` if `duration` is not 10, 20, 30, 40, 50, or 60. */ lookupCount(entry: string, duration: 10 | 20 | 30 | 40 | 50 | 60): number; } } ================================================ FILE: types/env.d.ts ================================================ declare module 'fastly:env' { /** * Function to get the value for the provided environment variable name. * * For a list of available environment variables, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) * * **Note**: The environment variables can only be retrieved when processing requests, not during build-time initialization. * * @param name The name of the environment variable * * @example * * In this example we log to stdout the environment variables `FASTLY_HOSTNAME` and `FASTLY_TRACE_ID`. * * * */ function env(name: string): string; } ================================================ FILE: types/experimental.d.ts ================================================ /** * @experimental */ declare module 'fastly:experimental' { import type { enforceExplicitBackends } from 'fastly:backend'; /** * JavaScript SDK version string for the JS runtime engine build. * * @experimental * @hidden */ export const sdkVersion: string; /** * @experimental * @hidden */ export function setBaseURL(base: URL | null | undefined): void; /** * Set the default backend to use when dynamic backends are disabled. * * For backwards compatibility, unless `allowDynamicBackends` has been explicitly * called before invoking this function, it will disable dynamic backends when * it is called, as if calling `allowDynamicBackends(false)`. * * @param backend The name of the default backend. * @experimental * @deprecated Use {@link enforceExplicitBackends} instead. */ export function setDefaultBackend(backend: string): void; /** * Causes the Fastly Compute JS runtime environment to log debug information to stdout. * * **Note**: This is mostly for internal debugging purposes and will generate highly unstable * output. * @experimental * @hidden */ export function enableDebugLogging(enabled: boolean): void; /** * Embed a file as a Uint8Array. * * **Note**: Can only be used during build-time initialization, not when processing requests. * * @param path The path to include, relative to the project's top-level directory. * @experimental */ export function includeBytes(path: string): Uint8Array; /** * Control whether or not Dynamic Backends are allowed within this Fastly * Compute service. * * By default, Dynamic Backends are disabled within a JavaScript application * as it can be a potential avenue for third-party JavaScript code to send * requests, potentially including sensitive/secret data, off to destinations * that the JavaScript project was not intending, which could be a security * issue. * * **Note**: This feature is disabled by default for Fastly Services. Please * contact [Fastly Support](https://support.fastly.com/hc/en-us/requests/new?ticket_form_id=360000269711) * to request the feature be enabled on the Fastly Services which require * Dynamic Backends. * * @param enabled Whether or not to allow Dynamic Backends. * @experimental * @deprecated Use {@link enforceExplicitBackends} instead. */ export function allowDynamicBackends(enabled: boolean): void; /** * Enable Dynamic Backends with default timeout configuration. * * @param defaultConfig Default timeout configuration for dynamic backends. * @throws `RangeError` if any timeout value is negative or greater than or * equal to 2^32. * @experimental * @deprecated Use {@link enforceExplicitBackends} instead. */ export function allowDynamicBackends(defaultConfig: { /** Maximum duration in milliseconds to wait for a connection to be established. */ connectTimeout?: number; /** Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. */ firstByteTimeout?: number; /** Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. */ betweenBytesTimeout?: number; }): void; /** * Get information about an error as a ready-to-print array. * This includes the error name, message, and a call stack. * * If `--enable-stack-traces` is specified during the build, the call stack * will be mapped using source maps. If `--enable-stack-traces` is specified * and `--exclude-sources` is not, this will also include a code dump of * neighboring lines of user code. * * @param error The error to retrieve information about. If a string is * provided, it is first converted to an `Error`. * @version 3.37.0 */ export function mapError(error: Error | string): (Error | string)[]; /** * Calls {@link mapError} and outputs the results to stderr. * * @param error The error to map and log. If a string is provided, it is * first converted to an `Error`. * @version 3.37.0 */ export function mapAndLogError(error: Error | string): void; /** * @version 3.40.0 */ export interface ReusableSandboxOptions { /** * The maximum number of requests to handle with a single sandbox instance * before it is recycled. Default is 1. A value of 0 means no maximum. */ maxRequests?: number; /** * The maximum time in milliseconds to wait for the next request before * recycling the sandbox. Default is up to the platform. */ betweenRequestTimeoutMs?: number; /** * The maximum memory in MiB that the sandbox is allowed to use. If * exceeded, the sandbox will be recycled before the next request. * Default is no limit. */ maxMemoryMiB?: number; /** * The maximum time in milliseconds that a sandbox is allowed to run * before it is recycled after handling the current request. Default is * no timeout. */ sandboxTimeoutMs?: number; } /** * Configure reuse of the same underlying sandbox for multiple requests, * which can improve performance by avoiding the overhead of initializing a * new sandbox for each request. * * **Note**: Can only be used during build-time initialization, not when * processing requests. * * @param options Configuration options for sandbox reuse. * @experimental * @version 3.40.0 */ export function setReusableSandboxOptions( options: ReusableSandboxOptions, ): void; } ================================================ FILE: types/fanout.d.ts ================================================ /// declare module 'fastly:fanout' { /** * Creates a {@link Response} that instructs Fastly to pass the original * request through [Fanout](https://www.fastly.com/documentation/guides/concepts/real-time-messaging/fanout/) * to the declared backend. * * **Note**: Can only be used when processing requests, not during build-time * initialization. * * @example * ```js * import { createFanoutHandoff } from "fastly:fanout"; * * async function handleRequest(event) { * const url = new URL(event.request.url); * if (url.pathname === "/stream") { * return createFanoutHandoff(event.request, "my-backend"); * } * return new Response("Not found", { status: 404 }); * } * * addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); * ``` * * @param request The request to pass through Fanout. * @param backend The name of the backend that Fanout should send the request * to. The name must be between 1 and 254 characters inclusive. * @returns A {@link Response} that can be passed to `event.respondWith`. * @throws `Error` if `request` is not a {@link Request} instance, or * if `backend` is an empty string or longer than 254 characters. */ function createFanoutHandoff(request: Request, backend: string): Response; } ================================================ FILE: types/geolocation.d.ts ================================================ declare module 'fastly:geolocation' { /** * Retrieve geolocation information about the given IP address. * * **Note**: Can only be used when processing requests, not during build-time * initialization. * * @example * ```js * import { getGeolocationForIpAddress } from "fastly:geolocation"; * * async function app(event) { * const ip = * new URL(event.request.url).searchParams.get("ip") || * event.client.address; * const geo = getGeolocationForIpAddress(ip); * return new Response(JSON.stringify(geo), { * headers: { "Content-Type": "application/json" }, * }); * } * * addEventListener("fetch", (event) => event.respondWith(app(event))); * ``` * @fiddle meta * { * "title": "Geolocation Example", * "request": "/status=200" * } * * @param address The IPv4 or IPv6 address to query. * @returns A {@link Geolocation} object, or `null` if no geolocation data is * available for the address. * @throws {Error} If `address` is not a valid IPv4 or IPv6 address. */ function getGeolocationForIpAddress(address: string): Geolocation | null; /** * [Fastly Geolocation](https://developer.fastly.com/reference/vcl/variables/geolocation/) * information about an IP address. * * Can be retrieved for the incoming request's client IP address using the * {@link ClientInfo.geo} accessor, and for arbitrary addresses using * {@link geolocation!getGeolocationForIpAddress | getGeolocationForIpAddress}. */ interface Geolocation { /** * The name of the organization associated with `as_number`. * * For example, fastly is the value given for IP addresses under AS-54113. */ as_name: string | null; /** * [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. */ as_number: number | null; /** * The telephone area code associated with an IP address. * * These are only available for IP addresses in the United States, its territories, and Canada. */ area_code: number | null; /** * City or town name. */ city: string | null; /** * Connection speed. */ conn_speed: string | null; /** * Connection type. */ conn_type: string | null; /** * Continent. */ continent: string | null; /** * A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. * * The US country code is returned for IP addresses associated with overseas United States military bases. * * These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. */ country_code: string | null; /** * A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. * * The USA country code is returned for IP addresses associated with overseas United States military bases. */ country_code3: string | null; /** * Country name. * * This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. */ country_name: string | null; /** * Time zone offset from Greenwich Mean Time (GMT) for `city`. */ gmt_offset: string | null; /** * Latitude, in units of degrees from the equator. * * Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. */ latitude: number | null; /** * Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). * * Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. */ longitude: number | null; /** * Metro code, representing designated market areas (DMAs) in the United States. */ metro_code: number | null; /** * The postal code associated with the IP address. * * These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. * * For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. */ postal_code: string | null; /** * Client proxy description. */ proxy_description: string | null; /** * Client proxy type. */ proxy_type: string | null; /** * [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. * * For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. * * This field can be `null` for countries that do not have ISO country subdivision codes. For example, `null` is given for IP addresses assigned to the Åland Islands (country code AX). */ region: string | null; /** * Time zone offset from coordinated universal time (UTC) for `city`. */ utc_offset: number | null; } } ================================================ FILE: types/globals.d.ts ================================================ /** * @group Web APIs */ declare var self: typeof globalThis; /** * @group DOM Events */ interface EventMap { fetch: FetchEvent; } /** * @group DOM Events */ interface EventListenerMap { fetch: FetchEventListener; } /** * @group DOM Events */ interface FetchEventListener { (this: typeof globalThis, event: FetchEvent): any; } /** * @group DOM Events */ declare var onfetch: FetchEventListener; /** * This is a fetch specific implementation of [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener), and is very similar to [handling FetchEvent from a Service Worker](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/request). * * For Fastly Compute, this will be the entrypoint in handling your downstream request from your client. * @group DOM Events */ declare function addEventListener( type: K, listener: EventListenerMap[K], ): void; /** * @deprecated This has moved to {@link "fastly:backend".BackendConfiguration} - This global variable will be removed in the next major version. * @hidden */ declare interface BackendConfiguration { /** * The name of the backend. * @deprecated to avoid name collisions it is recommended to use auto-generated names by omitting this property. */ name?: string; /** * A hostname, IPv4, or IPv6 address for the backend as well as an optional port. * E.G. "hostname", "ip address", "hostname:port", or "ip address:port" */ target: string; /** * If set, will force the HTTP Host header on connections to this backend to be the supplied value. */ hostOverride?: string; /** * Maximum duration in milliseconds to wait for a connection to this backend to be established. * If exceeded, the connection is aborted and a 503 response will be presented instead. * Defaults to 1,000 milliseconds. */ connectTimeout?: number; /** * Maximum duration in milliseconds to wait for the server response to begin after a TCP connection is established and the request has been sent. * If exceeded, the connection is aborted and a 503 response will be presented instead. * Defaults to 15,000 milliseconds. */ firstByteTimeout?: number; /** * Maximum duration in milliseconds that Fastly will wait while receiving no data on a download from a backend. * If exceeded, the response received so far will be considered complete and the fetch will end. * Defaults to 10,000 milliseconds. */ betweenBytesTimeout?: number; /** * Whether or not to require TLS for connections to this backend. */ useSSL?: boolean; /** * Minimum allowed TLS version on SSL connections to this backend. * If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. */ tlsMinVersion?: number; /** * Maximum allowed TLS version on SSL connections to this backend. * If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. */ tlsMaxVersion?: number; /** * Define the hostname that the server certificate should declare. */ certificateHostname?: string; /** * The CA certificate to use when checking the validity of the backend. */ caCertificate?: string; /** * List of OpenSSL ciphers to support for connections to this origin. * If the backend server is not able to negotiate a connection meeting this constraint, a 503 response will be presented instead. */ ciphers?: string; /** * The SNI hostname to use on connections to this backend. */ sniHostname?: string; /** * @experimental * * When enabled, sets that this backend is to be used for gRPC traffic. * * Warning: When using this experimental feature, no guarantees are provided for behaviours for * backends that do not provide gRPC traffic. */ grpc?: boolean; /** * Set the client certificate to be provided to the server during the initial TLS handshake. * * @throws {TypeError} Throws a TypeError if the value is not an object of the correct type. */ clientCertificate?: { certificate: string; key: import('fastly:secret-store').SecretStoreEntry; }; /** * Enables and sets the HTTP keepalive time in milliseconds for the backend. */ httpKeepalive?: number; /** * Enables and sets the TCP keep alive options for the backend. * Setting to boolean true enables keepalive with the default options. */ tcpKeepalive?: | boolean | { /** * Configure how long to wait after the last sent data over the TCP connection before * starting to send TCP keepalive probes. */ timeSecs?: number; /** * Configure how long to wait between each TCP keepalive probe sent to the backend to determine if it is still active. */ intervalSecs?: number; /** * Number of probes to send to the backend before it is considered dead. */ probes?: number; }; } /** * Class for creating new [Fastly Backends](https://developer.fastly.com/reference/api/services/backend/). * * **Note**: Can only be used when processing requests, not during build-time initialization. * @deprecated This has moved to {@link "fastly:backend".Backend} - This global variable will be removed in the next major version. @hidden */ declare class Backend { /** * Creates a new Backend instance * * @example * Construct a new backend with all properties set to their default values: * ```js * const myBackend = new Backend({ name: 'fastly', target: 'www.fastly.com'}); * ``` */ constructor(configuration: BackendConfiguration); /** * The name of the backend */ readonly name: string; /** * Whether this backend was dynamically created by the running service. */ readonly isDynamic: boolean; /** * The host target for the backend */ readonly target: string; /** * The host header override defined for the backend. * * See https://docs.fastly.com/en/guides/specifying-an-override-host for more information. */ readonly hostOverride: string; /** * The backend port */ readonly port: number; /** * The connect timeout for the backend in milliseconds, if available. */ readonly connectTimeout: number | null; /** * The first byte timeout for the backend in milliseconds, if available. */ readonly firstByteTimeout: number | null; /** * The between bytes timeout for the backend in milliseconds, if available. */ readonly betweenBytesTimeout: number | null; /** * The HTTP keepalive time for the backend in milliseconds. */ readonly httpKeepaliveTime: number; /** * The TCP keepalive configuration, if TCP keepalive is enabled. */ readonly tcpKeepalive: null | { /** * The keepalive time in seconds. */ timeSecs: number; /** * The interval in seconds between probes. */ intervalSecs: number; /** * The number of probes to send before terminating the keepalive. */ probes: number; }; /** * Whether the backend is configured to use SSL. */ readonly isSSL: boolean; /** * The minimum SSL version number this backend will use, if available. */ readonly tlsMinVersion: 1 | 1.1 | 1.2 | 1.3 | null; /** * The maximum SSL version number this backend will use, if available. */ readonly tlsMaxversion: 1 | 1.1 | 1.2 | 1.3 | null; /** * Get the health of this backend. */ health(): 'healthy' | 'unhealthy' | 'unknown'; /** * Returns the name associated with the Backend instance. * @deprecated Use `backend.name` instead. */ toName(): string; /** * Returns the name associated with the Backend instance. * * @deprecated Use `backend.name` instead. */ toString(): string; /** * Returns a boolean indicating if a Backend with the given name exists or not. */ static exists(name: string): boolean; /** * Returns the Backend instance with the given name, if one exists. If one does not exist, an error is thrown. */ static fromName(name: string): Backend; /** * Returns a string representing the health of the given Backend instance. * Possible values are: * * "healthy" - The backend's health check has succeeded, indicating the backend is working as expected and should receive requests. * "unhealthy" - The backend's health check has failed, indicating the backend is not working as expected and should not receive requests. * "unknown" - The backend does not have a health check configured. * * @deprecated Use `backend.health()` ({@link Backend.prototype.health}) instead. */ static health(backend: Backend): 'healthy' | 'unhealthy' | 'unknown'; } /** * A Fastly Compute specific implementation of [FetchEvent](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/FetchEvent). * @group DOM Events */ /** * The event type for `fetch` events dispatched to a Fastly Compute service. * * Contains information about the incoming request, the downstream client, and * the server. Use {@link FetchEvent.respondWith | respondWith} to send a * response back to the client. * * @group DOM Events */ declare interface FetchEvent { /** * Information about the downstream client that made the request. */ readonly client: ClientInfo; /** * Information about the server which received the request. */ readonly server: ServerInfo; /** * The downstream request that came from the client */ readonly request: Request; /** * Send a response back to the client. * * **Note**: The service will be kept alive until the response has been fully sent. * * If the response contains a streaming body created by the service itself, then the service * will be kept alive until the body {@link ReadableStream} has been closed or errored. * * However, if the body is a stream originating in a request to a backend, i.e. if a backend * response's {@link Response.body} is passed as input to the {@link Response} constructor, the * service will not be kept alive until sending the body has finished. * * **Note**: If `response` is a `Promise`, the service will be kept alive until the * response has been resolved or rejected, and the {@link Response} it resolved to has been * fully sent. * * **Note**: Use {@link FetchEvent.waitUntil} to extend the service's lifetime further if * necessary. * * @param response - Response to send back down to the client */ respondWith(response: Response | PromiseLike): void; /** * Send a [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103) * response back to the client. * * Must be called before {@link FetchEvent.respondWith | respondWith}. * * @example * ```js * event.sendEarlyHints({ link: "; rel=preload; as=style" }); * * event.sendEarlyHints([ * ["link", "; rel=preload; as=style"], * ["link", "; rel=preload; as=script"], * ]); * ``` * * @param headers Headers to send back down to the client. * @version 3.36.0 */ sendEarlyHints(headers: HeadersInit): void; /** * Extend the service's lifetime to ensure asynchronous operations succeed. * * By default, a service will shut down as soon as the response passed to * {@link FetchEvent.respondWith | respondWith} has been sent. `waitUntil` can be used to * ensure that the service will stay alive until additional asynchronous operations have * completed, such as sending telemetry data to a separate backend after the response has * been sent. * * Must be initially called synchronously within the event callback, but after that it * can be called multiple times. * * @param promise The `Promise` to wait for. */ waitUntil(promise: Promise): void; } /** * Set the cache override mode on a request * * None * Do not override the behavior specified in the origin response’s cache control headers. * Pass * Do not cache the response to this request, regardless of the origin response’s headers. * Override * Override particular cache control settings using a {@linkcode CacheOverride} object. * * The origin response’s cache control headers will be used for ttl and stale_while_revalidate if None. * * @deprecated This has moved to {@link "fastly:cache-override".CacheOverrideMode} - This global type will be removed in the next major version. * @hidden */ declare type CacheOverrideMode = 'none' | 'pass' | 'override'; /** * Base class for Cache Override, which is used to configure caching behavior. * @deprecated This has moved to {@link "fastly:cache-override".CacheOverrideInit} - This global interface will be removed in the next major version. * @hidden */ declare interface CacheOverrideInit { /** * Override the caching behavior of this request to use the given Time to Live (TTL), in seconds. */ ttl?: number; /** * Override the caching behavior of this request to use the given `stale-while-revalidate` time, * in seconds */ swr?: number; /** * Override the caching behavior of this request to include the given surrogate key, provided as * a header value. * * See the [Fastly surrogate keys guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) * for details. */ surrogateKey?: string; /** * Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant * non-volatile caching. * * By default, this is false, which means the request may not be PCI/HIPAA-compliant. Set it to * true to enable compliant caching. * * See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) * for details. */ pci?: boolean; } /** * Configures the caching behavior of a {@linkcode Response}. * * Normally, the HTTP Headers on a Response would control how the Response is cached, * but CacheOverride can be set on a {@linkcode Request}, to define custom caching behavior. * * @deprecated This has moved to {@link "fastly:cache-override".CacheOverride} - This global interface will be removed in the next major version. * @hidden */ declare interface CacheOverride extends CacheOverrideInit { mode: CacheOverrideMode; } /** * @deprecated This has moved to {@link "fastly:cache-override".CacheOverride} - This global variable will be removed in the next major version. * @hidden */ declare var CacheOverride: { prototype: CacheOverride; new (mode: CacheOverrideMode, init?: CacheOverrideInit): CacheOverride; }; /** * Information about the downstream client making the request to the Fastly Compute service. */ declare interface ClientInfo { /** * A UUID generated by Fastly Compute for each request. * @version 3.40.1 */ readonly requestId: string; /** * A string representation of the IPv4 or IPv6 address of the downstream client. */ readonly address: string; /** * Geolocation data for the client IP address, or `null` if unavailable. */ readonly geo: import('fastly:geolocation').Geolocation | null; /** * The JA3 hash of the TLS ClientHello message, or `null` if unavailable. * @version 3.2.1 */ readonly tlsJA3MD5: string | null; /** * The JA4 fingerprint of the TLS ClientHello message, or `null` if unavailable. * @version 3.37.0 */ readonly tlsJA4: string | null; /** * The HTTP/2 fingerprint for HTTP/2 connections, or `null` for HTTP/1.1 * connections or when unavailable. * @version 3.37.0 */ readonly h2Fingerprint: string | null; /** * The Original Header fingerprint based on the order and presence of request * headers, or `null` if unavailable. * @version 3.37.0 */ readonly ohFingerprint: string | null; /** * The cipher suite used to secure the client TLS connection, or `null` if * unavailable. * @version 3.2.1 */ readonly tlsCipherOpensslName: string | null; /** * The TLS protocol version used to secure the client TLS connection, or * `null` if unavailable. * @version 3.2.1 */ readonly tlsProtocol: string | null; /** * The raw client certificate from the mutual TLS handshake in PEM format, * or `null` if unavailable. Returns an empty `ArrayBuffer` if the connection * is not mTLS. * @version 3.2.1 */ readonly tlsClientCertificate: ArrayBuffer | null; /** * The raw bytes sent by the client in the TLS ClientHello message, or * `null` if unavailable. * @version 3.2.1 */ readonly tlsClientHello: ArrayBuffer | null; } /** * Information about the server receiving the request for the Fastly Compute service. */ declare interface ServerInfo { /** * A string representation of the IPv4 or IPv6 address of the server which received the request. */ readonly address: string; } /** * Class for accessing [Fastly Edge Dictionaries](https://docs.fastly.com/en/guides/about-edge-dictionaries). * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @deprecated This has moved to {@link "fastly:config-store".ConfigStore} - This global class will be removed in the next major version. * @hidden */ declare class ConfigStore { /** * Creates a new ConfigStore object */ constructor(name: string); /** * Get a value for a key in the config-store. */ get(key: string): string; } /** * Class for accessing [Fastly Edge Dictionaries](https://docs.fastly.com/en/guides/about-edge-dictionaries). * * **Note**: Can only be used when processing requests, not during build-time initialization. * @deprecated This has moved to {@link "fastly:dictionary".Dictionary} - This global class will be removed in the next major version. * @hidden */ declare class Dictionary { /** * Creates a new Dictionary object, and opens an edge dictionary to query */ constructor(name: string); /** * Get a value for a key in the dictionary */ get(key: string): string; } /** * [Fastly Geolocation](https://developer.fastly.com/reference/vcl/variables/geolocation/) * information about an IP address * * Can be retrieved for the incoming request's client IP address using the * {@linkcode ClientInfo#geo} accessor, and for arbitrary addresses using * {@linkcode Fastly.getGeolocationForIpAddress}. * @deprecated This has moved to {@link "fastly:geolocation".Geolocation} - This global interface will be removed in the next major version. * @hidden */ declare interface Geolocation { /** * The name of the organization associated with as_number. * * For example, fastly is the value given for IP addresses under AS-54113. */ as_name: string | null; /** * [Autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS) number. */ as_number: number | null; /** * The telephone area code associated with an IP address. * * These are only available for IP addresses in the United States, its territories, and Canada. */ area_code: number | null; /** * City or town name. */ city: string | null; /** * Connection speed. */ conn_speed: string | null; /** * Connection type. */ conn_type: string | null; /** * Continent. */ continent: string | null; /** * A two-character [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country code for the country associated with an IP address. * * The US country code is returned for IP addresses associated with overseas United States military bases. * * These values include subdivisions that are assigned their own country codes in ISO 3166-1. For example, subdivisions NO-21 and NO-22 are presented with the country code SJ for Svalbard and the Jan Mayen Islands. */ country_code: string | null; /** * A three-character [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) country code for the country associated with the IP address. * * The USA country code is returned for IP addresses associated with overseas United States military bases. */ country_code3: string | null; /** * Country name. * * This field is the [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) English short name for a country. */ country_name: string | null; /** * Time zone offset from Greenwich Mean Time (GMT) for `city`. */ gmt_offset: string | null; /** * Latitude, in units of degrees from the equator. * * Values range from -90.0 to +90.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. */ latitude: number | null; /** * Longitude, in units of degrees from the [IERS Reference Meridian](https://en.wikipedia.org/wiki/IERS_Reference_Meridian). * * Values range from -180.0 to +180.0 inclusive, and are based on the [WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System) coordinate reference system. */ longitude: number | null; /** * Metro code, representing designated market areas (DMAs) in the United States. */ metro_code: number | null; /** * The postal code associated with the IP address. * * These are available for some IP addresses in Australia, Canada, France, Germany, Italy, Spain, Switzerland, the United Kingdom, and the United States. * * For Canadian postal codes, this is the first 3 characters. For the United Kingdom, this is the first 2-4 characters (outward code). For countries with alphanumeric postal codes, this field is a lowercase transliteration. */ postal_code: string | null; /** * Client proxy description. */ proxy_description: string | null; /** * Client proxy type. */ proxy_type: string | null; /** * [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) country subdivision code. * * For countries with multiple levels of subdivision (for example, nations within the United Kingdom), this variable gives the more specific subdivision. * * This field can be None for countries that do not have ISO country subdivision codes. For example, None is given for IP addresses assigned to the Åland Islands (country code AX, illustrated below). */ region: string | null; /** * Time zone offset from coordinated universal time (UTC) for `city`. */ utc_offset: number | null; } /** * Class for accessing a [Fastly KV Store](https://developer.fastly.com/reference/api/kv-store/). * * A KV Store is a persistent, globally consistent key-value store. * * **Note**: Can only be used when processing requests, not during build-time initialization. * @deprecated This has moved to {@link "fastly:kv-store".KVStore} - This global class will be removed in the next major version. * @hidden */ declare class KVStore { /** * Creates a new JavaScript KVStore object which interacts with the Fastly KV Store named `name`. * * @param name Name of the Fastly KV Store to interact with. A name cannot be empty, contain Control characters, or be longer than 255 characters. */ constructor(name: string); /** * Gets the value associated with the key `key` in the KV Store. * When the key is present, a resolved Promise containing an KVStoreEntry will be returned which contains the associated value. * When the key is absent, a resolved Promise containing null is returned. * @param key The key to retrieve from within the KV Store. A key cannot: * - Be any of the strings "", ".", or ".." * - Start with the string ".well-known/acme-challenge/"" * - Contain any of the characters "#;?^|\n\r" * - Be longer than 1024 characters */ get(key: string): Promise; /** * Write the value of `value` into the KV Store under the key `key`. * * Note: KV Store is eventually consistent, this means that the updated contents associated with the key `key` may not be available to read from all * edge locations immediately and some edge locations may continue returning the previous contents associated with the key. * * @param key The key to associate with the value. A key cannot: * - Be any of the strings "", ".", or ".." * - Start with the string ".well-known/acme-challenge/"" * - Contain any of the characters "#;?^|\n\r" * - Be longer than 1024 characters * @param value The value to store within the KV Store. */ put(key: string, value: BodyInit): Promise; } /** * Class for interacting with a [Fastly KV Store](https://developer.fastly.com/reference/api/kv-store/) entry. * * @deprecated This has moved to {@link "fastly:kv-store".KVStoreEntry} - This global interface will be removed in the next major version. * @hidden */ declare interface KVStoreEntry { /** * A ReadableStream with the contents of the entry. */ get body(): ReadableStream; /** * A boolean value that indicates whether the body has been read from already. */ get bodyUsed(): boolean; /** * Reads the body and returns it as a promise that resolves with a string. * The response is always decoded using UTF-8. */ text(): Promise; /** * Reads the body and returns it as a promise that resolves with the result of parsing the body text as JSON. */ json(): Promise; /** * Reads the body and returns it as a promise that resolves with an ArrayBuffer. */ arrayBuffer(): Promise; // And eventually formData and blob once we support them on Request and Response, too. } /** * The URL class as [specified by WHATWG](https://url.spec.whatwg.org/#url-class) * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL | URL on MDN} * @group Web APIs */ declare class URL { constructor(url: string, base?: string | URL); get href(): string; set href(V: string); get origin(): string; get protocol(): string; set protocol(V: string); get username(): string; set username(V: string); get password(): string; set password(V: string); get host(): string; set host(V: string); get hostname(): string; set hostname(V: string); get port(): string; set port(V: string); get pathname(): string; set pathname(V: string); get search(): string; set search(V: string); get searchParams(): URLSearchParams; get hash(): string; set hash(V: string); toJSON(): string; readonly [Symbol.toStringTag]: 'URL'; } /** * The URLSearchParams class as [specified by WHATWG](https://url.spec.whatwg.org/#interface-urlsearchparams) * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams | URLSearchParams on MDN} * @group Web APIs */ declare class URLSearchParams { constructor( init?: | ReadonlyArray | Iterable | { readonly [name: string]: string } | string, ); append(name: string, value: string): void; delete(name: string): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; set(name: string, value: string): void; sort(): void; keys(): IterableIterator; values(): IterableIterator; entries(): IterableIterator<[name: string, value: string]>; forEach( callback: ( this: THIS_ARG, value: string, name: string, searchParams: this, ) => void, thisArg?: THIS_ARG, ): void; readonly [Symbol.toStringTag]: 'URLSearchParams'; [Symbol.iterator](): IterableIterator<[name: string, value: string]>; } /** * Interface for logging to stdout for * [live log monitoring](https://developer.fastly.com/learning/compute/testing/#live-log-monitoring-in-your-console). * * **Note**: This implementation accepts any number of arguments. String representations of each object are appended * together in the order listed and output. Unlike the `Console` built-in in browsers and Node.js, this implementation * does not perform string substitution. * * **Note**: Messages are prefixed with the respective log level, starting with an upper-case letter, e.g. `"Log: "`. * @group Console API */ interface Console { assert(condition?: boolean, ...data: any[]): void; clear(): void; count(label?: string): void; countReset(label?: string): void; debug(...data: any[]): void; dir(item?: any, options?: any): void; dirxml(...data: any[]): void; error(...data: any[]): void; group(...data: any[]): void; groupCollapsed(...data: any[]): void; groupEnd(): void; info(...data: any[]): void; log(...data: any[]): void; table(tabularData?: any, properties?: string[]): void; time(label?: string): void; timeEnd(label?: string): void; timeLog(label?: string, ...data: any[]): void; trace(...data: any[]): void; warn(...data: any[]): void; } /** * The global {@linkcode Console} instance * @group Console API */ declare var console: Console; /** * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All * instances of `TextEncoder` only support UTF-8 encoding. * * TextEncoder takes a stream of code points as input and emits a stream of UTF-8 bytes. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder | TextEncoder on MDN} * @example * ```js * const encoder = new TextEncoder(); * const uint8array = encoder.encode('a string to encode'); * ``` * @group Encoding API */ declare class TextEncoder { /** * Returns a newly constructed TextEncoder that will generate a byte stream with UTF-8 encoding. */ constructor(); /** * The TextEncoder.encoding read-only property returns a string containing the name of the encoding algorithm used by the specific encoder. * It is always set to the value "utf-8". */ readonly encoding: 'utf-8'; /** * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the encoded bytes. * @param [input='an empty string'] The text to encode. */ encode(input?: string): Uint8Array; // /** // * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object // * containing the read Unicode code units and written UTF-8 bytes. // * // * ```js // * const encoder = new TextEncoder(); // * const src = 'this is some data'; // * const dest = new Uint8Array(10); // * const { read, written } = encoder.encodeInto(src, dest); // * ``` // * @param src The text to encode. // * @param dest The array to hold the encode result. // */ // encodeInto(src: string, dest: Uint8Array): TextEncoderEncodeIntoResult; } // https://encoding.spec.whatwg.org/#dictdef-textencoderencodeintoresult // declare interface TextEncoderEncodeIntoResult { // read: number; // written: number; // } /** * TextDecoder takes a stream UTF-8 bytes as input and emits a stream of code points * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder | TextDecoder on MDN} * * **Note**: On Fastly Compute, TextDecoder only supports UTF-8 bytes as input, and always operates * in non-fatal mode. * @group Encoding API */ declare class TextDecoder { // TODO: We should throw a RangeError if supplied a `label` that we do not support constructor(label?: 'unicode-1-1-utf-8' | 'utf-8' | 'utf8'); decode(input?: ArrayBuffer | ArrayBufferView): string; get encoding(): 'utf-8'; } /** * Simple interface for logging to * [third party logging providers](https://developer.fastly.com/learning/integrations/logging) * * Instances of Logger for specific endpoints can be created using {@linkcode Fastly.getLogger}. * @deprecated This has moved to {@link "fastly:logger".Logger} - This global class will be removed in the next major version. * @hidden */ declare interface Logger { /** * Send the given message, converted to a string, to this Logger instance's endpoint */ log(message: any): void; } /** * Fastly-specific APIs available to Fastly Compute JS services * @deprecated * @hidden */ declare interface Fastly { /** * @deprecated This has moved to {@link "fastly:experimental".setBaseURL} - This will be removed in the next major version. * @hidden * @experimental */ set baseURL(base: URL | null | undefined); /** * @deprecated This will be removed in the next major version. * @hidden * @experimental */ get baseURL(): URL | null; /** * @deprecated This has moved to {@link "fastly:experimental".setDefaultBackend} - This will be removed in the next major version. * @hidden * @experimental */ set defaultBackend(backend: string); /** * @deprecated This will be removed in the next major version. * @hidden * @experimental */ get defaultBackend(): string; /** * Property to access the environment variables for the Fastly Compute service. * @hidden * @experimental */ env: { /** * Function to get the environment variable value, for the provided environment variable name. * * For additional references, see the [Fastly Developer Hub for Compute Environment Variables](https://developer.fastly.com/reference/compute/ecp-env/) * * @param name The name of the environment variable * @returns the value of the environemnt variable * @deprecated This has moved to {@link "fastly:env".env} - This function will be removed in the next major version. * @hidden */ get(name: string): string; }; /** * JavaScript SDK version string for the JS runtime build. * @hidden */ sdkVersion: string; /** * Creates a new {@linkcode Logger} instance for the given * [named log endpoint](https://developer.fastly.com/learning/integrations/logging). * * **Note**: Can only be used when processing requests, not during build-time initialization. * @deprecated This function will be removed in the next major version. Use of this function can be replaced with the fastly logger class {@link "fastly:logger".Logger} * @hidden */ getLogger(endpoint: string): Logger; /** * Causes the Fastly Compute JS runtime environment to log debug information to stdout. * * **Note**: This is mostly for internal debugging purposes and will generate highly unstable * output. * * @deprecated This has moved to {@link "fastly:experimental".enableDebugLogging} - This function will be removed in the next major version. * @hidden * @experimental */ enableDebugLogging(enabled: boolean): void; /** * Retrieve geolocation information about the given IP address. * * @param address - the IPv4 or IPv6 address to query * * **Note**: Can only be used when processing requests, not during build-time initialization. * @deprecated This has moved to {@link "fastly:geolocation".getGeolocationForIpAddress} - This function will be removed in the next major version. * @hidden */ getGeolocationForIpAddress( address: string, ): import('fastly:geolocation').Geolocation; /** * Embed a file as a Uint8Array. * * @param path - The path to include, relative to the project's top-level directory * * **Note**: Can only be used during build-time initialization, not when processing requests. * * @deprecated This has moved to {@link "fastly:experimental".includeBytes} - This function will be removed in the next major version. * @hidden * @experimental */ includeBytes(path: string): Uint8Array; } /** * The global instance of the {@linkcode Fastly} builtin * @deprecated * @hidden */ declare var fastly: Fastly; /** * An API for compressing a stream of data. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream | CompressionStream on MDN} * * @example * In this example a request is made to httpbin.org/html and the response body is compressed using gzip compression. * * View this example on [Fiddle](https://fiddle.fastly.dev/fiddle/c1326776). * * ```js * async function app(event) { * const req = event.request; * const backendResponse = await fetch("https://httpbin.org/html", { backend: "my-backend" }); * if (!backendResponse.body) { * return backendResponse; * } * let resp = new Response(backendResponse.body.pipeThrough(new CompressionStream("gzip")), backendResponse); * resp.headers.set("Content-Encoding", "gzip"); * return resp; * } * addEventListener("fetch", event => event.respondWith(app(event))); * ``` * * @group Compression Streams APIs */ declare class CompressionStream { /** * Creates a new `CompressionStream` object which compresses a stream of data. * * @param format The compression format to use. * * @throws Throws a `TypeError` if the format passed to the constructor is not supported. * @example * ```js * const gzip = new CompressionStream("gzip"); * ``` */ constructor(format: 'deflate' | 'deflate-raw' | 'gzip'); /** * @example * ```js * let stream = new CompressionStream("gzip"); * console.log(stream.readable instanceof ReadableStream); // true * ``` */ readonly readable: ReadableStream>; /** * @example * ```js * let stream = new CompressionStream("gzip"); * console.log(stream.writable instanceof WritableStream); // true * ``` */ readonly writable: WritableStream>; } /** * An API for decompressing a stream of data. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DecompressionStream | DecompressionStream on MDN} * * @example * In this example a request is made to httpbin.org/gzip and the response body is decompressed using gzip decompression. * * View this example on [Fiddle](https://fiddle.fastly.dev/fiddle/637add51). * * ```js * async function app(event) { * const backendResponse = await fetch("https://httpbin.org/gzip", { backend: "origin_0" }); * let resp = new Response(backendResponse.body.pipeThrough(new DecompressionStream("gzip")), backendResponse); * resp.headers.delete('content-encoding'); * return resp; * } * addEventListener("fetch", event => event.respondWith(app(event))); * ``` * * @group Compression Streams APIs */ declare class DecompressionStream { /** * Creates a new `DecompressionStream` object which decompresses a stream of * data. * * @param format The compression format to use. * * @throws Throws a `TypeError` if the format passed to the constructor is not supported. * @example * ```js * const gzip = new DecompressionStream("gzip"); * ``` */ constructor(format: 'deflate' | 'deflate-raw' | 'gzip'); /** * @example * ```js * let stream = new DecompressionStream("gzip"); * console.log(stream.readable instanceof ReadableStream); // true * ``` */ readonly readable: ReadableStream>; /** * @example * ```js * let stream = new DecompressionStream("gzip"); * console.log(stream.writable instanceof WritableStream); // true * ``` */ readonly writable: WritableStream>; } // Note: the contents below here are, partially modified, copies of content from TypeScript's // `lib.dom.d.ts` file. // We used to keep them in a separate file, referenced using a `/// reference path="..."` // directive, but that causes the defined types to be absent from TypeDoc output. /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /*! * This file is largely a subset of TypeScript's lib.dom.d.ts file, with some * Fastly Compute-specific additions and modifications. Those modifications are * Copyright (c) Fastly Corporation, under the same license as the rest of the file. */ type BlobPart = BufferSource | Blob | string; type EndingType = 'native' | 'transparent'; type FormDataEntryValue = File | string; interface BlobPropertyBag { endings?: EndingType; type?: string; } interface FilePropertyBag extends BlobPropertyBag { lastModified?: number; } /** * A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) */ interface Blob { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ readonly size: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ readonly type: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ arrayBuffer(): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ slice(start?: number, end?: number, contentType?: string): Blob; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ stream(): ReadableStream>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ text(): Promise; } declare var Blob: { prototype: Blob; new (blobParts?: BlobPart[], options?: BlobPropertyBag): Blob; }; /** * Provides information about files and allows JavaScript in a web page to access their content. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) */ interface File extends Blob { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ readonly lastModified: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ readonly name: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/webkitRelativePath) */ readonly webkitRelativePath: string; } declare var File: { prototype: File; new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File; }; /** * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) */ interface FormData { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ append(name: string, value: string | Blob): void; append(name: string, value: string): void; append(name: string, blobValue: Blob, filename?: string): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) */ delete(name: string): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) */ get(name: string): FormDataEntryValue | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) */ getAll(name: string): FormDataEntryValue[]; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ has(name: string): boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ set(name: string, value: string | Blob): void; set(name: string, value: string): void; set(name: string, blobValue: Blob, filename?: string): void; forEach( callbackfn: ( value: FormDataEntryValue, key: string, parent: FormData, ) => void, thisArg?: any, ): void; } declare var FormData: { prototype: FormData; new ( form?: any /*form?: HTMLFormElement, submitter?: HTMLElement | null*/, ): FormData; }; /** * Used within the * [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) and * [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response) constructors. * ({@linkcode Request}, and {@linkcode Response}) * @group Fetch API */ declare type BodyInit = ReadableStream | XMLHttpRequestBodyInit; declare type XMLHttpRequestBodyInit = | Blob | BufferSource | FormData | URLSearchParams | string; /** * Body for Fetch HTTP Requests and Responses * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Body | Body on MDN} * @group Fetch API */ declare interface Body { readonly body: ReadableStream> | null; readonly bodyUsed: boolean; arrayBuffer(): Promise; blob(): Promise; formData(): Promise; json(): Promise; text(): Promise; } /** * Constructor parameter for * [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) * * Usually this a URL to the resource you are requesting. * @group Fetch API */ declare type RequestInfo = Request | string; /** * Constructor parameter for * [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) * * This contains information to send along with the request (Headers, body, etc...), as well as * Fastly specific information. * @group Fetch API */ declare interface RequestInit { /** A BodyInit object or null to set request's body. */ body?: BodyInit | null; // /** A string indicating how the request will interact with the browser's cache to set request's cache. */ // cache?: RequestCache; // /** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */ // credentials?: RequestCredentials; /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ headers?: HeadersInit; // /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ // integrity?: string; // /** A boolean to set request's keepalive. */ // keepalive?: boolean; /** A string to set request's method. */ method?: string; // /** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */ // mode?: RequestMode; // /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ // redirect?: RequestRedirect; // /** A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. */ // referrer?: string; // /** A referrer policy to set request's referrerPolicy. */ // referrerPolicy?: ReferrerPolicy; // /** An AbortSignal to set request's signal. */ // signal?: AbortSignal | null; // /** Can only be null. Used to disassociate request from any Window. */ // window?: null; /** The Fastly configured backend name or instance the request should be sent to. */ backend?: string | import('fastly:backend').Backend; /** Fastly-specific cache override configuration for this request. */ cacheOverride?: | import('fastly:cache-override').CacheOverride | import('fastly:cache-override').ICacheOverride | Exclude; /** Fastly-specific cache key override for this request. */ cacheKey?: string; /** Fastly-specific options. */ fastly?: { /** Whether to automatically gzip decompress the response. */ decompressGzip?: boolean; }; /** * Controls how framing headers (`Content-Length`, `Transfer-Encoding`) are * determined. When `true`, any provided framing headers will be honored * instead of being automatically set based on the body. */ manualFramingHeaders?: boolean; /** * Fastly Image Optimizer transformation options to apply to the response. * @version 3.36.0 */ imageOptimizerOptions?: import('fastly:image-optimizer').ImageOptimizerOptions; } /** * The Request class as [specified by WHATWG](https://fetch.spec.whatwg.org/#ref-for-dom-request%E2%91%A0) * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request | Request on MDN} * @group Fetch API */ interface Request extends Body { // /** Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching. */ // readonly cache: RequestCache; // /** Returns the credentials mode associated with request, which is a string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. */ // readonly credentials: RequestCredentials; // /** Returns the kind of resource requested by request, e.g., "document" or "script". */ // readonly destination: RequestDestination; /** Returns a Headers object consisting of the headers associated with request. */ readonly headers: Headers; // /** Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] */ // readonly integrity: string; // /** Returns a boolean indicating whether or not request can outlive the global in which it was created. */ // readonly keepalive: boolean; /** Returns request's HTTP method, which is "GET" by default. */ readonly method: string; // /** Returns the mode associated with request, which is a string indicating whether the request will use CORS, or will be restricted to same-origin URLs. */ // readonly mode: RequestMode; // /** Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. */ // readonly redirect: RequestRedirect; // /** Returns the referrer of request. Its value can be a same-origin URL if explicitly set in init, the empty string to indicate no referrer, and "about:client" when defaulting to the global's default. This is used during fetching to determine the value of the `Referer` header of the request being made. */ // readonly referrer: string; // /** Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer. */ // readonly referrerPolicy: ReferrerPolicy; // /** Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. */ // readonly signal: AbortSignal; /** Returns the URL of request as a string. */ readonly url: string; /** Creates a copy of the current Request object. */ clone(): Request; /** * The backend this request was sent to, or `undefined` for the downstream * request itself. */ readonly backend: import('fastly:backend').Backend | undefined; /** * Set the cache override for this request. * * @param override The cache override configuration to apply. */ setCacheOverride( override: import('fastly:cache-override').CacheOverride, ): void; /** * Set a custom cache key for this request. * * @param key The cache key to use. */ setCacheKey(key: string): void; /** * Controls how framing headers (`Content-Length`, `Transfer-Encoding`) are * determined. In "manual" mode, any provided framing headers will be * honored. In "automatic" mode (the default), they are set based on the * body. * * @param manual Whether to use manual mode for framing headers. */ setManualFramingHeaders(manual: boolean): void; /** * Fastly-specific property - determines whether a request is cacheable per conservative RFC 9111 semantics. * In particular, this function checks whether the request method is `GET` or `HEAD`, and * considers requests with other methods uncacheable. Applications where it is safe to cache * responses to other methods should consider using their own cacheability check instead of * this function. * * This function always returns undefined on hosts not supporting the HTTP Cache API (i.e. Viceroy) * @version 3.30.0 */ readonly isCacheable: boolean | undefined; } /** * @group Fetch API */ declare var Request: { prototype: Request; new (input: RequestInfo | URL, init?: RequestInit): Request; }; /** * Constructor parameter for the [Fetch API Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) * This contains information to send along with the response. * @group Fetch API */ declare interface ResponseInit { headers?: HeadersInit; status?: number; statusText?: string; /** * Controls how framing headers (`Content-Length`, `Transfer-Encoding`) are * determined. When `true`, any provided framing headers will be honored * instead of being automatically set based on the body. */ manualFramingHeaders?: boolean; } /** * The Response class as [specified by WHATWG](https://fetch.spec.whatwg.org/#ref-for-dom-response%E2%91%A0) * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response | Response on MDN} * @group Fetch API */ interface Response extends Body { /** * The response headers. * * May be modified even for upstream responses prior to storage in the cache. */ readonly headers: Headers; readonly ok: boolean; // readonly redirected: boolean; /** * The response status. May be modified prior to storage in the cache. */ status: number; readonly statusText: string; // readonly type: ResponseType; readonly url: string; /** * Fastly-specific property - obtain the IP address used for the request * * Undefined for user-created responses and when the response is returned from the cache. * Set cacheOverride: new CacheOverride("pass") to ensure a value. */ readonly ip: string | undefined; /** * Fastly-specific property - Obtain the port used for the request * * Undefined for user-created responses and when the response is returned from the cache. * Set cacheOverride: new CacheOverride("pass") to ensure a value. */ readonly port: number | undefined; // clone(): Response; /** * Controls how framing headers (`Content-Length`, `Transfer-Encoding`) are * determined. In "manual" mode, any provided framing headers will be * honored. In "automatic" mode (the default), they are set based on the * body. * * @param manual Whether to use manual mode for framing headers. */ setManualFramingHeaders(manual: boolean): void; /** * The backend this response was received from, or `undefined` for * user-created responses. */ readonly backend: import('fastly:backend').Backend | undefined; /** * Fastly-specific property - Returns whether the `Response` resulted from a cache hit. * For request collapsing, typically one response will show as a miss, and the others * (that awaited that response) will show as hits. * * Undefined if the environment does not support the new HTTP Cache hostcalls. * @version 3.30.0 */ readonly cached: boolean | undefined; /** * Fastly-specific property - Returns whether the cached `Response` is considered stale. * * Undefined if the environment does not support the new HTTP Cache hostcalls. * @version 3.30.0 */ readonly stale: boolean | undefined; /** * Fastly-specific property - Get the Time to Live (TTL) in the cache for this response in seconds, if it is cached. * * The TTL determines the duration of "freshness" for the cached response * after it is inserted into the cache. * * Undefined if the response is not cached or the environment does not support the HTTP Cache hostcalls. May be modified prior to injection into the cache. * @version 3.30.0 */ ttl: number | undefined; /** * Fastly-specific property - The current age of the response in seconds, if it is cached. * * Undefined if the response is not cached or the environment does not support the HTTP Cache hostcalls. May be modified prior to injection into the cache. * @version 3.30.0 */ readonly age: number | undefined; /** * Fastly-specific property - The time in seconds for which the response can safely be used despite being considered stale, if it is cached. * * Undefined if the response is not cached or the environment does not support the HTTP Cache hostcalls. May be modified prior to injection into the cache. * @version 3.30.0 */ swr: number | undefined; /** * Fastly-specific property - The set of request headers for which the response may vary. * * Undefined if the response is not cached or the environment does not support the HTTP Cache hostcalls. May be modified prior to injection into the cache. * @version 3.30.0 */ vary: Array | undefined; /** * Fastly-specific property - The surrogate keys for the cached response. * * Undefined if the response is not cached or the environment does not support the HTTP Cache hostcalls. May be modified prior to injection into the cache. * @version 3.30.0 */ surrogateKeys: Array | undefined; /** * Fastly-specific property - Get or set whether this response should only be stored via PCI/HIPAA-compliant non-volatile caching. * * See the [Fastly PCI-Compliant Caching and Delivery documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) * for details. * * Undefined if the response is not cached or the environment does not support the HTTP Cache hostcalls. May be modified prior to injection into the cache. * @version 3.30.0 */ pci: boolean | undefined; } /** * @group Fetch API */ declare var Response: { prototype: Response; new (body?: BodyInit | null, init?: ResponseInit): Response; // error(): Response; redirect(url: string | URL, status?: number): Response; json(data: any, init?: ResponseInit): Response; }; /** * @group Streams API */ type ReadableStreamReader = ReadableStreamDefaultReader; // type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; /** * @group Streams API */ type ReadableStreamController = ReadableStreamDefaultController; // type ReadableStreamController = ReadableStreamDefaultController | ReadableByteStreamController; /** * @group Streams API */ interface UnderlyingSinkAbortCallback { (reason?: any): void | PromiseLike; } /** * @group Streams API */ interface UnderlyingSinkCloseCallback { (): void | PromiseLike; } /** * @group Streams API */ interface UnderlyingSinkStartCallback { (controller: WritableStreamDefaultController): any; } /** * @group Streams API */ interface UnderlyingSinkWriteCallback { ( chunk: W, controller: WritableStreamDefaultController, ): void | PromiseLike; } /** * @group Streams API */ interface UnderlyingSourceCancelCallback { (reason?: any): void | PromiseLike; } /** * @group Streams API */ interface UnderlyingSourcePullCallback { (controller: ReadableStreamController): void | PromiseLike; } /** * @group Streams API */ interface UnderlyingSourceStartCallback { (controller: ReadableStreamController): any; } /** * @group Streams API */ interface UnderlyingSink { abort?: UnderlyingSinkAbortCallback; close?: UnderlyingSinkCloseCallback; start?: UnderlyingSinkStartCallback; type?: undefined; write?: UnderlyingSinkWriteCallback; } /** * @group Streams API */ interface UnderlyingSource { autoAllocateChunkSize?: number; cancel?: UnderlyingSourceCancelCallback; pull?: UnderlyingSourcePullCallback; start?: UnderlyingSourceStartCallback; type?: ReadableStreamType; } /** * @group Streams API */ type ReadableStreamType = 'bytes'; /** * @group Streams API */ interface StreamPipeOptions { preventAbort?: boolean; preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. * * Errors and closures of the source and destination streams propagate as follows: * * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. * * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. * * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. * * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. * * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; // signal?: AbortSignal; } /** * @group Streams API */ interface QueuingStrategySize { (chunk: T): number; } /** * @group Streams API */ interface QueuingStrategy { highWaterMark?: number; size?: QueuingStrategySize; } /** * @group Streams API */ interface QueuingStrategyInit { /** * Creates a new ByteLengthQueuingStrategy with the provided high water mark. * * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. */ highWaterMark: number; } /** * @group Streams API */ interface ReadableStreamDefaultReadDoneResult { done: true; value?: undefined; } /** * @group Streams API */ interface ReadableStreamDefaultReadValueResult { done: false; value: T; } /** * @group Streams API */ type ReadableStreamDefaultReadResult = | ReadableStreamDefaultReadValueResult | ReadableStreamDefaultReadDoneResult; /** * @group Streams API */ interface ReadableWritablePair { readable: ReadableStream; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other \{ writable, readable \} pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream; } /** * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. * @group Streams API */ interface ReadableStream { readonly locked: boolean; cancel(reason?: any): Promise; getReader(): ReadableStreamDefaultReader; pipeThrough( transform: ReadableWritablePair, options?: StreamPipeOptions, ): ReadableStream; pipeTo(dest: WritableStream, options?: StreamPipeOptions): Promise; tee(): [ReadableStream, ReadableStream]; } /** * The ReadableStream class as [specified by WHATWG](https://streams.spec.whatwg.org/#rs-class) * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream | ReadableStream on MDN} * @group Streams API */ declare var ReadableStream: { prototype: ReadableStream; new ( underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy, ): ReadableStream; }; /** * @group Streams API */ interface ReadableStreamDefaultController { readonly desiredSize: number | null; close(): void; enqueue(chunk: R): void; error(e?: any): void; } /** * @group Streams API */ declare var ReadableStreamDefaultController: { prototype: ReadableStreamDefaultController; new (): ReadableStreamDefaultController; }; /** * @group Streams API */ interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { read(): Promise>; releaseLock(): void; } /** * @group Streams API */ declare var ReadableStreamDefaultReader: { prototype: ReadableStreamDefaultReader; new (stream: ReadableStream): ReadableStreamDefaultReader; }; /** * @group Streams API */ interface ReadableStreamGenericReader { readonly closed: Promise; cancel(reason?: any): Promise; } /** * This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. * @group Streams API */ interface WritableStream { readonly locked: boolean; abort(reason?: any): Promise; getWriter(): WritableStreamDefaultWriter; } /** * The WritableStream class as [specified by WHATWG](https://streams.spec.whatwg.org/#ws-class) * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WritableStream | WritableStream on MDN} * @group Streams API */ declare var WritableStream: { prototype: WritableStream; new ( underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy, ): WritableStream; }; /** * This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. * @group Streams API */ interface WritableStreamDefaultController { error(e?: any): void; } /** * @group Streams API */ declare var WritableStreamDefaultController: { prototype: WritableStreamDefaultController; new (): WritableStreamDefaultController; }; /** * This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink. * @group Streams API */ interface WritableStreamDefaultWriter { readonly closed: Promise; readonly desiredSize: number | null; readonly ready: Promise; abort(reason?: any): Promise; close(): Promise; releaseLock(): void; write(chunk: W): Promise; } /** * @group Streams API */ declare var WritableStreamDefaultWriter: { prototype: WritableStreamDefaultWriter; new (stream: WritableStream): WritableStreamDefaultWriter; }; /** * @group Streams API */ interface TransformStream { readonly readable: ReadableStream; readonly writable: WritableStream; } /** * The TransformStream class as [specified by WHATWG](https://streams.spec.whatwg.org/#ts-class) * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/TransformStream | TransformStream on MDN} * @group Streams API */ declare var TransformStream: { prototype: TransformStream; new ( transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy, ): TransformStream; }; /** * @group Streams API */ interface TransformStreamDefaultController { readonly desiredSize: number | null; enqueue(chunk?: O): void; error(reason?: any): void; terminate(): void; } /** * @group Streams API */ declare var TransformStreamDefaultController: { prototype: TransformStreamDefaultController; new (): TransformStreamDefaultController; }; /** * @group Streams API */ interface Transformer { flush?: TransformerFlushCallback; readableType?: undefined; start?: TransformerStartCallback; transform?: TransformerTransformCallback; writableType?: undefined; } /** * @group Streams API */ interface TransformerFlushCallback { (controller: TransformStreamDefaultController): void | PromiseLike; } /** * @group Streams API */ interface TransformerStartCallback { (controller: TransformStreamDefaultController): void | PromiseLike; } /** * @group Streams API */ interface TransformerTransformCallback { ( chunk: I, controller: TransformStreamDefaultController, ): void | PromiseLike; } /** * @group Fetch API */ type HeadersInit = Headers | string[][] | Record; /** * The Headers class as [specified by WHATWG](https://fetch.spec.whatwg.org/#headers-class) * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Headers | Headers on MDN} * @group Fetch API */ interface Headers { append(name: string, value: string): void; delete(name: string): void; get(name: string): string | null; getSetCookie(): string[]; has(name: string): boolean; set(name: string, value: string): void; forEach( callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any, ): void; // Iterable methods entries(): IterableIterator<[string, string]>; keys(): IterableIterator; values(): IterableIterator; [Symbol.iterator](): Iterator<[string, string]>; } /** * @group Fetch API */ declare var Headers: { prototype: Headers; new (init?: HeadersInit): Headers; }; /** * The atob() function decodes a string of data which has been encoded using Base64 encoding. * * @param data A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data. * @returns An ASCII string containing decoded data from `data`. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/atob | atob on MDN} * @group Encoding API */ declare function atob(data: string): string; /** * The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data). * @param data The binary string to encode. * @returns An ASCII string containing the Base64 representation of `data`. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/btoa | btoa on MDN} * @group Encoding API */ declare function btoa(data: string): string; /** * The setTimeout() method sets a timer which calls a function once the timer expires. * * @param callback A function to be called after the timer expires. * @param delay The time, in milliseconds, that the timer should wait before calling the specified function. Defaults to 0 if not specified. * @param args Additional arguments which are passed through to the callback function. * @returns A numeric, non-zero value which identifies the timer created; this value can be passed to clearTimeout() to cancel the timeout. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/setTimeout | setTimeout on MDN} * @group Timers */ declare function setTimeout( callback: (...args: TArgs) => void, delay?: number, ...args: TArgs ): number; /** * The clearTimeout() method cancels a timeout previously established by calling setTimeout(). If the parameter provided does not identify a previously established action, this method does nothing. * @param timeoutID The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to setTimeout(). * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout | clearTimeout on MDN} * @group Timers */ declare function clearTimeout(timeoutID?: number): void; /** * The setInterval() method repeatedly calls a function, with a fixed time delay between each call. * This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval(). * * @param callback A function to be called every delay milliseconds. The first call happens after delay milliseconds. * @param delay The time, in milliseconds, that the timer should delay in between calls of the specified function. Defaults to 0 if not specified. * @param args Additional arguments which are passed through to the callback function. * @returns A numeric, non-zero value which identifies the timer created; this value can be passed to clearInterval() to cancel the interval. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/setInterval | setInterval on MDN} * @group Timers */ declare function setInterval( callback: (...args: TArgs) => void, delay?: number, ...args: TArgs ): number; /** * The clearInterval() method cancels a timed, repeating action which was previously established by a call to setInterval(). If the parameter provided does not identify a previously established action, this method does nothing. * @param intervalID The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to setInterval(). * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/clearInterval | clearInterval on MDN} * @group Timers */ declare function clearInterval(intervalID?: number): void; /** * Fetch resources from backends. * * **Note**: Fastly Compute requires all outgoing requests to go to a predefined * {@link https://developer.fastly.com/reference/glossary#term-backend | backend}, passed in * via the {@link RequestInit.backend | backend} property on the `init` object. * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch on MDN} * * @param resource - The resource to fetch, either a URL string or a {@link Request} object * @param init - An object containing settings to apply to the request * @group Fetch API */ declare function fetch( input: RequestInfo | URL, init?: RequestInit, ): Promise; /** * @group Scheduling */ interface VoidFunction { (): void; } /** * @group Scheduling */ declare function queueMicrotask(callback: VoidFunction): void; /** * @group DOM APIs */ declare function structuredClone( value: any, options?: StructuredSerializeOptions, ): any; /** * @group DOM APIs */ interface StructuredSerializeOptions { transfer?: Transferable[]; } /** * @group DOM APIs */ type Transferable = ArrayBuffer; // type Transferable = ArrayBuffer | MessagePort | ImageBitmap; /** * The absolute location of the script executed by the Worker. * * Available via the global {@link location} property. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WorkerLocation | WorkerLocation on MDN} * @group Web APIs */ interface WorkerLocation { /** The fragment identifier (`#` followed by the fragment) of the worker's URL. */ readonly hash: string; /** The host (hostname and port) of the worker's URL. */ readonly host: string; /** The hostname of the worker's URL. */ readonly hostname: string; /** The serialized URL of the worker's location. */ readonly href: string; /** Returns the serialized URL. Synonym for {@link WorkerLocation.href}. */ toString(): string; /** The origin of the worker's URL. */ readonly origin: string; /** The pathname of the worker's URL. */ readonly pathname: string; /** The port of the worker's URL. */ readonly port: string; /** The protocol scheme of the worker's URL. */ readonly protocol: string; /** The query string (`?` followed by parameters) of the worker's URL. */ readonly search: string; } /** * The WorkerLocation class as [specified by WHATWG](https://html.spec.whatwg.org/multipage/workers.html#worker-locations) * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WorkerLocation | WorkerLocation on MDN} * @group Web APIs */ declare var WorkerLocation: { prototype: WorkerLocation; new (): WorkerLocation; }; /** * @group Web APIs */ declare var location: WorkerLocation; interface Algorithm { name: string; } type AlgorithmIdentifier = Algorithm | string; type BufferSource = ArrayBufferView | ArrayBuffer; declare class SubtleCrypto { constructor(); // decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; // deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; // deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise; digest( algorithm: AlgorithmIdentifier, data: BufferSource, ): Promise; // encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; // exportKey(format: "jwk", key: CryptoKey): Promise; // exportKey(format: Exclude, key: CryptoKey): Promise; // generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray): Promise; // generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray): Promise; // generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise; // importKey(format: "jwk", keyData: JsonWebKey, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: ReadonlyArray): Promise; importKey( format: 'jwk', keyData: JsonWebKey, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams, extractable: boolean, keyUsages: ReadonlyArray, ): Promise; importKey( format: Exclude, keyData: BufferSource, algorithm: | AlgorithmIdentifier | RsaHashedImportParams // | EcKeyImportParams | HmacImportParams, // | AesKeyAlgorithm extractable: boolean, keyUsages: KeyUsage[], ): Promise; // sign(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, key: CryptoKey, data: BufferSource): Promise; sign( algorithm: AlgorithmIdentifier, key: CryptoKey, data: BufferSource, ): Promise; // unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise; // verify(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, key: CryptoKey, signature: BufferSource, data: BufferSource): Promise; verify( algorithm: AlgorithmIdentifier, key: CryptoKey, signature: BufferSource, data: BufferSource, ): Promise; // wrapKey(format: KeyFormat, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams): Promise; } interface HmacImportParams extends Algorithm { hash: HashAlgorithmIdentifier; length?: number; } interface RsaHashedImportParams extends Algorithm { hash: HashAlgorithmIdentifier; } type HashAlgorithmIdentifier = AlgorithmIdentifier; interface EcKeyImportParams { name: 'ECDSA'; namedCurve: 'P-256' | 'P-384' | 'P-521'; } interface JsonWebKey { alg?: string; crv?: string; d?: string; dp?: string; dq?: string; e?: string; ext?: boolean; k?: string; key_ops?: string[]; kty?: string; n?: string; oth?: RsaOtherPrimesInfo[]; p?: string; q?: string; qi?: string; use?: string; x?: string; y?: string; } interface RsaOtherPrimesInfo { d?: string; r?: string; t?: string; } /** * The Crypto interface as [specified by WHATWG](https://w3c.github.io/webcrypto/#crypto-interface) * Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Crypto | Crypto on MDN} * @group Web Crypto APIs */ interface Crypto { readonly subtle: SubtleCrypto; getRandomValues(array: T): T; randomUUID(): string; } /** * @group Web Crypto APIs */ declare var Crypto: { prototype: Crypto; new (): Crypto; }; /** * @group Web Crypto APIs */ declare var crypto: Crypto; /** * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) */ interface CryptoKey { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ readonly algorithm: KeyAlgorithm; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ readonly extractable: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ readonly type: KeyType; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ readonly usages: KeyUsage[]; } declare var CryptoKey: { prototype: CryptoKey; new (): CryptoKey; }; interface KeyAlgorithm { name: string; } type KeyFormat = | 'jwk' // | "pkcs8" | 'raw'; // | "spki"; type KeyType = 'private' | 'public' | 'secret'; type KeyUsage = | 'decrypt' | 'deriveBits' | 'deriveKey' | 'encrypt' | 'sign' | 'unwrapKey' | 'verify' | 'wrapKey'; interface EventInit { bubbles?: boolean; cancelable?: boolean; composed?: boolean; } interface EventListenerOptions { capture?: boolean; } interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; passive?: boolean; // signal?: AbortSignal; } /** * An event which takes place in the DOM. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) */ interface Event { /** * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) */ readonly bubbles: boolean; /** * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) */ cancelBubble: boolean; /** * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) */ readonly cancelable: boolean; /** * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) */ readonly composed: boolean; /** * Returns the object whose event listener's callback is currently being invoked. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) */ readonly currentTarget: EventTarget | null; /** * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) */ readonly defaultPrevented: boolean; /** * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) */ readonly eventPhase: number; /** * Returns true if event was dispatched by the user agent, and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) */ readonly isTrusted: boolean; /** * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) */ returnValue: boolean; /** * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) */ readonly srcElement: EventTarget | null; /** * Returns the object to which event is dispatched (its target). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) */ readonly target: EventTarget | null; /** * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) */ readonly timeStamp: DOMHighResTimeStamp; /** * Returns the type of event, e.g. "click", "hashchange", or "submit". * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) */ readonly type: string; /** * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) */ composedPath(): EventTarget[]; /** * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/initEvent) */ initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; /** * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) */ preventDefault(): void; /** * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) */ stopImmediatePropagation(): void; /** * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) */ stopPropagation(): void; readonly NONE: 0; readonly CAPTURING_PHASE: 1; readonly AT_TARGET: 2; readonly BUBBLING_PHASE: 3; } declare var Event: { prototype: Event; new (type: string, eventInitDict?: EventInit): Event; readonly NONE: 0; readonly CAPTURING_PHASE: 1; readonly AT_TARGET: 2; readonly BUBBLING_PHASE: 3; }; interface EventListener { (evt: Event): void; } interface EventListenerObject { handleEvent(object: Event): void; } type EventListenerOrEventListenerObject = EventListener | EventListenerObject; /** * EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) * @group DOM Events */ interface EventTarget { /** * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. * * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. * * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. * * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. * * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. * * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. * * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) */ addEventListener( type: string, callback: EventListenerOrEventListenerObject | null, options?: AddEventListenerOptions | boolean, ): void; /** * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ dispatchEvent(event: Event): boolean; /** * Removes the event listener in target's event listener list with the same type, callback, and options. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) */ removeEventListener( type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean, ): void; } declare var EventTarget: { prototype: EventTarget; new (): EventTarget; }; /** * Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance) * @group Performance APIs */ interface Performance extends EventTarget { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/timeOrigin) */ readonly timeOrigin: DOMHighResTimeStamp; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now) */ now(): DOMHighResTimeStamp; } /** * @group Performance APIs */ declare var Performance: { prototype: Performance; new (): Performance; }; /** * @group Performance APIs */ declare var performance: Performance; type DOMHighResTimeStamp = number; ================================================ FILE: types/html-rewriter.d.ts ================================================ declare module 'fastly:html-rewriter' { /** * Lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the * selector is encountered, the rewriter calls your callback, which can manipulate the element's * attributes and add or remove content from the immediate context. * * `HTMLRewritingStream` implements `TransformStream`, so you can pipe an HTML response body * through it using `pipeThrough`. * * @example * ```js * import { HTMLRewritingStream } from 'fastly:html-rewriter'; * * async function handleRequest(event) { * let transformer = new HTMLRewritingStream() * .onElement("h1", e => e.prepend("Header: ")) * .onElement("div", e => e.setAttribute("special-attribute", "top-secret")); * let body = (await fetch("https://example.com/")).body.pipeThrough(transformer); * * return new Response(body, { * status: 200, * headers: new Headers({ * "content-type": "text/html; charset=utf-8", * }) * }); * } * * addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); * ``` * * @version 3.35.0 */ export class HTMLRewritingStream implements TransformStream { constructor(); /** * Registers a callback for elements matching the given CSS selector. The callback is called * once for each matching element. Elements added by handlers will not be processed by other * handlers. * * Supported CSS selectors: * * | Pattern | Description | * |---|---| * | `*` | Any element | * | `E` | All elements of type `E` | * | `E F` | `F` elements inside `E` elements | * | `E > F` | `F` elements directly inside `E` elements | * | `E:nth-child(n)` | The n-th child of type `E` | * | `E:first-child` | First child of type `E` | * | `E:nth-of-type(n)` | The n-th sibling of type `E` | * | `E:first-of-type` | First sibling of type `E` | * | `E:not(s)` | Type `E` elements not matching selector `s` | * | `E.myclass` | Type `E` elements with class `"myclass"` | * | `E#myid` | Type `E` elements with ID `"myid"` | * | `E[attr]` | Type `E` elements with attribute `attr` | * | `E[attr="val"]` | Type `E` elements where `attr` is `"val"` | * | `E[attr="val" i]` | Case-insensitive match | * | `E[attr="val" s]` | Case-sensitive match | * | `E[attr~="val"]` | `attr` contains `"val"` in a space-separated list | * | E[attr\|="val"] | `attr` is hyphen-separated and starts with `"val"` | * | `E[attr^="val"]` | `attr` starts with `"val"` | * | `E[attr$="val"]` | `attr` ends with `"val"` | * | `E[attr*="val"]` | `attr` contains `"val"` | * * @param selector CSS selector string * @param handler Function called with each matching Element * @returns The HTMLRewritingStream instance for chaining * @throws `Error` If the provided selector is not a valid CSS selector or * if the handler is not a function. */ onElement(selector: string, handler: (element: Element) => void): this; /** * The writable stream to which HTML content should be written. */ writable: WritableStream; /** * The readable stream from which transformed HTML content can be read. */ readable: ReadableStream; } /** * Options for content insertion and replacement methods on {@link Element}. * * @version 3.35.0 */ export interface ElementRewriterOptions { /** * If `true`, any HTML markup in the content will be escaped so it is safe to insert as text. */ escapeHTML?: boolean; } /** * Represents an HTML element encountered during rewriting. Passed to the callback registered * via {@link HTMLRewritingStream.onElement}. * * @version 3.35.0 */ export class Element { /** * The CSS selector that matched this element. */ readonly selector: string; /** * The tag name of this element. */ readonly tag: string; /** * Sets an attribute on the element. If the attribute already exists, its value is updated. * @param name Attribute name * @param value Attribute value */ setAttribute(name: string, value: string): void; /** * Gets the value of an attribute. * @param name Attribute name * @returns The attribute value, or `null` if the attribute is not present. */ getAttribute(name: string): string | null; /** * Removes an attribute from the element. * @param name Attribute name */ removeAttribute(name: string): void; /** * Replaces the element and its children with new content. * @param content Replacement HTML or text * @param options Optional rewriting options */ replaceWith(content: string, options?: ElementRewriterOptions): void; /** * Replaces the element's children with new content, keeping the element's tags. * @param content Replacement HTML or text * @param options Optional rewriting options */ replaceChildren(content: string, options?: ElementRewriterOptions): void; /** * Inserts content before the element's opening tag. * @param content HTML or text to insert * @param options Optional rewriting options */ before(content: string, options?: ElementRewriterOptions): void; /** * Inserts content after the element's closing tag. * @param content HTML or text to insert * @param options Optional rewriting options */ after(content: string, options?: ElementRewriterOptions): void; /** * Inserts content at the beginning of the element's children. * @param content HTML or text to prepend * @param options Optional rewriting options */ prepend(content: string, options?: ElementRewriterOptions): void; /** * Inserts content at the end of the element's children. * @param content HTML or text to append * @param options Optional rewriting options */ append(content: string, options?: ElementRewriterOptions): void; } } ================================================ FILE: types/image-optimizer.d.ts ================================================ declare module 'fastly:image-optimizer' { /** * A color, either a 3 or 6 character hexadecimal string, or an object with RGB(A) components. * * When specified as an object: * - `r`, `g`, `b` are integers (0-255) * - `a` is an optional alpha value (0.0-1.0) */ type Color = | string | { r: number; g: number; b: number; a?: number; }; /** * A percentage, expressed as a string containing a number suffixed with a percent sign * (e.g. `'50%'`). */ type Percentage = string; /** * The size of a region, specified as either absolute dimensions or a ratio. * Exactly one of `absolute` or `ratio` must be provided. */ interface Size { /** * Absolute dimensions, with width and height as integer pixel values or percentage strings. */ absolute?: { width: number | Percentage; height: number | Percentage; }; /** * Aspect ratio, with width and height as numbers. */ ratio?: { width: number; height: number; }; } /** * The position of a region. Provide exactly one of `x`/`offsetX` and exactly one of * `y`/`offsetY`. */ interface Position { /** Absolute x position as integer pixels or percentage string. */ x?: number | Percentage; /** X offset as a percentage number. */ offsetX?: number; /** Absolute y position as integer pixels or percentage string. */ y?: number | Percentage; /** Y offset as a percentage number. */ offsetY?: number; } /** * Pixel or percentage values for each side of an image. */ interface Sides { top: number | Percentage; bottom: number | Percentage; left: number | Percentage; right: number | Percentage; } /** * Where image optimizations should occur. * * @version 3.36.0 */ var Region: { UsEast: 'us_east'; UsCentral: 'us_central'; UsWest: 'us_west'; EuCentral: 'eu_central'; EuWest: 'eu_west'; Asia: 'asia'; Australia: 'australia'; }; /** * Enable optimization features automatically based on browser support. * * @version 3.36.0 */ var Auto: { /** If the browser's Accept header indicates compatibility, deliver an AVIF image. */ AVIF: 'avif'; /** If the browser's Accept header indicates compatibility, deliver a WebP image. */ WEBP: 'webp'; }; /** * Algorithm for converting an image to black and white. * * @version 3.36.0 */ var BWAlgorithm: { /** Uses a luminance threshold to convert the image to black and white. */ Threshold: 'threshold'; /** Uses Atkinson dithering to convert the image to black and white. */ Atkinson: 'atkinson'; }; /** * Mode for content-aware cropping. * * @version 3.36.0 */ var CropMode: { /** Content-aware cropping that intelligently focuses on the most important visual content, including face detection. */ Smart: 'smart'; /** Allow cropping out-of-bounds regions. */ Safe: 'safe'; }; /** * Disable features that are enabled by default. * * @version 3.36.0 */ var Disable: { /** Prevent images being resized larger than the source image. */ Upscale: 'upscale'; }; /** * Enable features that are disabled by default. * * @version 3.36.0 */ var Enable: { /** Allow images to be resized larger than the source image. */ Upscale: 'upscale'; }; /** * How the image will fit within the size bounds provided. * * @version 3.36.0 */ var Fit: { /** Resize to fit entirely within the specified region, making one dimension smaller if needed. */ Bounds: 'bounds'; /** Resize to entirely cover the specified region, making one dimension larger if needed. */ Cover: 'cover'; /** Resize and crop centrally to exactly fit the specified region. */ Crop: 'crop'; }; /** * Output image format. * * @version 3.36.0 */ var Format: { /** Automatically use the best format based on browser support and image/transform characteristics. */ Auto: 'auto'; /** AVIF. */ AVIF: 'avif'; /** Baseline JPEG. */ BJPG: 'bjpg'; /** Graphics Interchange Format. */ GIF: 'gif'; /** JPEG. */ JPG: 'jpg'; /** JPEG XL. */ JXL: 'jxl'; /** MP4 (H.264). */ MP4: 'mp4'; /** Progressive JPEG. */ PJPG: 'pjpg'; /** Progressive JPEG XL. */ PJXL: 'pjxl'; /** Portable Network Graphics. */ PNG: 'png'; /** PNG palette image with 256 colors and 8-bit transparency. */ PNG8: 'png8'; /** Scalable Vector Graphics. */ SVG: 'svg'; /** WebP. */ WEBP: 'webp'; /** WebP (Lossless). */ WEBPLL: 'webpll'; /** WebP (Lossy). */ WEBPLY: 'webply'; }; /** * Which metadata fields to preserve during transformation. * * @version 3.36.0 */ var Metadata: { /** Preserve copyright notice, creator, credit line, licensor, and web statement of rights fields. */ Copyright: 'copyright'; /** Preserve the C2PA manifest and add any transformations performed by Fastly Image Optimizer. */ C2PA: 'c2pa'; /** Preserve both copyright and C2PA metadata. */ CopyrightAndC2PA: 'copyright,c2pa'; }; /** * Automatic quality compression level. * * @version 3.36.0 */ var Optimize: { /** Output image quality will be similar to the input image quality. */ Low: 'low'; /** More optimization is allowed; attempts to preserve visual quality. */ Medium: 'medium'; /** Minor visual artifacts may be visible; produces the smallest file. */ High: 'high'; }; /** * Cardinal orientation of the image (EXIF orientation values). * * @version 3.36.0 */ var Orient: { Default: '1'; FlipHorizontal: '2'; FlipHorizontalAndVertical: '3'; FlipVertical: '4'; FlipHorizontalOrientLeft: '5'; OrientRight: '6'; FlipHorizontalOrientRight: '7'; OrientLeft: '8'; }; /** * H.264 profile class when converting to video. * * @version 3.36.0 */ var Profile: { /** Recommended for video conferencing and mobile applications. (Default) */ Baseline: 'baseline'; /** Recommended for standard-definition broadcasts. */ Main: 'main'; /** Recommended for high-definition broadcasts. */ High: 'high'; }; /** * Resize filter algorithm. * * @version 3.36.0 */ var ResizeFilter: { /** Uses the value of nearby translated pixel values. */ Nearest: 'nearest'; /** Uses an average of a 2x2 environment of pixels. */ Bilinear: 'bilinear'; /** Same as Bilinear. */ Linear: 'linear'; /** Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher. */ Bicubic: 'bicubic'; /** Same as Bicubic. */ Cubic: 'cubic'; /** Uses the Lanczos filter with sinc resampling for edge and linear feature detection. */ Lanczos2: 'lanczos2'; /** Uses a better approximation of the sinc resampling function. (Default) */ Lanczos3: 'lanczos3'; /** Same as Lanczos3. */ Lanczos: 'lanczos'; }; /** * Options for the Fastly Image Optimizer, specified via the `imageOptimizerOptions` property * in the `Request` constructor. See the * [Image Optimizer reference docs](https://www.fastly.com/documentation/reference/io/) for * detailed documentation on all options. * * @example * ```js * import { Format, Orient, CropMode, Region } from 'fastly:image-optimizer'; * * async function handleRequest(event) { * return await fetch('https://www.w3.org/Graphics/PNG/text2.png', { * imageOptimizerOptions: { * region: Region.UsEast, * format: Format.PNG, * bgColor: { r: 100, g: 255, b: 9, a: 0.5 }, * brightness: -20, * orient: Orient.FlipVertical, * crop: { size: { ratio: { width: 4, height: 3 } }, mode: CropMode.Safe }, * }, * backend: 'my-backend' * }); * } * * addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); * ``` * * @version 3.36.0 */ interface ImageOptimizerOptions { /** * Specify the region where image optimizations should occur. This is the only required option. */ region: | 'us_east' | 'us_central' | 'us_west' | 'eu_central' | 'eu_west' | 'asia' | 'australia'; /** * Enable optimization features automatically based on browser support. */ auto?: 'avif' | 'webp'; /** * Set the background color of an image. */ bgColor?: Color; /** * Set the blurriness of the output image. Number values are in the range 0.5-1000; * percentage strings are also accepted. */ blur?: number | Percentage; /** * Set the brightness of the output image (-100 to 100). */ brightness?: number; /** * Convert an image to black and white using a given algorithm. */ bw?: 'threshold' | 'atkinson'; /** * Increase the size of the canvas around an image. */ canvas?: { size: Size; position?: Position; }; /** * Set the contrast of the output image (-100 to 100). */ contrast?: number; /** * Remove pixels from an image. */ crop?: { size: Size; position?: Position; mode?: 'smart' | 'safe'; }; /** * Disable features that are enabled by default. */ disable?: 'upscale'; /** * Set the ratio between physical pixels and logical pixels (1-10). */ dpr?: number; /** * Enable features that are disabled by default. */ enable?: 'upscale'; /** * Set how the image will fit within the size bounds provided. */ fit?: 'bounds' | 'cover' | 'crop'; /** * Specify the output format to convert the image to. */ format?: | 'auto' | 'avif' | 'bjpg' | 'gif' | 'jpg' | 'jxl' | 'mp4' | 'pjpg' | 'pjxl' | 'png' | 'png8' | 'svg' | 'webp' | 'webpll' | 'webply'; /** * Extract the first frame from an animated image sequence. */ frame?: 1; /** * Resize the height of the image, as integer pixels or a percentage string. */ height?: number | Percentage; /** * Specify the level constraints when converting to video. Must be one of: * `"1.0"`, `"1.1"`, `"1.2"`, `"1.3"`, `"2.0"`, `"2.1"`, `"2.2"`, `"3.0"`, `"3.1"`, * `"3.2"`, `"4.0"`, `"4.1"`, `"4.2"`, `"5.0"`, `"5.1"`, `"5.2"`, `"6.0"`, `"6.1"`, * or `"6.2"`. */ level?: string; /** * Control which metadata fields are preserved during transformation. */ metadata?: 'copyright' | 'c2pa' | 'copyright,c2pa'; /** * Automatically apply optimal quality compression. */ optimize?: 'low' | 'medium' | 'high'; /** * Change the cardinal orientation of the image. */ orient?: '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8'; /** * Add pixels to the edge of an image. */ pad?: Sides; /** * Remove pixels from an image before any other transformations occur. */ precrop?: { size: Size; position?: Position; mode?: 'smart' | 'safe'; }; /** * Specify the H.264 profile class when converting to video. */ profile?: 'baseline' | 'main' | 'high'; /** * Optimize the image to the given compression level for lossy file formatted images (0-100). */ quality?: number; /** * Specify the resize filter used when resizing images. */ resizeFilter?: | 'nearest' | 'bilinear' | 'linear' | 'bicubic' | 'cubic' | 'lanczos2' | 'lanczos3' | 'lanczos'; /** * Set the saturation of the output image (-100 to 100). */ saturation?: number; /** * Set the sharpness of the output image. */ sharpen?: { /** Sharpening amount (0-10). */ amount: number; /** Sharpening radius (0.5-1000). */ radius: number; /** Sharpening threshold (0-255). */ threshold: number; }; /** * Remove pixels from the edge of an image. */ trim?: Sides; /** * Trim pixels from the image edges that match the specified color. Either a {@link Color} * value, or an object with `color` and optional `threshold` (0-1) properties. */ trimColor?: | Color | { color: Color; /** Tolerance for color matching (0-1). */ threshold?: number; }; /** * Remove explicit width and height properties in SVG output. */ viewbox?: 1; /** * Resize the width of the image, as integer pixels or a percentage string. */ width?: number | Percentage; } /** * Convert image optimizer options into the query string that is sent to the image optimizer, * for logging and debugging purposes. * * @version 3.36.0 */ function optionsToQueryString(options: ImageOptimizerOptions): string; } ================================================ FILE: types/index.d.ts ================================================ /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ================================================ FILE: types/index.js ================================================ export {}; ================================================ FILE: types/kv-store.d.ts ================================================ /// declare module 'fastly:kv-store' { /** * Class for accessing a [Fastly KV store](https://developer.fastly.com/reference/api/kv-store/). * * A KV store is a persistent, globally consistent key-value store. See * [Data stores for Fastly services](https://developer.fastly.com/learning/concepts/edge-state/data-stores#kv-stores) * for initialization and usage details. * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @example * In this example we connect to a KV store named `'files'`, save an entry to the store * under the key `'hello'` and then read back the value and return it to the client. * * ```js * /// * * import { KVStore } from "fastly:kv-store"; * * async function app(event) { * const files = new KVStore('files') * * await files.put('hello', 'world') * * const entry = await files.get('hello') * * return new Response(await entry.text()) * } * * addEventListener("fetch", (event) => event.respondWith(app(event))) * * ``` */ export class KVStore { /** * Creates a new JavaScript KVStore object which interacts with the Fastly KV store named `name`. * * @param name Name of the Fastly KV store to interact with. A name cannot be empty, contain * control characters, or be longer than 255 characters. * @throws `TypeError` if no KV store exists with the provided name, or the name is empty, * longer than 255 characters, does not start with an ASCII alphabetical character, * or contains control characters (`\u0000-\u001F`). */ constructor(name: string); /** * Delete the value associated with the key `key` in the KV store. * * @param key The key to delete from within the KV store. A key cannot: * - Be any of the strings "", ".", or ".." * - Start with the string ".well-known/acme-challenge/" * - Contain any of the characters "#;?^|\n\r" * - Be longer than 1024 characters * @throws `TypeError` if the key violates any of the above constraints. * @version 3.13.0 */ delete(key: string): Promise; /** * Gets the value associated with the key `key` in the KV store. * * When the key is present, a resolved `Promise` containing a `KVStoreEntry` will be returned * which contains the associated value. When the key is absent, a resolved `Promise` * containing `null` is returned. * * @param key The key to retrieve from within the KV store. A key cannot: * - Be any of the strings "", ".", or ".." * - Start with the string ".well-known/acme-challenge/" * - Contain any of the characters "#;?^|\n\r" * - Be longer than 1024 characters * @throws Throws `TypeError` if the key violates any of the above constraints. */ get(key: string): Promise; /** * Write the value of `value` into the KV store under the key `key`. * * Note: KV store is eventually consistent, this means that the updated contents associated * with the key `key` may not be available to read from all edge locations immediately and * some edge locations may continue returning the previous contents associated with the key. * * @param key The key to associate with the value in the KV store. A key cannot: * - Be any of the strings "", ".", or ".." * - Start with the string ".well-known/acme-challenge/" * - Contain any of the characters "#;?^|\n\r" * - Be longer than 1024 characters * @param value The value to store within the KV store. Maximum size is 30 MB. * @throws `TypeError` if the key violates any of the above constraints or * if `gen` is provided and is not a positive integer. */ put( key: string, value: BodyInit, options?: { /** * Binary metadata to associate with the entry, up to 1000 bytes. * * If passing a string, UTF-8 encoding is used. * * @version 3.26.0 */ metadata?: ArrayBufferView | ArrayBuffer | string; /** * TTL (time-to-live) for the entry, in seconds. * * @version 3.26.0 */ ttl?: number; /** * Insert mode, defaults to `'overwrite'`. * - `'overwrite'`: Replace any existing value for the key. * - `'add'`: Only insert if the key does not already exist. * - `'append'`: Append to any existing value for the key. * - `'prepend'`: Prepend to any existing value for the key. * * @version 3.26.0 */ mode?: 'overwrite' | 'add' | 'append' | 'prepend'; /** * Generation counter for conditional writes. The write only succeeds if the * current generation of the entry matches this value. Must be a positive integer. * * @version 3.31.0 */ gen?: number; }, ): Promise; /** * List keys in the KV store, optionally filtered by prefix. * * @param options Options for filtering and paginating the key list. * @returns A `Promise` resolving with the list of keys and a cursor for pagination. * @version 3.26.0 */ list(options?: { /** * Do not wait to sync the key list, and instead immediately return the current * cached key list. May be faster but possibly out of date. */ noSync?: boolean; /** * String prefix for keys to list. */ prefix?: string; /** * Limit the number of keys provided per listing. */ limit?: number; /** * The base64 cursor string representing the last listing operation. */ cursor?: string; }): Promise<{ list: string[]; /** * Pass this base64 cursor into a subsequent list call to obtain the next listing. * * The cursor is `undefined` when the end of the list is reached. */ cursor: string | undefined; }>; } /** * Class for interacting with a [Fastly KV store](https://developer.fastly.com/reference/api/kv-store/) entry. */ interface KVStoreEntry { /** * A ReadableStream with the contents of the entry. */ get body(): ReadableStream; /** * A boolean value that indicates whether the body has been read from already. */ get bodyUsed(): boolean; /** * Reads the body and returns it as a promise that resolves with a string. * The response is always decoded using UTF-8. */ text(): Promise; /** * Reads the body and returns it as a promise that resolves with the result of parsing the body text as JSON. */ json(): Promise; /** * Reads the body and returns it as a promise that resolves with an ArrayBuffer. */ arrayBuffer(): Promise; /** * Binary metadata associated with this entry, up to 1000 bytes. * * Returns `null` if no metadata is set. * * @version 3.26.0 */ metadata(): ArrayBuffer | null; /** * Metadata associated with this entry, decoded as a UTF-8 string. * * Returns `null` if no metadata is set. * * @throws If the metadata is not valid UTF-8. * @version 3.26.0 */ metadataText(): string | null; } } ================================================ FILE: types/logger.d.ts ================================================ declare module 'fastly:logger' { /** * Class for connecting to [Fastly named log endpoints](https://developer.fastly.com/learning/integrations/logging/). * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @example * In this example we create a logger named `"splunk"` and log the incoming request method * and destination. * * ```js * /// * import { Logger } from "fastly:logger"; * * async function app(event) { * let logger = new Logger("splunk"); * logger.log(JSON.stringify({ * method: event.request.method, * url: event.request.url * })); * * return new Response('OK'); * } * * addEventListener("fetch", event => event.respondWith(app(event))); * ``` */ export class Logger { /** * Creates a new Logger instance for the given * [named log endpoint](https://developer.fastly.com/learning/integrations/logging). * * @param name The name of the Fastly log endpoint to associate with this Logger instance. */ constructor(name: string); /** * Send the given message, converted to a string, to this Logger instance's endpoint. */ log(message: any): void; } interface ConsoleLoggingOptions { /** * Whether to output string prefixes "Log: " | "Debug: " | "Info: " | "Warn: " | "Error: " * before messages. * * Defaults to false. */ prefixing?: boolean; /** * Whether to use stderr for `console.warn` and `console.error` messages. * * Defaults to false. */ stderr?: boolean; } /** * Configure the behaviour of `console.log` and related console logging functions. * @version 3.28.0 */ export function configureConsole(loggingOptions: ConsoleLoggingOptions): void; } ================================================ FILE: types/secret-store.d.ts ================================================ declare module 'fastly:secret-store' { /** * Class for accessing a [Fastly secret store](https://developer.fastly.com/reference/api/services/resources/secret-store/). * * A secret store is a persistent, globally distributed store for secrets accessible to * Fastly Compute services during request processing. * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @example * In this example we connect to a secret store named `'secrets'` and retrieve a secret * named `'cat-api-key'` to use in a request header. * * ```js * /// * * import { SecretStore } from "fastly:secret-store"; * * async function app(event) { * const secrets = new SecretStore('secrets') * * const catApiKey = await secrets.get('cat-api-key') * * return fetch('/api/cat', { * headers: { * 'cat-api-key': catApiKey.plaintext() * } * }) * } * * addEventListener("fetch", (event) => event.respondWith(app(event))) * ``` */ class SecretStore { /** * Creates a new `SecretStore` object which interacts with the Fastly secret store named `name`. * * @param name Name of the Fastly secret store to interact with. A name cannot be empty, * longer than 255 characters, or contain characters other than letters, numbers, dashes * (`-`), underscores (`_`), and periods (`.`). * @throws Throws `TypeError` if no secret store exists with the provided name, the name is empty, * longer than 255 characters, or contains invalid characters. */ constructor(name: string); /** * Get the value associated with the key `key` in the secret store. If the key does not * exist, the returned `Promise` resolves with `null`. * * @param key The key to retrieve. A key cannot be empty, longer than 255 characters, or * contain characters other than letters, numbers, dashes (`-`), underscores (`_`), and * periods (`.`). * @throws Throws `TypeError` if the key is empty, longer than 255 characters, or contains * invalid characters. */ get(key: string): Promise; /** * Construct a local in-memory `SecretStoreEntry` from the provided bytes, useful for * passing bytes to APIs that only accept a `SecretStoreEntry`. * * **Note**: This is not the recommended way to obtain secrets — use {@link get} instead. * * @param bytes The raw bytes to wrap as a `SecretStoreEntry`. * @version 3.15.0 */ static fromBytes(bytes: ArrayBufferView | ArrayBuffer): SecretStoreEntry; } class SecretStoreEntry { /** * Get the plaintext value of the secret as a UTF-8 string. * * **Note**: Using this method will bring the secret into user memory — avoid using it * when possible, instead passing the `SecretStoreEntry` directly. */ plaintext(): string; /** * Get the raw byte value of the secret as a Uint8Array. * * **Note**: Using this method will bring the secret into user memory — avoid using it * when possible, instead passing the `SecretStoreEntry` directly. * * @version 3.15.0 */ rawBytes(): Uint8Array; } } ================================================ FILE: types/security.d.ts ================================================ declare module 'fastly:security' { /** * Inspect a request using the [Fastly Next-Gen WAF](https://docs.fastly.com/en/ngwaf/). * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @param request The request to inspect. * @param config Configuration for the inspection. * @throws {TypeError} If `request` is not a Request instance. * @throws {TypeError} If `overrideClientIp` is not a valid IPv4 or IPv6 address. * * @example * ```js * /// * * import { inspect } from "fastly:security"; * * async function app(event) { * const res = inspect(event.request, { * corp: "my-corp", * workspace: "my-workspace" * }); * switch (res.verdict) { * case "allow": * return await fetch(event.request); * case "block": * return new Response("Request Blocked", { status: 400 }); * case "unauthorized": * return new Response("Unauthorized", { status: 401 }); * default: * return new Response("Unexpected verdict", { status: 500 }); * } * } * * addEventListener("fetch", (event) => event.respondWith(app(event))); * ``` * * @version 3.38.0 */ export function inspect( request: Request, config: InspectConfig, ): InspectResponse; /** * Configuration for {@link inspect}. * * @version 3.38.3 */ export interface InspectConfig { /** * Set a corp name for the configuration. * * This is currently required, but will be made optional in the future. */ corp: string; /** * Set a workspace name for the configuration. * * This is currently required, but will be made optional in the future. */ workspace: string; /** * Specify an explicit client IP address to inspect. Must be a valid IPv4 or IPv6 address. * * By default, `inspect` will use the IP address that made the request to the * running Compute service, but you may want to use a different IP when * service chaining or if requests are proxied from outside of Fastly's * network. */ overrideClientIp?: string; } /** * Results of inspecting a request with the Fastly Next-Gen WAF. */ export interface InspectResponse { /** WAF response status code. */ waf_response: number; /** A redirect URL returned from the WAF, if applicable. */ redirect_url?: string; /** Tags returned by the WAF. */ tags: string[]; /** * The WAF's verdict on how to handle this request. * * Known verdicts are defined in {@link InspectVerdict}, but other values * may be returned. */ verdict: InspectVerdict | string; /** How long the WAF spent determining its verdict, in milliseconds. */ decision_ms: number; } /** * Known verdict values returned by {@link inspect}. * * @version 3.38.0 */ export enum InspectVerdict { /** The request is allowed. */ Allow = 'allow', /** The request should be blocked. */ Block = 'block', /** This service is not authorized to inspect requests. */ Unauthorized = 'unauthorized', } } ================================================ FILE: types/shielding.d.ts ================================================ /// declare module 'fastly:shielding' { /** * Configuration options for shield backends returned by * {@link Shield.encryptedBackend} and {@link Shield.unencryptedBackend}. */ interface ShieldBackendConfiguration { /** * First byte timeout for the returned backend, in milliseconds. */ firstByteTimeout?: number; } /** * Represents a [Fastly shield](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations) * location, used to route requests through a designated shield POP. * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @example * ```js * /// * * import { Shield } from "fastly:shielding"; * * async function app(event) { * const shield = new Shield('wsi-australia-au'); * // If running on the shield POP, fetch from the origin directly * if (shield.runningOn()) { * return await fetch('https://my-site.com/anything', { backend: 'my-backend' }); * } * // Otherwise, route the request through the shield using an encrypted connection * return await fetch(event.request, { backend: shield.encryptedBackend() }); * } * * addEventListener("fetch", (event) => event.respondWith(app(event))) * ``` * * @version 3.37.0 */ export class Shield { /** * Load information about the given shield. * * Shield names are shield codes as listed in the * [shield locations](https://www.fastly.com/documentation/guides/concepts/shielding/#shield-locations) * documentation (e.g. `"pdx-or-us"` for Portland, OR, USA or `"paris-fr"` for Paris, France). * * @param name The shield code identifying the shield POP * @throws Throws an `Error` if no shield exists with the provided name */ constructor(name: string); /** * Returns whether the code is currently running on (or effectively on) the given shield POP. * * This may also return `true` when Fastly is routing traffic from the target shield POP to the * current POP for load balancing or performance reasons, since the result would be approximately * identical to running on the target shield itself. */ runningOn(): boolean; /** * Return a {@link backend!Backend | Backend} representing an unencrypted * connection to this shield POP. Prefer {@link encryptedBackend} unless the data is already * encrypted, as data sent over this backend travels unencrypted over the open internet. * * @param configuration Optional backend configuration */ unencryptedBackend( configuration?: ShieldBackendConfiguration, ): import('fastly:backend').Backend; /** * Return a {@link backend!Backend | Backend} representing an encrypted * connection to this shield POP. This is almost always the backend you want to use. * * @param configuration Optional backend configuration */ encryptedBackend( configuration?: ShieldBackendConfiguration, ): import('fastly:backend').Backend; } } ================================================ FILE: types/websocket.d.ts ================================================ /// declare module 'fastly:websocket' { /** * Create a {@link Response} that instructs Fastly to pass the original request through as a * WebSocket connection to the specified backend. * * **Note**: Can only be used when processing requests, not during build-time initialization. * * @example * ```js * import { createWebsocketHandoff } from "fastly:websocket"; * * async function handleRequest(event) { * const url = new URL(event.request.url); * if (url.pathname === '/stream') { * return createWebsocketHandoff(event.request, 'websocket-backend'); * } * return new Response('Not found', { status: 404 }); * } * * addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); * ``` * * @param request The request to pass through as a WebSocket connection * @param backend The name of the backend to send the request to (1–254 characters) * @throws Throws an `Error` if `request` is not a {@link Request} instance, or if `backend` is empty or longer than 254 characters * @version 3.34.0 */ function createWebsocketHandoff(request: Request, backend: string): Response; }